+ 1
Try and catch exception handling help
so basically try and catch in exception handling is to inform the user if they have keyed in the wrong data right?for example,my code below only accepts true and false input.so if u key in a number,the catch block will tell the user their exact error.am i doing it correctly? https://code.sololearn.com/cU0a0V9qPzC9/?ref=app
8 Antworten
+ 6
you should use an if statement.
if(input.equalsIgnoreCase("True"){System.out.println("True");}
else{System.out.println("false");
+ 5
hmm.. do u mean if the input is true print true and if the input is a number catch it and print false?
+ 4
i think the problem you have with this is that the try dosent really know what its ment to be catching try this which scanner is assigned to a interger input.
import java.util.Scanner;
public class MyClass {
public static void main(String[ ] args) {
boolean boo = true;
try {
Scanner x=new Scanner(System.in);
int i = x.nextInt();
System.out.println(boo);
}
catch (Exception e) {
System.out.println(!boo);
}
}
}
+ 3
yes as the string input is not equal to "true" so it will fall to the else statement
0
doesnt "System.out.println(x.nextBoolean());" tell the program that it only accepts only true or false input?
0
if you input a number,it will prompt the user that " "please key in true or false".doesnt it make sense?
0
does it show an error if i type in rubbish like /_×€×€×&&× ?; using your if else code?
- 1
it will prompt the user "please key in true or false" whatever rubbish the user key in "#%$_/_¥"'%("€".
unless you type true or false