0

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();
  }

} 
Moy_Desu
  • 19
  • 7
  • 1
    Where did you put the `try catch` ? – AxelH Nov 22 '16 at 15:14
  • 1
    I don't think an exception is appropriate in the case of bad input. Perhaps you're looking for something like [this](http://stackoverflow.com/a/8392032/770270) to *validate* input rather than throwing an exception for un-exceptional behavior. – tnw Nov 22 '16 at 15:14
  • Possible duplicate of [Java Try Catch block](http://stackoverflow.com/questions/35321312/java-try-catch-block) – AxelH Nov 22 '16 at 15:14
  • @tnw I incorporated that into `getInt` instead of the while method and that seems to have worked. – Moy_Desu Nov 22 '16 at 15:26
  • @Moy_Desu Ok, but you really shouldn't be throwing an exception here. – tnw Nov 22 '16 at 15:49
  • It's still a `try`/`catch`, it's just nested in a function. – Sy Dy Nov 22 '16 at 16:07

2 Answers2

1
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`
  • yes this works. I overlooked trying the `try{}catch(){}` in the main method instead. – Moy_Desu Nov 22 '16 at 15:33
  • I think it's a good idea to avoid generic error messages like "invalid input", good UX opts to inform the user what input the program is expecting when they make a mistake. – Sy Dy Nov 22 '16 at 15:59
  • Also, putting the entirety of the while loop in the `try` block terminates the program upon exception, instead of allowing the user to try again. – Sy Dy Nov 22 '16 at 16:04
1

try/catch/finally is the way to handle this, but if you aren't familiar with exception handling, it can be tricky to figure out exactly what to do with them. And even when you do put them in the right place, you need to deal with the string input that hasn't been properly "cleaned up" so to speak, so cascades down to where a is assigned and ends the program (since everything that is not yes is no).

The key is to put the line(s) that might throw an exception inside the try block, then catch the Exception with some error handling, and then continue what needs to happen with finally. (You could omit the finally here, but I wanted to make sure you understand it, because it's important. finally comes after try/catch and anything within that code block will be executed in either scenario (unless you exit the program prematurely).)

This should do it:

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;
    }
  }
}
Sy Dy
  • 116
  • 5
  • I have some other suggestions that would tighten up your code but I don't want to muddy the answer. If you're interested, let me know, I'm happy to code review it, but it should be done separately. – Sy Dy Nov 22 '16 at 16:01
  • Yes I usually dont work with exceptions but I can understand this, i think this is the best explention I've received for this so far. I will probably try making a porgram that finally comes into play to test that out (havent used finally before). – Moy_Desu Nov 22 '16 at 16:06
  • Thank you! Please do mark it as accepted if you think it's the best, I'd super appreciate it because I'm new to answering and so i don't have enough rep to unlock some of the site features. :) – Sy Dy Nov 22 '16 at 16:09