java Scanner类中nextLine()方法与nextInt()等联用时

本文详细解析了 Java 中 Scanner 类的使用方法,并针对 nextLine() 方法与 next() 或 nextInt() 联用时出现的问题提供了有效的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

先看一个简单的例子:

import java.util.Scanner;
public class ClassTest{
	public static void main(String[] args){
		Scanner input=new Scanner(System.in);
		System.out.println("in:");
		int a=input.nextInt();
		System.out.println("in:");
		String i=input.nextLine();
		System.out.println("in:");
		String j=input.nextLine();
		System.out.println("a is"+a+"i is"+i+"j is"+j);
	}
}


这是运行的结果,还不待我们输入第二个参数就直接跳转到第三条输入语句,nextLine()方法与next()或nextInt()联用时可能出现一个常见的错误,那就是当next()或者nextInt(),nextDouble()  、 nextFloat()用在nextLine的前面时。nextLine会把前者的结束符“换行符”作为字符串读入,进而不需要从键盘输入字符串nextLine已经转向下一条语句执行

解决方案:

在每一个next()、nextInt()、nextDouble()等后加一条nextLine()语句,将被next()去掉的Enter过滤掉,代码如下:

import java.util.Scanner;
public class ClassTest{
	public static void main(String[] args){
		Scanner input=new Scanner(System.in);
		System.out.println("in:");
		int a=input.nextInt();
		input.nextLine();
		System.out.println("in:");
		String i=input.nextLine();
		System.out.println("in:");
		String j=input.nextLine();
		System.out.println("a is "+a+"i is "+i+"j is "+j);
	}
}

修改后运行结果:



原因:

next()一定要读取到有效字符后才可以结束输入,对输入有效字符之前遇到的空格键、Tab键或Enter键等结束符,next()方法会自动将其去掉,只有在输入有效字符之后,next()方法才将其后输入的空格键、Tab键或Enter键等视为分隔符或结束符。简单地说,next()查找并返回来自此扫描器的下一个完整标记。完整标记的前后是与分隔模式匹配的输入信息,所以next方法不能得到带空格的字符串。 而nextLine()方法的结束符只是Enter键,即nextLine()方法返回的是Enter键之前的所有字符,它是可以得到带空格的字符串的。






以下是一个简单的Java扫雷游戏实现代码,供参考: ```java import java.util.Random; import java.util.Scanner; public class Minesweeper { // 游戏区域 private int[][] board; // 游戏状态 private boolean gameOver; // 雷的数量 private int numMines; // 标记的雷的数量 private int numMarkedMines; // 游戏用 private int timeElapsed; // 构造函数 public Minesweeper(int numRows, int numCols, int numMines) { this.board = new int[numRows][numCols]; this.gameOver = false; this.numMines = numMines; this.numMarkedMines = 0; this.timeElapsed = 0; // 初始化游戏区域 initBoard(); } // 初始化游戏区域 private void initBoard() { // 先将所有格子状态设为未翻开 for (int i = 0; i < board.length; i++) { for (int j = 0; j < board[0].length; j++) { board[i][j] = 0; } } // 随机生成雷的位置 Random rand = new Random(); int count = numMines; while (count > 0) { int row = rand.nextInt(board.length); int col = rand.nextInt(board[0].length); if (board[row][col] != -1) { board[row][col] = -1; count--; } } // 计算每个格子周围雷的数量 for (int i = 0; i < board.length; i++) { for (int j = 0; j < board[0].length; j++) { if (board[i][j] != -1) { int countMines = 0; for (int m = Math.max(0, i - 1); m <= Math.min(i + 1, board.length - 1); m++) { for (int n = Math.max(0, j - 1); n <= Math.min(j + 1, board[0].length - 1); n++) { if (board[m][n] == -1) { countMines++; } } } board[i][j] = countMines; } } } } // 打印游戏区域 private void printBoard(boolean showMines) { System.out.print(" "); for (int j = 0; j < board[0].length; j++) { System.out.print((j + 1) + " "); } System.out.println(); System.out.print(" "); for (int j = 0; j < board[0].length; j++) { System.out.print("--"); } System.out.println(); for (int i = 0; i < board.length; i++) { System.out.print((i + 1) + "|"); for (int j = 0; j < board[0].length; j++) { if (board[i][j] == 0) { System.out.print(" "); } else if (board[i][j] == -2) { System.out.print("F "); } else if (board[i][j] == -1) { if (showMines || gameOver) { System.out.print("* "); } else { System.out.print(" "); } } else { System.out.print(board[i][j] + " "); } } System.out.println("|" + (i + 1)); } System.out.print(" "); for (int j = 0; j < board[0].length; j++) { System.out.print("--"); } System.out.println(); System.out.print(" "); for (int j = 0; j < board[0].length; j++) { System.out.print((j + 1) + " "); } System.out.println(); } // 翻开格子 private void reveal(int row, int col) { if (row < 0 || row >= board.length || col < 0 || col >= board[0].length) { return; } if (board[row][col] == -2) { return; } if (board[row][col] == -1) { gameOver = true; return; } if (board[row][col] > 0) { board[row][col] = -board[row][col]; return; } board[row][col] = -1; for (int m = Math.max(0, row - 1); m <= Math.min(row + 1, board.length - 1); m++) { for (int n = Math.max(0, col - 1); n <= Math.min(col + 1, board[0].length - 1); n++) { if (m != row || n != col) { reveal(m, n); } } } } // 标记为雷或取消标记 private void mark(int row, int col) { if (board[row][col] == -2) { board[row][col] = 0; numMarkedMines--; } else if (board[row][col] == 0) { board[row][col] = -2; numMarkedMines++; } } // 检查是否胜利 private boolean checkWin() { if (numMarkedMines != numMines) { return false; } for (int i = 0; i < board.length; i++) { for (int j = 0; j < board[0].length; j++) { if (board[i][j] == -2 || board[i][j] == 0) { return false; } } } return true; } // 运行游戏 public void run() { Scanner scanner = new Scanner(System.in); boolean firstMove = true; long startTime = System.currentTimeMillis(); while (!gameOver) { printBoard(false); System.out.print("Enter row and column (e.g. 1 2), or 'm' to mark/unmark a mine: "); String input = scanner.nextLine(); if (input.equals("m")) { System.out.print("Enter row and column (e.g. 1 2): "); String[] pos = scanner.nextLine().split(" "); int row = Integer.parseInt(pos[0]) - 1; int col = Integer.parseInt(pos[1]) - 1; if (row < 0 || row >= board.length || col < 0 || col >= board[0].length) { System.out.println("Invalid position!"); continue; } mark(row, col); } else { String[] pos = input.split(" "); int row = Integer.parseInt(pos[0]) - 1; int col = Integer.parseInt(pos[1]) - 1; if (row < 0 || row >= board.length || col < 0 || col >= board[0].length) { System.out.println("Invalid position!"); continue; } if (firstMove) { // 第一次翻开格子不能是雷 while (board[row][col] == -1) { initBoard(); } firstMove = false; } reveal(row, col); if (checkWin()) { printBoard(true); System.out.println("You win!"); return; } } } printBoard(true); System.out.println("Game over!"); } public static void main(String[] args) { Minesweeper game = new Minesweeper(8, 8, 10); game.run(); } } ``` 该代码实现了一个简单的8x8扫雷游戏,有10个雷。运行程序后,按照提示输入行和列号进行游戏,输入`m`可以标记为雷或取消标记。游戏结束后会显示游戏区域,如果有未翻开的雷则显示`*`,否则显示数字。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值