+ 1
JAVA: Can someone please help me handle all the exceptions in this code? (I'M A NOVICE)
when I try to handle some of the exceptions the programs shuts down or turn into infinite loop https://code.sololearn.com/cXxCZjk5i7AM/?ref=app
3 odpowiedzi
0
Rewrite your main function. Start with your do while loops and make sure there is a proper exit condition for each loop. For example, you allow 1, 2 or 3 but otherwise, do you want it to stay in the loop or exit? The way it is written, the following would do the same. I did pseudocode below
exiting = false
do while (!exiting)
{
print "0=exit 1=... 2=... 3=..."
x = accept input
switch ( x )
{
case 1:
// do something
case 2:
// do something
case 3:
// do something
case 0:
// they want to exit
exiting = true
default:
print "Unrecognized input"
}//esac
} // wend
Also, if the code gets confusing because the case statements get big, try using functions instead. Something like
case 1:
HandleCase1()
case 2:
HandleCase2()
etc.
// then in the function
HandleCase()
{
try {
// do whatever here
}
catch
{
// do whatever here
}
}
This will hopefull allow you to get cleaner code.
Hope that helps.. Sorry, I dont really speak French
0
@Nestor there is a problem with this case and I can't fix it. This is the case where the user, at first, makes the choice "Sort a table of value ..." and that it enters a number different from 1 or 2 and that after the program tells him of enter 1 or 2 and restart the loop "Do you want to sort by odre ..." and then instead of entering an integer it enters a letter. Then The program tells him that he has to enter a number and return to the main loop but keeps in memory the last choice of the user that is to say the letter he had returned. So if again he chooses "Sort a table of value ...", without giving him the possibility to choose between sorting ascending or descending, the program automatically assigns the last value he has entered and so told him to "Enter a number" and so once again gets into the main loop and still does the same thing.
0
Hi, please try GetUserChoice() function to get your input
public static void showln( String m ) // like your aT() function
{
System.out.println(m);
}
// IN prompt, string of valid numeric responses (numeric per your current code)
// Ex. GetUserChoice( "1=XXX 2=YYY 3=ZZZ 0=DONE", "0123" );
// OUT value of the response.
public static int GetUserChoice( String prompt, String validResponses )
{
int res = 0;
Scanner s = new Scanner(System.in);
while ( true )
{
System.out.print( prompt);
String choix = s.nextLine();
System.out.println();
if ( choix.length() > 0 )
{
char resp = choix.charAt(0);
int index = validResponses.indexOf(Character.toString(resp));
if ( index >= 0 ) {
showln("OK");
char c = validResponses.charAt(index);
res = c - '0';
break;
}
}
}
return res;
}