December 21, 2020 I've used standard input in C, but never in Java. I will summarize what I studied today.
Simply put, keyboard input is called standard input. In Java, get the standard input in the in field of the Sysytem class.
The standard output is like a device for displaying data from a program, which is displayed on a display. Java uses the out field of the Syste class.
The following methods are provided in the java.util.Scanner class.
--NextLine method to get one line of input --Next method to get input up to whitespace --NextInt method to get numeric input
The nextLine method can get the input for one line up to the line feed.
Sample code
import java.util.Scanner;
public class Sample {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String str = scan.nextLine();
System.out.println(str);
scan.close();
}
}
The next method can get the input up to the whitespace character.
Sample code
import java.util.Scanner;
public class Sample {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String str1 = scan.next();
String str2 = scan.next();
System.out.println(str1);
System.out.println(str2);
scan.close();
}
}
You can get an int type number by using nextInt. There are also nextDouble and nextFloat methods to get the floating point type.
Sample code
import java.util.Scanner;
public class Sample {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int num1 = scan.nextInt();
int num2 = scan.nextInt();
int sum = num1 + num2;
//Outputs the addition of the entered numbers
System.out.println(num1 + " + " + num2 + " = " + sum);
scan.close();
}
}
Class Scanner [Introduction to Java] How to get and output standard input (Explanation of Scanner)
Recommended Posts