Moy_Desu Moy_Desu - 18 days ago 5
Java Question

Adding exception to java program

I am having trouble adding an String exception to prevent my program from crashing when a string is entered instead of a int. I did look around and try out

try{}catch{}
but my program would still crash with a string. I'm looking to fix
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();
}

}

Answer
import java.util.*;
public class Binary{

  public static void main(String[]args){
    try {
    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;
      } }
    } catch(Exception e) {
      System.out.println("Invalid input");
    }


  }

  public static int getInt( Scanner console, String prompt){
    System.out.print(prompt);
    while(!console.hasNext()){
        console.next();
        System.out.println("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();
  }

} `enter code here`