Reputation: 21
What did i do wrong??
The errors are:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at MyClass.main(MyClass.java:14)
Here is the code:
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!");
}
}
}
}
Upvotes: 1
Views: 4020
Reputation: 16379
Your code is working fine.
But since you mentioned NoSuchElementException
, it is thrown when you try to read something form the Scanner
but the Scanner
do not have anything to be read.
From documentation of Scanner#nextInt()
@throws NoSuchElementException if input is exhausted
To prevent it you should check whether any element exists in the Scanner
:
if(scan.hasNextInt()){
person = scan.nextInt();
} else {
//show error
return;
}
Upvotes: 1