我试图从用户输入中加总两个数字。但它不起作用
这就是我所做的
import java.util.*;
public class EX2 {
public static void main(String[] args){
int x;
int y;
Scanner x = new Scanner(System.in);
x.nextInt();
Scanner y = new Scanner(System.in);
y.nextInt();
int sum = x + y;
System.out.println(x +" "+ y);
System.out.println(sum);
}
}
错误代码是
Error:(12, 17) java: variable x is already defined in method main(java.lang.String[])
Error:(13, 10) java: int cannot be dereferenced
我在这里错过了什么吗?
答案 0 :(得分:1)
您重复使用x
和y
变量名称(因此variable x is already defined in method main
错误),并忘记将int
的{{1}}读取内容分配给Scanner
x
和y
变量。
此外,无需创建两个Scanner
个对象。
public static void main(String[] args){
int x;
int y;
Scanner sc = new Scanner(System.in);
x = sc.nextInt();
y = sc.nextInt();
int sum = x + y;
System.out.println(x +" "+ y);
System.out.println(sum);
}
答案 1 :(得分:1)
您是否知道扫描仪和整数共享相同的名称?
int x;
Scanner x = new Scanner(System.in);
在java中无效,请考虑为扫描仪使用更具描述性的名称
答案 2 :(得分:0)
import java.util.Scanner;
public class Output {
public static void main(String[] args)
{
int varX;
int varY;
int sum;
Scanner scan = new Scanner(System.in);
varX = scan.nextInt();
varY = scan.nextInt();
sum = varX + varY;
System.out.println(varX + " + " + varY + " equals " + sum);
System.out.println(sum);
}
}