I'm having issues utilizing the scanner for int input. In the getInputs method, if I do not inlcude the if (in.hasNextInt()) ... I get error:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at Solution.getInputs(Solution.java:30)
at Solution.main(Solution.java:7)
However, with the line included I get stuck in an infinite loop since despite however many times I enter a number into the console it never evaluates that there exists an int so int n never changes value. I've tried searching and everyone says to use if (in.hasNextInt()) but cannot find a solution for breaking the infinite loop. I'm lost and can't figure it out. I've tried conditioninig
while(in.hasNextInt()) {
n = in.nextInt();
if (n > 0) break;
}
but this just skips over the loop. Honestly I'm lost.
import java.util.*;
public class Solution{
public static void main(String[] args) {
int t = getTestCases();
int[] inputs = getInputs(t);
int[] solutions = getSolutions(inputs);
for (int i = 0; i < solutions.length; i++) {
System.out.println(solutions[i]);
}
}
static int getTestCases() {
int t = getNumber();
while(t <= 0 && t > 15) {
t = getNumber();
}
System.out.println("t = " + t);
return t;
}
static int[] getInputs(int t) {
int[] inputs = new int[t];
for (int i = 0; i < t; i++) {
int n = getNumber();
while (n <= 0) {
n = getNumber();
}
inputs[i] = n;
}
return inputs;
}
static int[] getSolutions(int[] inputs) {
int[] solutions = new int[inputs.length];
for (int i = 0; i < solutions.length; i++){
solutions[i] = findDigits(inputs[i]);
}
return solutions;
}
static int findDigits(int n) {
int total = 0;
String str = "" + n;
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
int d = Character.getNumericValue(ch);
if (d != 0) {
if (n % d == 0) total++;
}
}
return total;
}
static int getNumber() {
Scanner in = new Scanner(System.in);
int n = -1;
if(in.hasNextInt()) n = in.nextInt();
in.close();
return n;
}
}