就是在刷题网站上想要读取多行应该怎么做?
想要读取这四行数据,最简单的方法是使用nextLine()函数每次读一行数据,注意这个函数读取的是String数据,一般刷题网站给的也是String数据,后面根据需要在进行数据类型转换。
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner in=new Scanner(System.in);
String tempstr=in.nextLine();
int num=Integer.valueOf(tempstr);
String str=in.nextLine();
String str1=in.nextLine();
String str2=in.nextLine();
System.out.println(num);
System.out.println(str);
System.out.println(str1);
System.out.println(str2);
}
}
读取的结果进行打印后的效果:
当然还有一些其他的读取方式:
例如nextInt,nextDouble,nextFloat等等类似于Next+基本数据类型的读取方式
这些方式读取之后,每次只读取一个基本数据类型的变量,遇到空格和回车后会自动停止,如果是空格就调用nextInt就可以跳过空格,来读取下一个值,如果是回车那么用nextLine来读取这个回车才能进行下一行操作
输入是:
代码为
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner in=new Scanner(System.in);
int num =in.nextInt();
int num1 =in.nextInt();
int num2 =in.nextInt();
String str=in.nextLine();
String str1=in.nextLine();
String str2=in.nextLine();
System.out.println(num);
System.out.println(num1);
System.out.println(num2);
System.out.println(str);
System.out.println(str1);
System.out.println(str2);
}
}
输出为
这个例子说明nextInt可以把下一个空格给拿掉,但是却不能拿掉下一个回车,因此需要在使用完nextInt之后需要使用一个nextLine来吃掉这个多余的空格。
代码实际输出为
3
4
5
helloo
helllo
这样就成功的读取了