An external library for "entering" a value into the console and using that value in your program. This article describes how to receive a string and how to receive a number.
The procedure for receiving a character string is as follows.
In order to use Scanner, a description for loading an external library is required. First, add the description of import java.util.Scanner; above the class definition.
Main.java
import java.util.Scanner;
class Main {
public static void main (String[] args) {
System.out.print("name:");
}
}
Next, add the description Scanner scanner = new Scanner (System.in); to initialize the Scanner. The Scanner is initialized with new Scanner (System.in) and assigned to the variable scanner.
Main.java
import java.util.Scanner;
class Main {
public static void main (String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("name:");
}
}
Finally, add the description String name = scanner.next () ;. You can substitute the character string entered in the variable name by writing scanner.next ().
Main.java
import java.util.Scanner;
class Main {
public static void main (String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("name:");
String name = scanner.next();
System.out.println("Hello" + name + "Mr.");
}
}
The procedure for receiving numerical values is also as follows, but 1 and 2 are omitted because there is a common part with the procedure for receiving numerical strings.
We will add a description to receive numerical values in the following file. (Steps 1 and 2 have been completed)
Main.java
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("age:");
System.out.print("height(m):");
}
}
To receive the age value int age = scanner.nextInt(); Add the description of. The data type is specified by writing nextInt () as a difference from the procedure for receiving as a character string. Note that if you write nextString () etc. when receiving as a character string, an error will occur.
Main.java
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("age:");
int age = scanner.nextInt();
System.out.print("height(m):");
double height = scanner.nextDouble();
}
}
Recommended Posts