PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, September 16, 2022

[FIXED] How can I print out in the "while" section of a do while loop in java?

 September 16, 2022     java, printing     No comments   

Issue

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


Solution

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


Answered By - NNK
Answer Checked By - Cary Denson (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing