gpt4 book ai didi

java - 通过用户输入更改变量

转载 作者:太空宇宙 更新时间:2023-11-04 07:16:12 25 4
gpt4 key购买 nike

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

最佳答案

你的代码应该是这样的:

   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.

关于java - 通过用户输入更改变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19939523/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com