Java程序开发过程中,需要从键盘获取输入值是常有的事。C语言提供scanf()函数,C++提供cin()获取键盘输入值。那么Java有什么解决方法呢?
package pkg2020华南虎;
import java.io.*;
/**
*
* @author yl
*/
public class JavaInput {
public static void main(String[] args) throws IOException {
System.out.println("Enter a Char:");
char i=(char)System.in.read();
System.out.println("Your char is:"+i);
}
}
虽然此方式实现了从键盘获取输入的字符,但是System.out.read()只能针对一个字符的获取,同时,获取进来的变量类型只能是char。当输入数字时,还需要转换类型。
package pkg2020华南虎;
import java.io.*;
/**
*
* @author yl
*/
public class JavaInput02 {
public static void main(String[] args) throws IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str=null;
System.out.println("Enter your value:");
str=br.readLine();
System.out.println("Your value is:"+str);
}
}
package pkg2020华南虎;
import java.util.Scanner;
/**
*
* @author yl
*/
public class JavaInput03 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Input your name:");
String name=sc.nextLine();
System.out.println("Input your age:");
int age=sc.nextInt();
System.out.println("Input your salary:");
double salary=sc.nextDouble();
System.out.println("Your information is follow as:");
System.out.println("Name:"+name+"\n"+"Age:"+age+"\n"+"Salary:"+salary);
}
}
在Java中,next()方法是不接收空格的,在接收到有效数据前,所有的空格或者tab键等输入被忽略,若有有效数据,则遇到这些键退出。nextLine()可以接收空格或者tab键,其输入应该以enter键结束。(这部分不太理解!!!)
最后附上源博客的链接:Constructor的博客
原文:https://www.cnblogs.com/2020yl/p/12244258.html