while loop problem | Sololearn: Learn to code for FREE!
Новый курс! Каждый программист должен знать генеративный ИИ!
Попробуйте бесплатный урок
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; }

14th Aug 2016, 3:39 PM
Barra
Barra - avatar
3 ответов
0
try to remove ! should be: while(sc.hasNextInt ())
14th Aug 2016, 5:51 PM
Tiger
Tiger - avatar
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.
15th Aug 2016, 5:07 AM
Barra
Barra - avatar
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 (); } } } }
15th Aug 2016, 9:48 AM
Tiger
Tiger - avatar