我无法添加String异常,以防止输入字符串而不是int时程序崩溃。我确实环顾四周并尝试try{}catch{}
,但是我的程序仍然会因字符串而崩溃。我正在寻求解决getInt().
import java.util.*;
public class Binary{
public static void main(String[]args){
Scanner in = new Scanner(System.in);
String a = "";
boolean cont = true;
while(cont){
printb(convert(getInt(in, "Enter a number: ")));
System.out.println("Do you want to continue (yes or no)?");
a = in.next();
if(a.equals("yes"))
cont = true;
else{
System.out.println("You answerd no. Have a nice day.");
cont = false;
}
}
}
public static int getInt( Scanner console, String prompt){
System.out.print(prompt);
while(!console.hasNext()){
try{
console.next();
System.out.println("Not an integer, try again.");
System.out.print(prompt);
}
catch(Input MismatchException exception){
System.out.print("Not an integer, try again.");
System.out.print(prompt);
}
}
return console.nextInt();
}
public static int[] convert(int decimal){
int decimalCopy = decimal;
int len = 0;
while(decimal != 0){
decimal/=2;
len++;
}
decimal = decimalCopy;
int[] b = new int[len];
int index = 0;
while(decimal !=0){
if(decimal%2 != 0)
b[index] = 1;
else{
b[index] = 0;
}
decimal/=2;
index++;
}
return b;
}
public static void printb(int[] b){
for(int i = b.length-1; i>=0; i--){
System.out.print(b[i]);
}
System.out.println();
}
}
最佳答案
try
/ catch
/ finally
是处理此问题的方法,但是如果您不熟悉异常处理,则很难弄清楚该如何处理它们。即使将它们放在正确的位置,您也需要处理尚未正确“清理”的字符串输入,可以这么说,因此向下层叠到分配了a
的位置并结束程序(自一切不是的事物都是否。
关键是将可能引发异常的行放在try
块中,然后将catch
Exception
进行一些错误处理,然后继续进行finally
所需的操作。 (您可以在此处省略finally
,但是我想确保您理解它,因为它很重要。finally
紧跟在try
/ catch
之后,并且该代码块中的任何内容都会在两种情况下执行(除非您可能会过早退出程序。)
应该这样做:
while (cont) {
// getInt() is the troublemaker, so we try it:
// Notice I have changed 'number' to 'integer' here - this improves
// UX by prompting the user for the data type the program expects:
try {
printb(convert(getInt(in, "Enter an integer: ")));
}
// we catch the Exception and name it. 'e' is a convention but you
// could call it something else. Sometimes we will use it for info,
// and in this case we don't really need it, but Java expects it
// nonetheless.
// We do our error handling here: (notice the call to in.next() -
// this ensures that the string that was entered gets properly
// handled and doesn't cascade down to the assignment of 'a') - if
// this confuses you, try it without the in.next() and see what
// happens!
catch (Exception e) {
System.out.println("\nPlease enter an integer.\n");
in.next();
}
// Again, in this case, the finally isn't necessary, but it can be
// very handy, so I'm using it for illustrative purposes:
finally {
System.out.println("Do you want to continue (yes or no)?");
a = in.next();
if (a.equals("yes")) {
cont = true;
} else {
System.out.println("You answered no. Have a nice day.");
cont = false;
}
}
}