Java中的两个整数求和
我正在尝试对用户输入的两个数字求和。但它不起作用 这就是我所做的Java中的两个整数求和,java,variables,java.util.scanner,Java,Variables,Java.util.scanner,我正在尝试对用户输入的两个数字求和。但它不起作用 这就是我所做的 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
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
这里我遗漏了什么吗?您重新使用了
x
和y
变量名(因此变量x已经在方法main
错误中定义),并且忘记将从扫描仪读取的int
分配给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);
}
您是否知道扫描仪和整数共享同一名称
int x;
Scanner x = new Scanner(System.in);
这在java中是无效的,请考虑对扫描仪使用更具描述性的名称您不能将x
声明为int
和扫描仪
。。。对于y
…同样,为变量指定不同的名称。调用一切x
和y
都会让你和编译器感到困惑。虽然这段代码可以解决这个问题,但如何以及为什么解决这个问题将真正有助于提高你的文章质量,并可能导致更多的投票。请记住,你是在将来回答读者的问题,而不仅仅是现在提问的人。请在回答中添加解释,并说明适用的限制和假设。
import java.util.Scanner;
public class Output {
public static void main(String[] args)
{
/*
Step 1. Declare Variables
*/
int varX;
int varY;
int sum;
/*
Step 2. Create a Scanner to take in user input
*/
Scanner scan = new Scanner(System.in);
/*
Step 3. varX and varY will take in the next two integers the user enters
*/
varX = scan.nextInt();
varY = scan.nextInt();
sum = varX + varY;
/*
Step 4. Print out the two chosen integers and display the sum
*/
System.out.println(varX + " + " + varY + " equals " + sum);
System.out.println(sum);
}
}