gpt4 book ai didi

java - 需要帮助跳转到 Java 以及从 C++ 输入 Java

转载 作者:行者123 更新时间:2023-11-30 05:11:28 25 4
gpt4 key购买 nike

这是我用java编写的第一个程序,我还没有找到像this one for C++这样的好网站。这对我来说很困惑,因为我刚刚开始编写 java,而我刚刚来自 C++。无论如何,关于这段代码,有人可以解释如何修复此代码,因为包含 Scanner 的行和/或如何简单地接收输入,因为我还没有找到任何简单的方法来翻译 cin >> 来自 C++

public class input {
public static void main(String[] args) {
double total = 0;
Scanner in = new Scanner(System.in);
System.out.println("As you enter numbers, they will be added.");
System.out.println("Entering a non-number will stop the program.");

while (in.hasNextDouble()) {
double n = in.nextDouble();
total = total + n;
System.out.println("The total is " + total);
}
}
}

最佳答案

你的代码可以工作。只需确保您有import java.util.Scanner。与此相关的是,请使用 Eclipse 或 Netbeans,因为它们会告诉您这一点。另外,您应该将类​​名大写并将类放入包中而不是“默认包”中。我推荐“Head First Java”。

package sand1;

import java.util.Scanner;

public class Input {
public static void main(String[] args) {
double total = 0;
Scanner in = new Scanner(System.in);
System.out.println("As you enter numbers, they will be added.");
System.out.println("Entering a non-number will stop the program.");

while (in.hasNextDouble()) {
double n = in.nextDouble();
total = total + n;
System.out.println("The total is " + total);
}
}
}

这是我运行它时的输出。我想我可能会认为这是一个错误,我能够用空行按 Enter 键而不结束。

run:
As you enter numbers, they will be added.
Entering a non-number will stop the program.
12.2
The total is 12.2
43
The total is 55.2

a
BUILD SUCCESSFUL (total time: 11 seconds)

关于java - 需要帮助跳转到 Java 以及从 C++ 输入 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3240074/

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