Sometimes we need to receive char type data with scanner instead of receiving string. For example, when we use the switch () statement, we cannot use the string type.
Switch statement:
Switch keyword in Chinese meaning is the meaning of switching, conversion, the switch statement in the conditional statement is particularly suitable for a set of variable equality of judgment, in the structure than if statement is much clearer.
The syntax format for a switch statement is:
switch (expression) {
Case value 1:
function code 1;
[Break;]
Case Value 2:
function code 2;
[Break;]
......
Default
function code 1;
[Break;]
}
Syntax Description:
1, the type of expression can only be byte, short, char and int of these 4 kinds.
2, value 1, value 2 ... Value n can only be a constant or constant, not a variable.
3, the function code part may write any many sentences.
4, break keyword meaning is interrupted, refers to the end switch statement, the breaking statement is optional.
5, Case statement can have any number of sentences, is a label statement.
6, the default statement can be written anywhere in the switch statement, functionality is similar to else in an if statement. Execution process: When the value of an expression is the same as the value after the corresponding Case statement, the execution of the switch statement ends at the end of the switch statement, and in execution, if the break statement is encountered.
When you use scanner normally, you can do this:
Guide Bag
import Java.util.Scanner;
public class textscanner{public
static void Main (String [] args) {
//Create Scanner object accept input from console
Scanner input = new Scanner (system.in);
System.out.println ("Please enter first name:");
Accept String
String name = Input.next ();
System.out.println ("Please enter the school number");
Accept int
int id = input.nextint ()//What type Next will be followed by the attention to the case
/output
System.out.println ("name: +name+" \ T-School number is: "+id);
}
}
When you receive data with a switch, you can do this:
Scanner s=new Scanner (system.in);
Char b =s.next (). charAt (0);
System.out.println (b);
Then you can use the switch.