Entering a value in the console and using that value in your program. A library called Scanner is used to receive input to the console. Scanner uses "import java.util.Scanner". [Example]
Main.java
import java.util.Scanner;
class Main {
public static void main(String[]args) {
Scanner scanner = new Scanner(System.in); //Initialize with Scanner
String name = scanner.next(); //Receiving string input
}
}
Initialize with new Scanner (System.in) ;. Receives string input with scanner.next () ;.
First, the Scanner is initialized and put in a variable called the scanner. The Scanner calls the method using the variable assigned to this initialized one. Receive the string entered in the console with scanner.next (). [Example]
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(name + "Mr.");
}
}
When you execute the above, "Name:" will be displayed, so if you enter a character string there, it will be output as Mr. 〇〇.
Use the Scanner as before. The method that receives an integer uses the nextInt method, and the method that receives a decimal uses the nextDouble method. [Example]
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 firstName = scanner.next();
System.out.print("Last name:");
String lastName = scanner.next();
System.out.print("age:");
int age = scanner.nextInt(); //Receive an integer with the nextInt method
System.out.print("height(m):");
double height = scanner.nextDouble(); //Receive a decimal with the nextDouble method
System.out.print("body weight(kg):");
double weight = scanner.nextDouble();
Person.printData(Person.fullName(firstName, lastName), age, height, weight);
}
}
Recommended Posts