Scanner中nextInt()、nextLine()方法的使用注意事项 笔记

一、nextInt()、nextLine()区别:

1.nextInt()只会读取数值,剩下"\n"还没有读取,并将cursor放在本行中。

2.nextLine()会读取"\n",并结束(nextLine() reads till the end of line \n)。

3.如果想要在nextInt()后读取一行,就得在nextInt()之后额外加上cin.nextLine(),

/**
 * 
 */
package com.hqy.test;

import java.util.Scanner;

/**
 * @author hadoop
 *
 */
public class scannertest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner inScanner=new Scanner(System.in);
		int m=inScanner.nextInt();
		String string=inScanner.nextLine();
		System.out.println("OK");
	}

}

从下图可以看出:


从下图看出:String string=inScanner.nextLine(); 

该行并没有被执行,nextInt()只会读取数值,剩下"\n"还没有读取,并将cursor放在本行中。所以,inScanner.nextLine()直接读取“\n”并结束了。


二、要想在nextInt()后读取一行则要,载加上:in.nextLine()将nextInt()留下的“\n”读取掉。如下:

import java.util.Scanner;

/**
 * @author hadoop
 *
 */
public class scannertest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner inScanner=new Scanner(System.in);
		int m=inScanner.nextInt();
		inScanner.nextLine();
		String string=inScanner.nextLine();
		System.out.println("OK");
	}

}


三、读取一个整数n,并在下一行中读取n个由空格隔开的整数的方法:

方法一:

/**
 * 
 */
package com.hqy.test;

import java.util.Scanner;

/**
 * @author hadoop
 *
 */
public class scannertest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner inScanner=new Scanner(System.in);
		
		while(inScanner.hasNext()){
			int m=inScanner.nextInt();
			inScanner.nextLine();//去掉换行
			String[] strings=inScanner.nextLine().trim().split(" ");
			
			for(String str:strings){
				System.out.print(str);
			}
			System.out.println();
		}
		
		
	}

}

方法二:

/**
 * 
 */
package com.hqy.test;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * @author hadoop
 *
 */
public class scannertest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner inScanner=new Scanner(System.in);
		
		while(inScanner.hasNext()){
			int m=inScanner.nextInt();
			List<Integer> list=new ArrayList<>();
			for(int i=0;i<m;i++){
				list.add(inScanner.nextInt());
			}
			
			for(Integer str:list){
				System.out.print(str);
			}
			System.out.println();
		}
		
		
	}

}

注意:

inScanner.nextInt()只读取数字



猜你喜欢

转载自blog.csdn.net/sinat_38301574/article/details/79588366
今日推荐