Reputation: 19
I am getting error in my java code. I was writing code that will take two number and and one string and then it will tell the index position in string which is divisible by both the number. Our string will consist of numbers separated by commas.
import java.util.Scanner;
class Main {
public static void main(String args[]) {
System.out.println("This program receives an integer vector and checks if it has any element divisible by N and M.");
System.out.println("Note that you should only enter numbers (do not use any letter or space) otherwise the execution will be terminated.");
Scanner sc = new Scanner(System.in);
Scanner scString = new Scanner(System.in);
System.out.print("Enter an integer value for N: ");
int n = sc.nextInt();
System.out.print("Enter an integer value for M: ");
int m = sc.nextInt();
//sc. nextLine();
System.out.println("Please enter your vector elements (comma separated) below.");
String str = scString.nextLine();
String[] arrOfStr = str.split(",", 0);
int i=0;
for (String a : arrOfStr){
int x = Integer.parseInt(a);
if(x%n ==0 && x%m == 0){
break;
}
i=i+1;
}
System.out.print("Element "+i+" of the entered vector is divisible by both "+n+" and "+m);
}
}
Error that I am getting is:
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 Main.main(Main.java:9)
Can anyone suggest me correct way of doing it??
Upvotes: 0
Views: 53
Reputation: 4614
NoSuchElementException
is thrown from int n = sc.nextInt();
or from int m = sc.nextInt();
because there is no input token left which can be converted to int.
Java doc:
NoSuchElementException - if input is exhausted
Can you check if you are giving correct input against integer.
Or may be you can do :
System.out.print("Enter an integer value for N: ");
int n=0;
int m=0;
if (sc.hasNextInt()) {
n = sc.nextInt();
}else {
System.out.print("No value for N");
}
System.out.print("Enter an integer value for M: ");
if (sc.hasNextInt()) {
m = sc.nextInt();
}else {
System.out.print("No value for M");
}
Upvotes: 1