Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java中的两个整数求和_Java_Variables_Java.util.scanner - Fatal编程技术网

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);
}

}