一起添加3个用户输入数字

时间:2016-02-06 02:21:39

标签: java sum user-input

我正在从我试图添加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循环,但我一直卡住,因为我只能使用三个变量。阅读器已被Scanner使用。 sum将会改变值,read将是一个临时值。

我会用

System.out.println("Enter a number: ");
int read = Integer.parseInt(reader.nextLine());

但那只会有1个号码。任何帮助我已经坚持了一段时间。

2 个答案:

答案 0 :(得分:2)

这应该满足要求:

for(read = 3; read > 0; read--) {
    System.out.println("Enter a number: ");
    sum += Integer.parseInt(reader.nextLine());
}

答案 1 :(得分: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;
  

不,这也是我所拥有的,但它没有工作

完整版 - 这对我有用。

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

    }
 }