Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and beauty - How char type receives console input in java
How char type receives console input in java
The input of basic data types in java includes plastic input: in. nextint (); Single-precision floating-point type: in.nextfloat (); Double-precision floating-point type: in.nextdouble (); String type: in.next (); in . nextline(); So, do you think the char type is also like in. nextchar (); How's this? If you wrote this, you must have seen this error: "The method nextchar () is undefined for the type scanner". So how do you enter the char type?

Sometimes we need to use a scanner to receive character data instead of strings. For example, when we want to use the switch () statement, we can't use the string type. Switch statement: the Chinese meaning of the switch keyword is switching and conversion. Switch statement is especially suitable for judging the equality of a group of variables in conditional statements, and it is much clearer in structure than if statement.

The syntax format of the switch statement is:

Switch (expression)

Case value 1:

Function code1;

[broken; ]

Case Value 2:

Function code 2;

[broken; ]

……

Default value:

Function code1;

[broken; ]

}

Syntax description:

1, the type of expression can only be one of four types: byte, short, char and int.

2.Value 1, value 2… The value n can only be a constant or a constant, not a variable.

3. You can write any number of sentences in the function code section.

4. The 4.break keyword means interruption, which means ending the switch statement. The break statement is optional.

5. A case statement can have any number of sentences, which is a tag statement.

6. The 6.default statement can be written anywhere in the switch statement, and its function is similar to else in the if statement. Execution flow: when the value of the expression is the same as the value after the corresponding case statement, it will be executed from this position to the end of the switch statement. If a break statement is encountered during execution, the execution of the switch statement will be ended.

When using the scanner normally, you can do the following:

Scanner in = new scanner (system. in);

char c = in.next()。 charAt(0);

The following are the topics taking the analog calculator in ACM as an example:

Import java.util. *;

Public class Main {

Public static void main(String[] args){

Scanner in = new scanner (system. in);

int a = in . nextint();

int b = in . nextint();

char c = in.next()。 charAt(0);

Switch (c)

{

Case "+":

System.out.printf("%d ",a+b);

Break;

Case'-':

System.out.printf("%d ",a-b);

Break;

Case' *':

System.out.printf("%d ",a * b);

Break;

Case "/":

If (b! =0)

{

System.out.printf("%d ",a/b);

}

Break;

}

}

}