sc.nextInt();给出了sc的错误。我只是想通过分配函数并调用它们来计算x和y的总和。这只是我必须完成的任务,但不幸的是我问了我的TA,但他不知道如何解决它。
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();
}
}
答案 0 :(得分:2)
将扫描仪声明移动到setnumber方法:
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();
}
}
答案 1 :(得分:0)
将Scanner sc从主方法中删除,在类级别定义它。
答案 2 :(得分:0)
你应该了解范围。 在主方法
之外看不到扫描仪对象