最近在写一个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);
}
在java中,next()方法是不接收空格的,在接收到有效数据前,所有的空格或者tab键等输入被忽略,若有有效数据,则遇到这些键退出。nextLine()可以接收空格或者tab键,其输入应该以enter键结束。