1

嘿,我是 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);
4

4 回答 4

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被多次声明。

您还可以使用复合赋值运算符

read += (Integer.parseInt(reader.nextInt())); //using .nextInt() per @Zong Zheng Li suggestion.
于 2013-11-12T20:49:03.400 回答
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()));
于 2013-11-12T20:50:31.273 回答
0

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

}

于 2015-09-05T04:14:36.303 回答
0

实际上对于这个简短的问题,您甚至不需要使用read变量。

你可以这样做。

Scanner reader = new Scanner(System.in);
int sum = 0;

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

输入:

1
2
3

输出:

6
于 2015-09-05T05:13:46.543 回答