1. Receive a character from the console
This method can only get one character, cannot get other data types, and generally does not use 2 to receive a string from the console
This method can only receive strings from the console, not other data types, and convert them if you want to receive other data types:
int num = integer.parseint (str) //Suppose that Str receives a numeric string, such as 123
double x = double.parseint (str) // Suppose that Str receives a double string, such as 3.14
This method is stronger than the first, but if you want to receive other data types and you need to convert, and the code is slightly more complex, the integer and double classes used to convert the above are all wrapper classes of the basic data type, which is to wrap the basic data type into an object, followed by a special description 3, Scanner class
The scanner class is one of the most powerful forms of reception in Java and the most common way to receive arbitrary data types, using the following methods:
However, there are some problems with its use:
Question one:
When you want to receive an integer, you enter a non integer in the console, such as: A, which throws a Java.util.InputMismatchException exception.
Solution:
1, the exception handling
2, with the scanner class provides the Hasnext method:
Hasnextint () will tell you whether you entered an integer, then return True, not return false, and similar hasnextdouble () and other methods
Question two:
When you want to receive an int first and then receive a string:
You will find that you cannot enter a string;
Reason:
First we need to know how the Nextline () method gets one line: When you enter a carriage return, the end of the line is shown, and after we enter an integer and hit the carriage return, nextline () reads the carriage return, checking the method:
System.out.print ("1111111111");
System.out.print (line);
System.out.print ("2222222222");
The output results are:
1111111111
2222222222
Prove line is a carriage return
Solution:
1, create two scanner objects, but not recommended, waste of storage space
2, all with the string to receive, let it be converted to the required data type