The following code below asks the user to enter a number. Then it prompts the user to enter more numbers. When they exit the program they display the highest number entered. How could I convert this code to ask for the gender of a person then age. So the output of the program would state the highest girl age is ____ and the highest boy age is _______? Right now its gender neutral and just complies the highest age.
import javax.swing.JOptionPane;
public class largestNumb{
public static void main(String[] args) {
int highestNumber;
boolean firstNumberEntered = false;
int firstNumber;
do {
String firstNumberInput = JOptionPane.showInputDialog("Enter the first number: ");
try {
firstNumber = Integer.parseInt(firstNumberInput);
firstNumberEntered = true;
}
catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Invalid number! Please try again.");
firstNumber = 0;
firstNumberInput = JOptionPane.showInputDialog("Enter the first number: ");
}
} while (!firstNumberEntered);
highestNumber = firstNumber;
String numberInput = JOptionPane.showInputDialog("Enter another number, or Q to quit");
while (!numberInput.equalsIgnoreCase("Q")) {
int number;
try {
number = Integer.parseInt(numberInput);
if (number > highestNumber) {
highestNumber = number;
}
}
catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Invalid number!");
}
numberInput = JOptionPane.showInputDialog("Enter another number, or Q to quit");
}
JOptionPane.showMessageDialog(null, "The highest number was: " + highestNumber);
}
}
You can ask for the gender in another showInputDialog method.
Change the showInputDialog from an int to a collection of values, it can be an array with a length of 2 to store the highest age for the gender, it can be a map where the key is the gender, the limit is the sky
You will need to work in your validations:
If you are asking ages, shouldn't that be stated when you are asking the data?
What will happen if the user inputs a negative number?
Would you accept an age of 1345 years?
What if it the text is empty, a character different to 'q'?
I would suggest either placing another showInputDialog message within each loop or creating an if statement to specify the gender.
You need to maintain two different variables which will keep track of the highest age for each girl and boy respectively. You do not need to add any additional in this case. Add code to ask the user to enter gender (validate the data) and ask for age. Based on gender do the separate calculation.
while(...)
{
//Ask for gender and validate
//Ask for age and validate
switch(gender)
{
case 'M':
//maleHigestAge calculation here
break;
case 'F':
//femaleHigestAge calculation here
break;
}
}
//display maleHigestAge and femaleHigestAge with formated string
Related
I recently started learning Java as I have a keen interest in programming. I am currently creating an application that calculates a person's BMI.
Question: Is there a way to return to the previous statement when the user has made a mistake on instead of restarting the whole program (EG: when the line Please enter your weight in pounds executed, the user input a non-integer value and an error prompts out saying Invalid Input, it will then return to the previous line that the user made an error -> Please enter your weight in pounds executed).
If yes, how so?
import java.util.Scanner;
import java.text.DecimalFormat;
public class Body_Mass_Calculation {
private static int gender, inputAnswer;
private static boolean wenttocatch;
private static double myBMI, heightInch, weightPound, weightKilo, heightMeter;
private static Scanner input_1 = new Scanner(System.in);
private static DecimalFormat df2 = new DecimalFormat("#.##");
//Questions + Calculation
static void myMethod() {
try {
System.out.println("Please enter gender. 1-- Male 2--Female");
gender = input_1.nextInt();
while (gender > 2 || gender < 1) {
System.out.println("Invalid input!");
System.out.println("Please enter gender. 1-- Male 2--Female");
gender = input_1.nextInt();
}
if (gender == 1 || gender == 2) {
System.out.println("Please enter your height in inches. ");
heightInch = input_1.nextInt();
System.out.println("Please enter your weight in pounds. ");
weightPound = input_1.nextInt();
heightMeter = heightInch * 0.0254;
weightKilo = weightPound * 0.45359237;
myBMI = weightKilo / (heightMeter * heightMeter);
}
if (gender == 1) {
if (myBMI >= 27.8)
System.out.println("Your body-mass-index is " + df2.format(myBMI) + " this is considered high ! \n \n");
else
System.out.println("Your body-mass-index is " + df2.format(myBMI) + " this is not considered high ! \n \n");
}
if (gender == 2) {
if (myBMI >= 27.3)
System.out.println("Your body-mass-index is " + df2.format(myBMI) + " this is considered high ! \n \n");
else
System.out.println("Your body-mass-index is " + df2.format(myBMI) + " this is not considered high! \n \n");
}
System.out.println("Do you wish to continue? Enter: 1 -> Yes, 2 -> No.");
inputAnswer = input_1.nextInt();
System.out.println("Invalid Input !");
if (inputAnswer == 2) { //If input = 2, Program executes line below
System.out.println("Thank You for using this shitty app !");
System.exit(2);
} else if (inputAnswer == 1) {
myMethod();
}
} catch
(Exception e) {
input_1.next();
wenttocatch = true;
System.out.println("Invalid input !");
input_1.nextLine();
myMethod();
}
}
public static void main(String[] args) {
//Executes Function/Method
System.out.println("Welcome ! \n ");
myMethod();
}
}
No, you can't. The solution is to write a method that takes care of it. Instead of writing a ton of code and repeating yourself, you use a method to encapsulate some functionality, so that you can invoke it a lot without copying code. For example, instead of:
System.out.println("Please enter gender. 1-- Male 2--Female");
gender = input_1.nextInt();
while (gender > 2 || gender < 1) {
System.out.println("Invalid input!");
gender = input_1.nextInt();
}
you really just want to write something like:
gender = askInt("Please enter gender. 1-- Male 2-- Female", 1, 2);
where the askInt is a method you write which takes the text you want to show as prompt, along with the smallest and largest valid value.
Now that you have this function, you can expand its functionalities and all the code that uses this function gets the functionality automatically. So, if you add 'catch invalid input exceptions and re-ask' functionality to this one method, ALL the questions get it.
int askInt(String prompt, int min, int max) {
int result;
while (true) {
System.out.println(prompt);
result = input.nextInt();
if (result >= min && result <= max) return result;
System.out.println("Invalid input!");
}
}
This basic loop will keep looping until the if clause is triggered, causing the method to return, which is the only way out. You can now add handling for NumberFormatException within this one method, within the while loop. You can't go back to the line that caused the problem, but you can go forward, and in a while loop, going forward automatically jumps back to the start (i.e., that's how to go 'backwards'). So, we mix a while loop (which can go backwards) and a catch block, and that's how to solve the problem. And then we put all this in a method, so that we can write this code only once, instead of having to repeat it every time.
You can do it by using a do { _code1 } while (_condition) which execute the _code until _condition is false.
And _code1 is a try {}catch which will catch any exception (error) thrown from inside the try {} block.Here the exception (error) is thrown if the user enters a character instead of a digit.
System.out.println("Please enter gender. 1-- Male 2--Female");
int gender = 0 ;
do {
try {
if (gender == -1) {
System.out.println("Invalid input!");
System.out.println("Please enter gender. 1-- Male 2--Female");
}
gender = input_1.nextInt () ;
}catch (Exception e){
gender = -1 ;
}
}while (gender > 2 || gender < 1);
System.out.println("Enter your age here:");
setAge(sc.nextInt());
How can I validate that users' age is not a char or a negative number?
Ideally, if the users input anything but an int, the program would ask for the input again.
I have tried using a do-while, but doesn't seem to be working.
I am a beginner. Any help is super appreciated.
Thanks!
What you are doing with sc.nextInt() will only allow the user to enter an int or the program will throw an InputMismatchException (thus that part behaves the way you want). If you want to make sure the number isn't negative though, do this:
System.out.println("Enter your age here:");
while (!sc.hasNextInt()) {
System.out.println("Please enter an integer.");
sc.next();
}
int age = sc.nextInt();
if(age < 0) {
//do what you want if the number is negative
//if you're in a loop at this part of the program,
//you can use the continue keyword to jump back to the beginning of the loop and
//have the user input their age again.
//Just prompt them with a message like "invalid number entered try again" or something to that affect
}
else {
setAge(age);
//continue execution
}
The following block will do what you need:
int age;
System.out.println("Please enter an integer");
while (true) {
try{
age= scan.nextInt();
if (age<=0) throw new Exception("Negative number");
break;
} catch(Exception e){
System.out.println("Please enter a positive integer");
}
scan.nextLine();
}
// below just call
setAge(age);
I hope this helps.
import java.util.*;
public class AccountClient {
public static void main(String[] args) {
#SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
boolean infiniteLoop = true;
boolean invalidInput;
int id = 0;
// Create array of different accounts
Account[] accountArray = new Account[1000000];
//Initialize each account array with its own unique id and a starting account balance of $100
for (int i = 0; i < accountArray.length; i++) {
accountArray[i] = new Account("name", i, 100);
}
do {
try {
//inner loop to detect invalid Input
do {
invalidInput = false;
System.out.print("Enter an id: ");
if (!(input.hasNextInt())) {
System.out.println("Invalid input. Please enter a numeric id between 0 and 999999, no letters or symbols allowed. Try again.");
invalidInput = true;
input.nextLine();
}
else {
id = input.nextInt();
accountArray[id].setNumberOfTimesOpened(accountArray[id].getNumberOfTimesOpened() + 1);
input.nextLine();
if (accountArray[id].firstTimeAccount()) {
System.out.print("Please enter a name to register to this account: ");
String name = input.nextLine();
accountArray[id].setName(name);
}
}
} while (invalidInput);
boolean exit;
do {
exit = false;
boolean notAnOption;
int choice;
do {
notAnOption = false;
System.out.print("\nMain Menu\n1: check balance\n2: withdraw\n3: deposit\n4: view transaction history\n5: exit\nEnter a choice: ");
choice = input.nextInt();
if (choice < 1 || choice > 5) {
System.out.println("Sorry, " + choice + " is not an option. Please try again and enter a number between 1 and 5 (inclusive).");
notAnOption = true;
}
} while(notAnOption);
switch (choice) {
case 1: System.out.printf("The balance for your account is $%.2f\n", accountArray[id].getBalance());
break;
case 2: {
boolean withdrawFlag;
do {
System.out.print("Enter the amount you would like to withdraw: ");
double withdrawAmount = input.nextDouble();
input.nextLine();
if (withdrawAmount > accountArray[id].getBalance()) {
System.out.printf("Sorry, you only have an account balance of $%.2f. Please try again and enter a number at or below this amount.\n", accountArray[id].getBalance());
withdrawFlag = true;
}
else {
accountArray[id].withdraw(withdrawAmount);
System.out.printf("Thank you. You have successfully withdrawn $%.2f from your account.\n", withdrawAmount);
withdrawFlag = false;
}
} while (withdrawFlag);
}
break;
case 3: {
System.out.print("Enter the amount you would like to deposit: ");
double depositAmount = input.nextDouble();
input.nextLine();
accountArray[id].deposit(depositAmount);
System.out.printf("Thank you. You have successfully deposited $%.2f into your account.\n", depositAmount);
}
break;
case 4: {
accountArray[id].accountSummary();
}
break;
case 5: {
System.out.println("returning to the login screen...\n");
exit = true;
}
break;
}
} while (exit == false);
}
catch (ArrayIndexOutOfBoundsException ex1) {
System.out.println("Invalid input. Please enter an id between 0 and 999999 (inclusive).");
input.nextLine();
}
catch (InputMismatchException ex2) {
System.out.println("Sorry, invalid input. Please enter an id between 0 and 999999 (inclusive) with no letters or symbols.");
input.nextLine();
}
} while (infiniteLoop);
}
}
Hello everyone, I have a program that simulates an ATM machine. It uses the account class which I created to generate an account for a user after they enter an id between 0 and 999999. They can then perform various tasks like view balance, withdraw, deposit, etc. I'm having an issue though with error checking the program. It compiles with no errors and the first time it goes through the loop, it works perfectly. However, if they hit exit and enter another invalid id, It displays the invalid input message twice. I copied the console of what happens below. Can somebody please explain to me why it does this and how to fix it. Also I'm new to java so if anybody can tell me a better way to error check this it would be much appreciated. As of right now if they enter an int value and it isn't in the range of 0 to 999999, I have to have a separate ArrayIndexOutofBoundsException to catch the error. This seems inefficient. Is there a way I can error check if they entered a numeric value and if they did, check again if they entered an input between 0 and 999999? Thanks
Enter an id: f
Invalid input. Please enter a numeric id between 0 and 999999, no letters or symbols allowed. Try again.
Enter an id: 5
Please enter a name to register to this account: Bob
Main Menu
1: check balance
2: withdraw
3: deposit
4: view transaction history
5: exit
Enter a choice: 5
returning to the login screen...
Enter an id: f
Invalid input. Please enter a numeric id between 0 and 999999, no letters or symbols allowed. Try again.
Enter an id: Invalid input. Please enter a numeric id between 0 and 999999, no letters or symbols allowed. Try again.
Enter an id:
I got zero help from anyone but after hours of frustration I realized this was because I failed to put input.nextLine() after I asked the user to pick a choice. This caused the scanner not to be cleared and caused the statement to be printed twice before it got cleared in the inner loop I had at the start. Once i added the input.nextLine() it worked fine.
So I've written a test class to test a program that will allow me to take in number of courses, letter grades, and course credits and then calculate total weighted points, total credits, and GPA within a loop designed for 3 courses max.
However, I need to validate the number of courses and prove that it will run after both an invalid and valid input have been entered.
I've gotten it so that will prompt the user for a valid number of courses after an invalid response, but once the valid response is input the program just stops instead of running like it is supposed to. Can anyone tell me why?
Here's my code:
import java.util.*;
import java.lang.*;
public class ComputeGpa
{
public static void main(String [] args)
{
Gpa grades1 = new Gpa();
Scanner in = new Scanner (System.in);
System.out.println("Enter number of courses: ");
int courses = in.nextInt();
if(courses > 0)
{
int i = 0;
while(i < 3)
{
System.out.println("Please enter a letter grade.");
String letter = in.next();
char result = letter.charAt(0);
System.out.println("How many credits was this class worth?");
int credits = in.nextInt();
grades1.addToTotals(result, credits);
i++;
}
System.out.printf("GPA: %.2f", grades1.calcGpa());
}
else
{
System.out.println("Number of courses must be greater than 0. Please enter a valid number of courses.");
courses = in.nextInt();
}
}
}
The output for that is as follows:
Enter number of courses:
-2
Number of courses must be greater than 0. Please enter a valid number of courses.
3
And then the program stops running. Where Am I going wrong? I thought the in.next() on the letter String would fix this problem but apparently I was wrong. Any ideas?
Your flow is currently if/else.
int foo = ...;
if(foo > 0) {
//your grade stuff
}
else {
//ask for reinput
}
What ends up happening is you catch the problem input once, but never give your flow the opportunity to check it again.
Instead, use a while loop over an if/else layout, to force re-entry until you get the exact information you want, then continue.
System.out.println("Enter number of courses: ");
int courses = in.nextInt();
while(courses < 0) {
System.out.println("Number of courses must be greater than 0. Please enter a valid number of courses.");
courses = in.nextInt();
}
int i = 0;
//...
I want to check that the data entered by the user via terminal is the correct type needed in the program. If it is not, the code should loop so it asks for the data again before proceeding to the next step.
Example:
The message in terminal is as follows:
Enter Number:
and the user enters a string such as
yes
How can I loop the program and ask for the number again until the user enters a number of type double?
The code so far for this is:
System.out.println("Enter number:");
double number = scanner.nextDouble();
double number;
try
{
number = scanner.nextDouble();
number = parseDouble(inputString);
}
catch(NumberFormatException nfe)
{
System.out.println("Please enter a valid double!");
number = scanner.nextDouble();
number = parseDouble(inputString);
// if the input is not valid again, you need a loop, rethink.
}
As you're using Scanner, you could use Scanner.hasDouble(). To ensure that you do get a valid double, some looping mechanism will be necessary:
boolean numberFound = false;
while (!numberFound) {
if (input.hasNextDouble()) {
number = input.nextDouble();
numberFound = true;
} else {
System.out.println("Invalid double " + input.next());
}
}