1. Use of scanner
Use to introduce package import Java.util.Scanner; First define Scanner object
Scanner sc = new Scanner (system.in);
If you want to enter an integer, int n = sc.nextint ();
String, temp = Sc.next ();
Like what:
Import Java.util.Scanner;
public class Test {
public static void Main (string[] args) {
Scanner Scanner = new Scanner (system.in);
Int[] days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int month =-1;
while (true) {
try {
System.out.print ("Please enter the month:");
month = Scanner.nextint ();
if (month >= 1 && month <= 12) {
Break
}
SYSTEM.OUT.PRINTLN ("* * Please enter the correct month * *");
catch (Exception e) {
SYSTEM.OUT.PRINTLN ("* * format is wrong.) Please enter a number * * ");
Scanner.next ();
}
}
SYSTEM.OUT.PRINTLN (month + "month has:" + days[month-1] + "Day");
}
}
2. Use of BufferedReader
import Java.io.Reader should be introduced before use;
BufferedReader br = new BufferedReader (new InputStreamReader (system.in));
String input = Br.readline ();
Like what:
==================================================================================================
Import java.io.*;
public class Importtext {
public static void Main (string[] args) {
String St;
int num;
float Fnum;
try{
System.out.print ("Input:");
BufferedReader br=new BufferedReader (New InputStreamReader (system.in));
st = Br.readline ();
System.out.print ("Enter a number:");
num = Integer.parseint (Br.readline ());
System.out.print ("Enter a floating-point number:");
Fnum = Float.parsefloat (Br.readline ());
System.out.print ("Output:" +st+ ' \ n ');
System.out.print ("Output:" +num+ ' \ n ');
System.out.print ("Output:" +fnum+ ' \ n ');
}catch (IOException e) {}
}
}
==================================================================================================
Package com.s2;
Import java.io.*;
public class Input
{
public static void Main (string[] args) throws IOException
{
while (true)
{
BufferedReader buf;
String str;
BUF =new BufferedReader (New InputStreamReader (system.in));
System.out.println ("Input A string:");
Str=buf.readline ();
System.out.println ("string=" +str);
}
}
}
==================================================================================================
It should be noted that Java input data from the keyboard as a string, so to input from the keyboard and let system approval is numeric data, must be converted.
Like what:
Package com.s2;
Import java.io.*;
public class Input
{
public static void Main (string[] args) throws IOException
{
while (true)
{
int num;
BufferedReader buf;
String str;
BUF =new BufferedReader (New InputStreamReader (system.in));
System.out.println ("Input an Integer:");
Str=buf.readline ();
Num=integer.parseint (str);
System.out.println ("string=" +str);
System.out.println ("integer=" +str);
}
}
}