当前位置: 首页 > 知识库问答 >
问题:

线程“main”java.util.NoSuChelementException在我的代码上?

陶博涉
2023-03-14

在java.util.scanner.throwfor(Scanner.java:862)
在java.util.scanner.next(Scanner.java:1485)
java.util.scanner.nextint(Scanner.java:2117)
在java.util.scanner.nextint(Scanner.java:2076)
在myclass.main(Myclass.java:14)

代码如下:

import java.util.Scanner;
import java.util.Random;
public class MyClass {
public static Scanner scan = new Scanner(System.in);
public static void main(String args[]) {
    int person,ai,aiint;
    Scanner scan = new Scanner(System.in);
     Random rand = new Random(); 

   System.out.println("Let's Play rock paper scissors! press 1 for rock 2 for paper 3 for scissors ");
   System.out.println();
   aiint=rand.nextInt(3)+1;
   System.out.println("Enter your play: ");
    person=scan.nextInt();
    System.out.println("Computer play is: " +aiint);
    System.out.println("Your play is:" +person);
    if (person==aiint) {
        System.out.println("It's a tie!");
    }
    else if (person==1){
            if(aiint==2){
                System.out.println("Paper beats rock, you lose!");
            }
            else if(aiint==3){
                System.out.println("Rock beats scissors, you win!");
            }
        }
    else if (person==2){
            if(aiint==1){
                System.out.println("Paper beats rock, you win!");
            }
            else if (aiint==3){
                System.out.println("Scissors beats paper, you lose!");
            }
        }
    else if (person==3){
        if(aiint==1){
            System.out.println("Rock beats scissors, you lose!");
        }
        else if(aiint==2){
            System.out.println("Scissors beats paper. you win!");
        }
    }    
    }
}

共有1个答案

左丘阳晖
2023-03-14

您的代码运行良好。

但是由于您提到了NoSuchelementException,当您试图从扫描程序中读取某些内容,但扫描程序没有任何内容要读取时,它就会引发。

摘自扫描器#NextInt()的文档

if(scan.hasNextInt()){
    person = scan.nextInt();
} else {
    //show error
    return;
}
 类似资料: