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

标签 java input

这是我用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/

相关文章:

java - HTC Dialer 从电话号码中删除字母

java - FreeMarker 模板中处理错误的不同方法有哪些?

java - 为什么 com.sun.media.sound 包没有记录在 Java SE 6 apidoc 中?

python - 如何在 Python 中使用用户输入调用方法

java - JSP 构造函数不可见

java - 如何正确使用 guava Closer

jquery - 使用输入框防止文本选择突出显示

java - 以两种不同的方法读取相同的输入两次

java菜单程序切换大小写避免退出如果从菜单中选择了数字

jquery - 使用 jQuery 通过 id 定位隐藏输入