0
while loop problem
I call the triangleInput() method from another class 3 times to get 3 different numbers from the user. the while loop should keep looping until the user enters a valid integer. but it doesn't loop the first time. any ideas how to get round this? w do while worked a bit weird. //code Scanner sc = new Scanner(System.in); public static int triangleInput(){ int insides = 0; // to hold user input to return while(!sc.hasNextInt()){ System.out.println("Enter a number:") ; insides = sc.nextInt(); } return intSides; }
3 ответов
0
try to remove !
should be:
while(sc.hasNextInt ())
0
the problem when I take that out is if the user enters something invalid, it breaks out of the loop and moves on to the next number, meaning it misses a number.
what I'm trying to do in that loop is keep asking the user for a number until he enters a valid one, it then returns that number and the method is called again.
0
Is the below is what you want:
import java.util.Scanner;
public class Program
{
public static void main(String[] args) {
System.out.println(triangleInput());
}
public static int triangleInput(){
int insides = 0; // to hold user input to return
Scanner sc = new Scanner(System.in);
while(true){
System.out.println("Enter a number:") ;
try{
insides = sc.nextInt();
return insides;
}catch(Exception e){
if (sc != null) sc.next ();
}
}
}
}