[英]Sum two integers in Java
我试图从用户输入中对两个数字求和。 但它不起作用
这就是我所做的
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
变量名(因此variable x is already defined in method main
error 中variable x is already defined in method main
),并且忘记将从Scanner
读取的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 中无效,考虑为扫描仪使用更具描述性的名称
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.