Ziyad Mohammed Ziyad Mohammed - 2 months ago 14
Java Question

Error in Scanner with Integer Inputs

The sc.nextInt(); gives error for the sc. I am just trying to calculate the sum of x and y by assigning functions and calling them. It's just an assignment that I have to finish but unfortunately I asked my TA but he didn't know how to solve it.

import java.util.Scanner;
public class calculator {

int x;
int y;

public void setnumber (){
System.out.println("Please Enter X");
x = sc.nextInt ();
System.out.println("Please Enter Y");
y = sc.nextInt ();
}

public void sum (){
int sum = x + y;
System.out.println ("The Sum" + sum);
}

public static void main(String[] args) {

Scanner sc = new Scanner (System.in);
calculator sx = new calculator ();
sx.setnumber ();
sx.sum();
}
}

Answer

move the scanner declaration to the setnumber method:

import java.util.Scanner;
public class calculator {

int x;
int y;

public void setnumber (){
    Scanner sc = new Scanner (System.in);
    System.out.println("Please Enter X");
    x = sc.nextInt ();
    System.out.println("Please Enter Y");
    y = sc.nextInt ();
}

public void sum (){
    int sum = x + y;
    System.out.println ("The Sum" + sum);
}

public static void main(String[] args) {

    calculator sx = new calculator ();
    sx.setnumber ();
    sx.sum();
}
}