我需要编写一个测试类,实现以下功能:
- a. 允许用户输入一个整数并显示它。
- b. 允许用户输入一个浮点值并显示它。
- c. 允许用户输入他/她的名字(没有空格)并将其显示为:
“Hello <name>, welcome to Scanner!”
- d. 允许用户输入一个字符并显示它。
- e. 允许用户输入任何字符串(包括空格)并显示它。
我的问题是,如何简单地扫描只有一个Character
并显示它?在第二个问题中,如何输入带有空格的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);
}
}
我希望你能帮助我。谢谢!