Home > Back-end >  How can I print out in the "while" section of a do while loop in java?
How can I print out in the "while" section of a do while loop in java?

Time:04-16

This is my current code. I would like it to return a System.out.println("Please enter a number above zero") if the user enters a "0". It currently just repeats, if the user enters 0

Currently, it checks if the user has entered a 0 and repeats.

import java.util.Scanner;
public class MyProgram {
  public static void main(String[] args) {
    
    
    // call scanner for user input 
    Scanner in = new Scanner(System.in);
    // double for salary
    int salary = 0;
    double incomeTax = 0;//

    do {
      System.out.println("Please enter your salary?");
      try {
          salary = in.nextInt();
          // test if user enters something other than an integer 
      } catch (java.util.InputMismatchException e) { 
          System.out.println("Invalid input, only enter a number above 0");
          salary = Integer.MIN_VALUE; 
          in.next(); // consume the non-int so we don't get caught in an endless loop
      }
  } while (salary <= 0);  // loop as long as the salary is less than zero
  
  if (salary <= 18000 & salary > 0) {
    incomeTax = 0;
    System.out.println("your weekly income is $"   salary   ", you will pay no income tax this financial year.");
  }

    in.close();
  }
}

CodePudding user response:

Although I would add expected value in the question. On error, your recommended string may be printed as below. Hope I understood your question correctly and this answers it.

    do {
      System.out.println("Please enter your salary? (> 0)");
      try {
          salary = in.nextInt();
          // test if user enters something other than an integer 
      } catch (java.util.InputMismatchException e) { 
          System.out.println("Invalid input, only enter a number above 0");
          salary = Integer.MIN_VALUE; 
          in.next(); // consume the non-int so we don't get caught in an endless loop
      }
      if (salary <= 0) {
         System.out.Println("Please enter a number above zero");
      }
  } while (salary <= 0);  // loop as long as the salary is less than zero
  • Related