When doing online programming problems, you need to know the data input format. This can have a better grasp of data processing, do not need to put too much time on this, focus on the main algorithm logic can be. Here’s a summary for the written test.
1. Input from the terminal
How to use the Scanner class:
Scanner scanner = new Scanner(System.in);
Copy the code
Gets an input stream from the terminal, which is passed in as a parameter when Scanner initializes the object.
The Scanner class has several important methods:
Next method (read a character)
- 1, must read valid characters before you can end the input (if nothing is input, the program does not end)
- 2. The next method automatically removes whitespace encountered before entering valid characters. Only after a valid character is entered will the following input whitespace be used as a delimiter or terminator.
- The next method completes the eng to get a string with a space.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){ String next = sc.next(); System.out.println(next); }}Copy the code
NextLine method (reads a string)
- 1. The nextLine() method ends with Enter, which means that it returns all characters up to Enter.
- 2. You can get whitespace.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNextLine()){ String next = sc.nextLine(); System.out.println(next); }}Copy the code
nextInt
Read an integer. Sometimes you can get an integer directly from a terminal without having to convert a String to an int. This reduces the running time of the program.
2. The String and Char
String toChar [] : toCharArray()
Scanner sc = new Scanner(System.in);
String line = sc.nextLine();
char[] chars = line.toCharArray();
Copy the code
String to single insert character: use charAt()
Scanner sc = new Scanner(System.in);
String line = sc.nextLine();
char charAt = line.charAt(2);
Copy the code
3. The String and int
Int to String: valueOf()
int n = 10;
String s = String.valueOf(10);
System.out.println(s);
Copy the code
String to int: use integer.parseint (s);
Scanner sc = new Scanner(System.in);
String line = sc.nextLine();
int i = Integer.parseInt(line);
System.out.println(i);
Copy the code
4. Input format
Such as:
5.15 2.10
Copy the code
import java.util.Scanner;
/ * * *@author [email protected] 2018/8/24 19:27
*/
public class ScannerTest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String line = sc.nextLine();
String[] split = line.split("");
for (int i = 0; i < split.length; i++) {
String s = split[i];
int i1 = Integer.parseInt(s.split(",") [0]);
int i2 = Integer.parseInt(s.split(",") [1]);
System.out.println(i1+""+i2); }}}Copy the code
Start to do online pen test!