gpt4 book ai didi

java - Java 中的基本输入和输出

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

我使用的是 NetBeans IDE 7.4,我是 Java 的新手,我试图让用户输入两个数字(都是双数),然后将它们存储在另一个变量中。我去过 DOZENS 个教程站点,但它们都不好。我怎样才能得到基本的输入和输出?

最佳答案

原始示例:

import java.util.Scanner;

public class TestIO {

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.println("Print something:"); // printing output
String text = scanner.nextLine(); // taking input

System.out.println("You have printed the following text: " + text);
}

}


更新:
对不起,错过了要点,你想参加 double 。给你:

import java.util.Scanner;
import java.util.InputMismatchException;

public class TestIO {

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double firstDouble = 0L;
double secondDouble = 0L;
while (true) { // take input (two doubles) until successful
System.out.println("Print two doubles (press enter after each input):");
try {
firstDouble = scanner.nextDouble();
secondDouble = scanner.nextDouble();
} catch (InputMismatchException e) {
System.out.println("Wrong input. You must print doubles.\n" +
"Depending on your locale, as a decimal separator " +
"use either a comma or a dot.\n");
scanner.nextLine(); // clearing the buffer with the wrong input
// to avoid infinite loop
continue;
}
break;
}
// Printing the user input (limiting doubles to 3 decimal places)
System.out.format("You have printed %.3f and %.3f %n",
firstDouble, secondDouble);
}
}

推荐阅读:

关于java - Java 中的基本输入和输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19759535/

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