使用用户输入更改变量

时间:2013-11-12 20:45:28

标签: java

嘿,我是Java编程的新手,我正在努力改变变量并寻求一些帮助。问题如下:

创建一个程序,询问用户三个数字,然后打印它们的总和。在程序中使用以下结构:

    // TODO code application logic here
    Scanner reader = new Scanner(System.in);
    int sum = 0;
    int read;//`enter code here`
    // WRITE YOUR PROGRAM HERE
    // USE ONLY THE VARIABLES sum, reader AND read!
    System.out.println("Sum: " + sum);

这是我在下面写的,当然我得到语法错误:

    Scanner reader = new Scanner(System.in);
    int sum = 0;
    System.out.print("Type the first Number: ");
    int read = Integer.parseInt(reader.nextLine());
    System.out.print("Type the second number: ");
    int read = read + (Integer.parseInt(reader.nextLine()));
    System.out.print("Type the third number: ");
    int read = read + (Integer.parseInt(reader.nextLine()));

    sum = read;
    System.out.println("Sum: " + sum);

3 个答案:

答案 0 :(得分:1)

您的代码应该是:

   Scanner reader = new Scanner(System.in);

    int sum = 0;
    System.out.print("Type the first Number: ");
    int read = Integer.parseInt(reader.nextLine());
    System.out.print("Type the second number: ");
    read = read + (Integer.parseInt(reader.nextLine()));
    System.out.print("Type the third number: ");
    read = read + (Integer.parseInt(reader.nextLine()));

    sum = read;
    System.out.println("Sum: " + sum);

您收到语法错误,因为您的变量read被多次声明。

您也可以使用compound assignment operator

read += (Integer.parseInt(reader.nextInt())); //using .nextInt() per @Zong Zheng Li suggestion.

答案 1 :(得分:0)

您声明变量再次读取,尝试再次声明相同的变量将产生语法错误。

int read = Integer.parseInt(reader.nextLine());
System.out.print("Type the second number: ");
read = read + (Integer.parseInt(reader.nextLine()));
System.out.print("Type the third number: ");
read = read + (Integer.parseInt(reader.nextLine()));

答案 2 :(得分:0)

package ejercicio.pkg25.cambio.de.variables.suma.de.tres.numeros;

/ **  * @author Diego Urrea  * / import java.util.Scanner;

公共课Ejercicio25CambioDeVariablesSumaDeTresNumeros {

public static void main(String[] args) {
    Scanner reader = new Scanner(System.in);
    int sum = 0;
    int read;
    System.out.println("Digita el primer número");
    read = Integer.parseInt(reader.nextLine());
    sum = sum+read;
    System.out.println("Digita el segundo número");
    read = Integer.parseInt(reader.nextLine());
    sum = sum+read;
    System.out.println("Digita el número tres");
    read = Integer.parseInt(reader.nextLine());
    sum = sum+read;
    System.out.println("Sum: " + sum);
}

}