简体   繁体   English

Java中的两个整数相加

[英]Sum two integers in Java

Im trying to sum two numbers from user input.我试图从用户输入中对两个数字求和。 But its not working但它不起作用

This is what I have done这就是我所做的

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

the error code is错误代码是

Error:(12, 17) java: variable x is already defined in method main(java.lang.String[])
Error:(13, 10) java: int cannot be dereferenced

Am I missing something here?我在这里错过了什么吗?

You reused the x and y variable names (hence the variable x is already defined in method main error), and forgot to assign the int s read from the Scanner to the x and y variables.您重用了xy变量名(因此variable x is already defined in method main error 中variable x is already defined in method main ),并且忘记将从Scanner读取的int分配给xy变量。

Besides, there's no need to create two Scanner objects.此外,无需创建两个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);
}

are you aware that the scanner and an integer are sharing the same name?你知道扫描仪和整数共享同一个名字吗?

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

that is invalid in java,think about using a more descriptive name for the scanner在 java 中无效,考虑为扫描仪使用更具描述性的名称

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM