Проблема связана с использованием вами класса сканера. Поскольку вы используете клавиатуру для ввода своих чисел, функция Scanner.hasNextInt()
всегда будет возвращать true, потому что она ожидает, что вы введете число при следующем вводе, поэтому, чтобы остановить бесконечный вызов, вы должны ввести список, который не содержит любое целое число.
Также ваш код остановится без обработки остальной части текущего списка при обнаружении отрицательного числа. Вы должны поставить условие остановки за пределы условия SENTINEL.
И не забудьте закрыть сканер, когда закончите с ним.
Вот пример кода того, как я мог бы закодировать это
import java.util.Scanner;
public class multiple3 {
/**
* The minimum value of the numbers to test.<br>
* Any value less or equal than SENTINEL will not be considered as valid
*/
static final int SENTINEL = -1;
public static void main(String [] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a list of numbers: ");
String line = in.nextLine();//take all the input
multipleThree(line.split(" "));//Split the line into an array containing the differents values
in.close(); //Close the Scanner
}
/**
* Simplified version of {@link #multipleThree(String[], int)}<br>
* Only need the array of String to work
*
* @param arr : An array of Strings containing
*/
static void multipleThree(String[] arr) {
multipleThree(arr, 0);
}
/**
* Print all numbers evenly divisible by 3 in the console
*
* @param arr : An array of Strings containing
* @param count : Index of the currently checked
*
* @throws NumberFormatException If one of arr's element is not an Integer
*/
static void multipleThree(String[] arr, int count) throws NumberFormatException {
if(count == arr.length)
{//We stop when we reach the end of the array
System.out.println();//go to the next line
return;
}
int store = Integer.parseInt(arr[count]);//store the next integer in a variable..
if(store > SENTINEL && store % 3 == 0)
{//so long as the next int is greater than negative one and evenly divisible by 3..
System.out.print(store+" ");//print out that integer.
}
multipleThree(arr, count+1);//re-invoke method multipleThree.
}
}
Как вы видите, я звоню Scanner.nextLine()
один раз, поэтому я уверен, что бесконечный звонок от l oop до Scanner.nextInt()
не будет.