Java中的“scanf()、cin()、input()"

时间:2023-03-08 16:57:07

最近在写一个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键结束。