Skip to main content
Cap
Source Link
Caridorc
  • 28.2k
  • 7
  • 55
  • 138

autoAuto-formatting yields:

auto-formatting yields:

Auto-formatting yields:

factoring
Source Link
Caridorc
  • 28.2k
  • 7
  • 55
  • 138

I suggest factoring out the askInteger logic:

public static int askInteger(String prompt, Scanner scanner) {
    int n = 0;
    System.out.println(prompt);
    while (n < 1) {
        n = scanner.nextInt();
    }
    return n;
}

You can call it like:

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int a = askInteger("a: ", scanner);
    int b = askInteger("b: ", scanner);

    System.out.println(a);
    System.out.println(b);

}

Coupling this function and @h.j.k 's function you can have very readable code.


I suggest factoring out the askInteger logic:

public static int askInteger(String prompt, Scanner scanner) {
    int n = 0;
    System.out.println(prompt);
    while (n < 1) {
        n = scanner.nextInt();
    }
    return n;
}

You can call it like:

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int a = askInteger("a: ", scanner);
    int b = askInteger("b: ", scanner);

    System.out.println(a);
    System.out.println(b);

}

Coupling this function and @h.j.k 's function you can have very readable code.

more info
Source Link
Caridorc
  • 28.2k
  • 7
  • 55
  • 138

I don't usually post an answer only about indentation but the code as-is is very hard to read,Indentation

auto-formatting yields:


Formatting actually shows that:

  • You defined the same variable two times:

      hasString = false; //sets up the booleans
      hasString = false;
    
  • You got an unused variable:

      hasInt = false;
    

Also please be more precise and consistent in the UI:

  • Ask for an integer, not for an 'input'
  • Display a prompt also for the operand as you did for the numbers.

I don't usually post an answer only about indentation but the code as-is is very hard to read, auto-formatting yields:

Indentation

auto-formatting yields:


Formatting actually shows that:

  • You defined the same variable two times:

      hasString = false; //sets up the booleans
      hasString = false;
    
  • You got an unused variable:

      hasInt = false;
    

Also please be more precise and consistent in the UI:

  • Ask for an integer, not for an 'input'
  • Display a prompt also for the operand as you did for the numbers.
Source Link
Caridorc
  • 28.2k
  • 7
  • 55
  • 138
Loading