最近在寫一個Java程序時遇到一個問題,就是如何在Java里面輸入數值,又叫做獲取鍵盤輸入值。
因為c語言里面有scanf(),C++里面有cin(),python里面有input()。Java里面有三種方法:
First:從控制台接受一個字符並打印
import java.io.*;
import java.io.IOException;
public class test {
public static void main(String args[]) throws IOException{
char word = (char)System.in.read();
System.out.print("Your word is:" + word);
}
}
這種方式只能在控制台接受一個字符,同時獲取到的時char類型變量。另外補充一點,下面的number是int型時輸出的結果是Unicode編碼。
import java.io.*;
import java.io.IOException;
public class test {
public static void main(String args[]) throws IOException{
int number = System.in.read();
System.out.print("Your number is:" + number);
}
}
Second:從控制台接受一個字符串並將它打印出來。這里面需要使用BufferedReader類和InputStreamReader類。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class test {
public static void main(String args[]) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = null;
str = br.readLine();
System.out.println("Your value is :" + str);
}
}
通過這個方式能夠獲取到我們輸入的字符串。這里面的readLine()也得拿出來聊一聊。
Third:使用Scanner類。
import java.util.Scanner;
public class CSU1726 {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("請輸入你的姓名:");
String name = sc.nextLine();
System.out.println("請輸入你的年齡:");
int age = sc.nextInt();
System.out.println("請輸入你的工資:");
float salary = sc.nextFloat();
System.out.println("你的信息如下:");
System.out.println("姓名:"+name+"\n"+"年齡:"+age+"\n"+"工資:"+salary);
}
}
這段代碼已經表明,Scanner類不管是對於字符串還是整型數據或者float類型的變量,它都能夠實現功能。
But:上面這個方法要注意的是nextLine()函數,在io包里有一個
import java.util.Scanner;
public class CSU1726 {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("請輸入你的年齡:");
int age = sc.nextInt();
System.out.println("請輸入你的姓名:");
String name = sc.nextLine();
System.out.println("請輸入你的工資:");
float salary = sc.nextFloat();
System.out.println("你的信息如下:");
System.out.println("姓名:"+name+"\n"+"年齡:"+age+"\n"+"工資:"+salary);
}
上面兩段代碼主要區別在於,這段代碼先執行nextInt()再執行nextLine(),而第三種方法的例子是相反的。當你在運行着兩段代碼的時候你會發現第三種方法的例子可以實現正常的輸入,而這段代碼卻在輸入年齡,敲擊enter鍵后,跳過了輸入姓名,直接到了輸入工資這里,(可以自己運行代碼看看)。
這背后的原因是,在執行完nextInt()函數之后,敲擊了enter回車鍵,回車符會被nextLine()函數吸收,實際上是執行了nextLine()函數吸收了輸入的回車符(並不是沒有執行nextLine函數),前面講到和nextLine()功能一樣的函數next(),他們的區別就在於:next()函數不會接收回車符和tab,或者空格鍵等,所以在使用nextLine()函數的時候,要注意敲擊的回車符是否被吸收而導致程序出現bug。
最后的總結:next()和nextLine()的區別
在java中,next()方法是不接收空格的,在接收到有效數據前,所有的空格或者tab鍵等輸入被忽略,若有有效數據,則遇到這些鍵退出。nextLine()可以接收空格或者tab鍵,其輸入應該以enter鍵結束。
