这里记录JAVA输入相关的知识,后续会不定期更新。
20180306
介绍scanner 和 console
1.Scanner
scanner输入很简单,这里直接贴代码
import java.util.*;
import java.io.*;
public class InputTest{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("What is your name? ");
String name = in.nextLine();
System.out.println("What is your age?");
int age = in.nextInt();
System.out.println("Your name : " + name);
System.out.println("You will be " + (age + 1) + " next year!");
}
}
}
小结:
关于Scanner
Scanner(InputStream in)
用给定的输入流创建一个Scanner对象String nextLine()
读取输入的下一行内容String next()
读取输入的下一个单词(yi以空格作为分隔符)int nextInt()
double nextDouble()
读取并转换下一个表示整数或浮点数的字符序列boolean hasNextInt()
- boolouble()
检测是否还有表示整数或浮是否还有表示整数或浮点数的下一个字符序列
2.关于Console
首先贴代码
import java.util.*;
import java.io.*;
public class InputTest{
public static void main(String[] args)
{
Console cons = System.console();
System.out.print("Please input your username:");
String username = cons.readLine();
System.out.println("Please input your password:");
char[] psw = cons.readPassword();
System.out.println("Username:" + username);
System.out.println("Password:" + psw);
System.out.println("Anothe way input password.");
char[] psw2 = cons.readPassword("Password:");
System.out.println("Username:" + username);
System.out.println("Password:" + Arrays.toString(psw2));
System.out.println("Third way.");
String psw3 = new String(cons.readPassword("Password:"));
System.out.println("Username:" + username);
System.out.println("Password:" + psw3);
}
}
小结:
- console输入只能是控制台,不能是IDE
2.密码保存在数组之中,因此打印时要进行转换,可采用Arrays.toString(arr)或Arrays.deepToString(arr)