我需要编写一个测试类来执行以下操作:
- 一个。让用户输入一个整数并显示它。
- b。让用户输入一个浮点值并显示它。
- c。让用户输入他/她的名字(没有空格)并显示
名称为:
“Hello <name>, welcome to Scanner!”
- d。让用户输入一个字符并显示它。
- e。让用户输入任何字符串(带空格)并显示它。
我的问题是,我怎样才能简单地扫描 Character
并显示它?在第 2 条中,我如何输入 String
用空格并显示它? (字母“d”和“e”)
我四处搜索,但找不到最简单的解决方案(因为我是 Java 和编程的新手)。
到目前为止,这是我的代码:
package aw; import java.io.PrintStream; import java.util.Scanner; public class NewClass1 { public static void main(String[] args) { int num; double num2; String name; char c; Scanner sc = new Scanner(System.in); PrintStream ps = new PrintStream(System.out); //for integer System.out.println("Enter a number: "); num = sc.nextInt(); ps.printf("%d\n", num); //for float System.out.println("Enter a float value: "); num2 = sc.nextDouble(); ps.printf("%.2f\n", num2); //for name w/o white space System.out.print("Enter your first name: "); name = sc.next(); ps.printf("Hello %s, welcome to Scanner\n", name); //for character System.out.print("Enter a character: "); c = sc.findWithinHorizon(".", 0).charAt(0); System.out.print(“%c”, c); //for name w/ white space System.out.print("Enter your full name: "); name = sc.nextLine(); System.out.print(“%s”, name); } }
我希望你能帮助我。谢谢!
最佳答案
首先,不需要包装 System.out
在PrintStream
因为out
已经支持使用 format()
进行格式化或 printf()
方法。
接下来,您需要了解,当您输入一行数据时,您也会用换行 终止它 \n
. next<Type>()
方法只消耗 <Type>
没有别的。所以,如果 next<Type>()
call 可能匹配 \n
,您需要跳过任何额外的新行 \n
与另一个nextLine()
之前。
这是你的修复代码:
int num;
double num2;
String name;
char c;
Scanner sc = new Scanner(System.in);
//for integer
System.out.print("Enter a number: ");
num = sc.nextInt();
System.out.printf("%d\n", num);
//for float
System.out.print("Enter a float value: ");
num2 = sc.nextDouble();
System.out.printf("%.2f\n", num2);
//for name w/o white space
System.out.print("Enter your first name: ");
name = sc.next();
System.out.printf("Hello %s, welcome to Scanner\n", name);
//for character
System.out.print("Enter a character: ");
c = sc.findWithinHorizon(".", 0).charAt(0);
System.out.printf("%c\n", c);
sc.nextLine(); // skip
//for name w/ white space
System.out.print("Enter your full name: ");
name = sc.nextLine();
System.out.printf("%s", name);
关于java - 扫描仪输入数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18045614/