【问题标题】:Sum two integers in JavaJava中的两个整数相加
【发布时间】:2017-06-04 09:23:30
【问题描述】:

我试图对用户输入的两个数字求和。但它不起作用

这就是我所做的

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 声明为intScanner...同样适用于y...
  • 给你的变量起不同的名字。调用 everything xy 会让你和编译器都感到困惑。

标签: java variables java.util.scanner


【解决方案1】:

您重用了xy 变量名称(因此出现variable x is already defined in method main 错误),并且忘记将从Scanner 读取的ints 分配给xy 变量。

此外,无需创建两个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);
}

【讨论】:

    【解决方案2】:

    您知道扫描仪和整数共享同一个名称吗?

     int x;
     Scanner x = new Scanner(System.in);
    

    这在 java 中是无效的,请考虑为扫描仪使用更具描述性的名称

    【讨论】:

      【解决方案3】:
      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);
      }
      
      }
      

      【讨论】:

      • 虽然此代码可以解决问题,including an explanation 说明如何以及为什么解决问题将真正有助于提高您的帖子质量,并可能导致更多的赞成票。请记住,您正在为将来的读者回答问题,而不仅仅是现在提问的人。请edit您的回答添加解释并说明适用的限制和假设。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-10
      • 1970-01-01
      相关资源
      最近更新 更多