我正在一个网站上做一个练习,我试图用三个变量将用户输入的 3 个数字相加。他们让你开始的代码是:
Scanner reader = new Scanner(System.in);
int sum = 0;
int read;
// WRITE YOUR PROGRAM HERE
// USE ONLY THE VARIABLES sum, reader AND read!
System.out.println("Sum: " + sum);
我正在考虑使用 for 循环,但我一直卡住,因为我只能使用三个变量。 扫描仪已在使用读取器。 sum 将更改值,而读取将是一个临时值。
我会用
System.out.println("Enter a number: ");
int read = Integer.parseInt(reader.nextLine());
但这只能容纳 1 个数字。任何帮助我已经卡在这个上面一段时间了。
这应该满足以下要求:
for(read = 3; read > 0; read--) {
System.out.println("Enter a number: ");
sum += Integer.parseInt(reader.nextLine());
}
这会吗?它显然不能扩展到数百个数字:
int read;
System.out.println("Enter a number: ");
read = Integer.parseInt(reader.nextLine());
sum += read;
System.out.println("Enter a second number: ");
read = Integer.parseInt(reader.nextLine());
sum += read;
System.out.println("Enter a third number: ");
read = Integer.parseInt(reader.nextLine());
sum += read;
不,这也是我所拥有的,但它没有用
完整版 - 这对我有用。
import java.util.Scanner;
public class HelloWorld {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int sum = 0;
int read;
System.out.println("Enter a number: ");
read = Integer.parseInt(reader.nextLine());
sum += read;
System.out.println("Enter a second number: ");
read = Integer.parseInt(reader.nextLine());
sum += read;
System.out.println("Enter a third number: ");
read = Integer.parseInt(reader.nextLine());
sum += read;
System.out.println("Sum: " + sum);
}
}
输出:
Enter a number:
22
Enter a second number:
10
Enter a third number:
50
Sum: 82
当然,基于 jheimbouch 所做的更简单的版本会更好:
import java.util.Scanner;
public class HelloWorld
{
public static void main(String[] args)
{
Scanner reader = new Scanner(System.in);
int sum = 0;
for(int read = 1; read <= 3; read++)
{
System.out.println("Enter number " + read + ": ");
sum += Integer.parseInt(reader.nextLine());
}
System.out.println("Sum: " + sum);
}
}