3 回答
First, there's no need to wrap System.out
in a PrintStream
because out
already supports formatting with format()
or printf()
methods.
Next, you need to understand that when you input a line of data you also terminate it with a new line \n
. The next<Type>()
methods only consume the <Type>
and nothing else. So, if a next<Type>()
call may match \n
, you need to skip over any extra new lines \n
with another nextLine()
before.
Here's your code with fixes:
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);
Use this:
//for a single char
char Character = sc.findWithinHorizon(".", 0).charAt(0);
//for a name with white space
System.out.print("Enter your full name: ");
String name2 = sc.next();
String surname = sc.next();
System.out.println(name2 + " " + surname);
Use Scanner.next(Pattern)
and pass Pattern.compile("[A-Za-z0-9]")
to let scanner accept only 1 character defined.
You can pass any regex as argument and check for next()
Scanner.next();
for next line with spaces