【Mark学Java】Scanner

Scanner

Scanner类,可以实现键盘输入数据,到程序中.
java.util.ScannerJava5 的新特征,我们可以通过 Scanner 类来获取用户的输入。
下面是创建 Scanner 对象的基本语法:

Scanner s = new Scanner(System.in);

通过 Scanner 类的 next()nextLine() 方法获取输入的字符串,在读取前我们一般需要 使用 hasNexthasNextLine判断是否还有输入的数据:

next()

import java.util.Scanner; 
 
public class ScannerDemo {
    public static void main(String[] args) {
        // 从键盘接收数据
        Scanner scan = new Scanner(System.in);
        // next方式接收字符串
        System.out.println("next方式接收:");
        // 判断是否还有输入
        if (scan.hasNext()) {
            String str1 = scan.next();
            System.out.println("输入的数据为:" + str1);
        }
        scan.close();
    }
}

next方式接收:
runoob com
输入的数据为:runoob

可以看到 com 字符串并未输出,接下来我们看 nextLine

nextLine()

import java.util.Scanner;
 
public class ScannerDemo {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        // 从键盘接收数据
 
        // nextLine方式接收字符串
        System.out.println("nextLine方式接收:");
        // 判断是否还有输入
        if (scan.hasNextLine()) {
            String str2 = scan.nextLine();
            System.out.println("输入的数据为:" + str2);
        }
        scan.close();
    }
}

nextLine方式接收:
runoob com
输入的数据为:runoob com

next()与nextLine()区别

next():

  • 一定要读取到有效字符后才可以结束输入。
  • 对输入有效字符之前遇到的空白,next() 方法会自动将其去掉
  • 只有输入有效字符后才将其后面输入的空白作为分隔符或者结束符。
  • next() 不能得到带有空格的字符串。

nextLine()

  • Enter为结束符,也就是说 nextLine()方法返回的是输入回车之前的所有字符。
  • 可以获得空白

如果要输入 intfloat 类型的数据,在 Scanner 类中也有支持,但是在输入之前最好先使用 hasNextXxx() 方法进行验证,再使用 nextXxx()来读取:

nextInt()

 import java.util.Scanner;

public class MaxMap {
     public static void main(String[] args){
        Scanner cin = new Scanner(System.in);
         int n = cin.nextInt();
         String str = cin.nextLine();
         System.out.println("END");
         }
 } 

nextInt()只读取数值,剩下"\n"还没有读取,并将cursor放在本行中。nextLine()会读取"\n",并结束.如果想要在nextInt()后读取一行,就得在nextInt()之后额外加上cin.nextLine(),代码如下

import java.util.Scanner;

public class MaxMap {
    public static void main(String[] args){
        Scanner cin = new Scanner(System.in);
        int n = cin.nextInt();
        cin.nextLine();
        String str = cin.nextLine();
        System.out.println("END");
        }
}

读取数字也可以使用nextLine(),不过需要转换:
Integer.parseInt(cin.nextLine())

注意在next()nextInt()nextLine()一起使用时,next()nextInt()往往会读取部分数据会留下"\n"或者空格之后的数据)。

Scanner读取文件

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;


/**
 * 利用Scanner读取项目中的文档
 * */
public class TestScannerRead {
    
    public static void main(String[] args){
        
        Scanner sc;
        try {
            //读取项目中的文档
            sc = new Scanner(new File("ScannerTest.txt"));
            System.out.println("项目中的文本内容是:");
            //通过判断是否有下一行来输出文档内容
            while (sc.hasNextLine()) {
                System.out.println(sc.nextLine());
            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
import java.util.Scanner;
 
public class ScannerDemo {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        // 从键盘接收数据
        int i = 0;
        float f = 0.0f;
        System.out.print("输入整数:");
        if (scan.hasNextInt()) {
            // 判断输入的是否是整数
            i = scan.nextInt();
            // 接收整数
            System.out.println("整数数据:" + i);
        } else {
            // 输入错误的信息
            System.out.println("输入的不是整数!");
        }
        System.out.print("输入小数:");
        if (scan.hasNextFloat()) {
            // 判断输入的是否是小数
            f = scan.nextFloat();
            // 接收小数
            System.out.println("小数数据:" + f);
        } else {
            // 输入错误的信息
            System.out.println("输入的不是小数!");
        }
        scan.close();
    }
}

为了进一步理解next(),nextLine()区别,通过下面例子分析

import java.util.Scanner;
 
//Scanner中nextLine()方法和next()方法的区别
public class ScannerString {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("请输入字符串(next):");
        String str = input.next();
        System.out.println(str); 
        System.out.println("请输入字符串(nextLine):");//abc
        String str1 = input.nextLine();
        System.out.println(str1);
    }
}

请输入字符串(next):
abc
abc
请输入字符串(nextLine):

输入nextLine字符串之前,程序已停掉.Scanner是一个扫描器,我们录取到键盘的数据,先存到缓存区等待读取,它判断读取结束的标示是 空白符;比如空格,回车,tab 等等。
next()方法读取到空白符就结束
nextLine()读取到回车结束也就是“\r”

next()读取到空白符前的数据时结束了,然后把回车“\r”留给了nextLine();所以上面nextLine()没有输出,不输出不代表没数据,是接到了空(回车“/r”)的数据

OJ输入

Java5中引入了Scanner库,这个库在日常使用中是非常方便的,可以直接将输入按照格式读取,但是,效率要比BufferedReader差很多,因此,在做题时推荐还是用BufferedReaderInputStreamReader来使用。
在这些平台,一般要求主类名为Main,然后将方法写到main()方法中,因此,我们的类大概是类似如下的格式:

基本格式

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    public static void main(String[] args) throws IOException{
    	......
    }
}

输入为一个字符串

abcd

代码

// 创建一个BufferedReader对象
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// 读取字符串
String line = br.readLine();
// 测试输入是否正确
System.out.println(line);

输入为多个数字

1 2

代码

// 创建一个BufferedReader对象
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// 读取第一行数据
String line = br.readLine();
// 将字符串根据空格进行分隔
String[] strings = line.trim().split(" ");
// 分别将其中的每个数值读出
int n = Integer.parseInt(strings[0]);
int v = Integer.parseInt(strings[1]);
// 测试输入是否正确
System.out.println("n: " + n + "\tv: " + v);

输入中有一个数组,且有数组的长度

7 6
1 2 3 4 5 6 7

代码

 // 创建一个BufferedReader对象
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// 读取第一行数据
String line = br.readLine();
// 将字符串根据空格进行分隔
String[] strings = line.trim().split(" ");
// 分别将其中的每个数值读出
int n = Integer.parseInt(strings[0]);
int v = Integer.parseInt(strings[1]);
// 读取第二行数据
line = br.readLine();
strings = line.trim().split(" ");
// 创建一个int型的数组用来储存第二行的多个数字
int[] nums = new int[n];
for (int i = 0; i < n; i ++) {
   nums[i] = Integer.parseInt(strings[i]);
}
// 测试输入是否正确
for (int num: nums) {
  System.out.print(num + " ");
}

输入不定组数数据

输入多组数据,不告知组数,也没有截止符

Scanner s=new Scanner(System.in);
while(s.hasNext()){//判断是否数据结束
    int a=s.nextInt();
    int b=s.nextInt();
}

练习

求a+b

import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNextInt()) {//注意while处理多个case
            int a = in.nextInt();
            int b = in.nextInt();
            System.out.println(a + b);
        }
    }
}

求n阶方阵中所有数

Input:
3
1 2 3
2 1 3
3 2 1
Output:
18
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int ans = 0, x;
        for(int i = 0; i < n; i++){
            for(int j = 0; j < n; j++){
                x = sc.nextInt();
                ans += x;
            }
        } 
        System.out.println(ans);
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是Java井字棋人机对战的示例代码,其中包括了人机对战的逻辑和实现: ```java import java.util.Scanner; public class TicTacToe { private char[][] board; private char player; private char computer; public TicTacToe() { board = new char[3][3]; player = 'X'; computer = 'O'; initializeBoard(); } public void initializeBoard() { for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { board[i][j] = '-'; } } } public void printBoard() { System.out.println("-------------"); for (int i = 0; i < 3; i++) { System.out.print("| "); for (int j = 0; j < 3; j++) { System.out.print(board[i][j] + " | "); } System.out.println(); System.out.println("-------------"); } } public boolean isBoardFull() { boolean isFull = true; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (board[i][j] == '-') { isFull = false; } } } return isFull; } public boolean checkForWin(char player) { for (int i = 0; i < 3; i++) { if (board[i][0] == player && board[i][1] == player && board[i][2] == player) { return true; } } for (int j = 0; j < 3; j++) { if (board[0][j] == player && board[1][j] == player && board[2][j] == player) { return true; } } if (board[0][0] == player && board[1][1] == player && board[2][2] == player) { return true; } if (board[0][2] == player && board[1][1] == player && board[2][0] == player) { return true; } return false; } public void playerMove() { Scanner scanner = new Scanner(System.in); int row, col; do { System.out.print("Enter row number and column number (1-3): "); row = scanner.nextInt() - 1; col = scanner.nextInt() - 1; } while (row < 0 || row >= 3 || col < 0 || col >= 3 || board[row][col] != '-'); board[row][col] = player; } public void computerMove() { int[] move = getBestMove(); board[move[0]][move[1]] = computer; } public int evaluate(char player) { if (checkForWin(computer)) { return 10; } else if (checkForWin(player)) { return -10; } else { return 0; } } public int minimax(int depth, boolean isMax, char player, int alpha, int beta) { int score = evaluate(player); if (score == 10 || score == -10) { return score; } if (isBoardFull()) { return 0; } if (isMax) { int best = Integer.MIN_VALUE; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (board[i][j] == '-') { board[i][j] = computer; best = Math.max(best, minimax(depth + 1, !isMax, player, alpha, beta)); board[i][j] = '-'; alpha = Math.max(alpha, best); if (beta <= alpha) { break; } } } } return best; } else { int best = Integer.MAX_VALUE; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (board[i][j] == '-') { board[i][j] = player; best = Math.min(best, minimax(depth + 1, !isMax, player, alpha, beta)); board[i][j] = '-'; beta = Math.min(beta, best); if (beta <= alpha) { break; } } } } return best; } } public int[] getBestMove() { int bestVal = Integer.MIN_VALUE; int[] bestMove = new int[2]; bestMove[0] = -1; bestMove[1] = -1; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (board[i][j] == '-') { board[i][j] = computer; int moveVal = minimax(0, false, player, Integer.MIN_VALUE, Integer.MAX_VALUE); board[i][j] = '-'; if (moveVal > bestVal) { bestMove[0] = i; bestMove[1] = j; bestVal = moveVal; } } } } return bestMove; } public void play() { System.out.println("Welcome to Tic Tac Toe!"); System.out.println("-----------------------"); System.out.println("Instructions:"); System.out.println("Enter the row and column number to place your mark."); System.out.println("You are X, and the computer is O."); System.out.println("The first player to get three in a row wins!"); System.out.println(); printBoard(); while (!isBoardFull()) { playerMove(); if (checkForWin(player)) { System.out.println("Congratulations! You win!"); return; } computerMove(); System.out.println("Computer's move:"); printBoard(); if (checkForWin(computer)) { System.out.println("Sorry, you lose."); return; } } System.out.println("It's a tie!"); } public static void main(String[] args) { TicTacToe game = new TicTacToe(); game.play(); } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值