Java: Re-running user input in program after invalid entry (loop?) - java

After making an invalid entry, the invalid entry loop continues to appear in this program. I am seeking to keep asking the user for input until he/she enters valid data. Then I'd like to use that input to continue on with the program. I'm positive there's a type of loop associated with this. Thanks for your help.
identInput = JOptionPane.showInputDialog(null, "Please enter a student ID: ");
intID = Integer.parseInt(identInput);
savedIntID = Integer.parseInt(identInput);
for(x = 0; x < studentIDs.length; ++x)
{
if(identInput.equals(studentIDs[x]))
{
JOptionPane.showMessageDialog(null, "The first name associated with \nStudent ID "
+ intID + " is: " + firstNames[x] + "\n" + firstNames[x] + "'s current GPA is: "
+ gPAs[x]);
inputTruth = true;
break;
}
}
//The following will show up and continue to if the data is incorrect. Am not
//sure how to reuse if good data are entered.
while(inputTruth == false)
{
JOptionPane.showInputDialog(null, "The Student ID you entered "
+ savedIntID + "\nis not valid. \nPlease enter another Student ID: ");
}

inputTruth = false;
while(inputTruth == false)
{
identInput = JOptionPane.showInputDialog(null, "Please enter a student ID: ");
intID = Integer.parseInt(identInput);
savedIntID = Integer.parseInt(identInput);
for(x = 0; x < studentIDs.length; ++x)
{
if(identInput.equals(studentIDs[x]))
{
JOptionPane.showMessageDialog(null, "The first name associated with \nStudent ID "
+ intID + " is: " + firstNames[x] + "\n" + firstNames[x] + "'s current GPA is: "
+ gPAs[x]);
inputTruth = true;
break;
}
}
//The following will show up and continue to if the data is incorrect. Am not
//sure how to reuse if good data are entered.
if(inputTruth == false)
{
JOptionPane.showInputDialog(null, "The Student ID you entered "
+ savedIntID + "\nis not valid. \nPlease enter another Student ID: ");
}
}

You just Need a while loop
while(!isInputValid){
//Take your input
if(check == input){
isInputValid = true;
}else{
//Please enter valid input try again.
}
}

is this what you want ?
inputTruth = false;
while(inputTruth == false)
{
for(x = 0; x < studentIDs.length; ++x)
{
if(identInput.equals(studentIDs[x]))
{
JOptionPane.showMessageDialog(null, "The first name associated with \nStudent ID "
+ intID + " is: " + firstNames[x] + "\n" + firstNames[x] + "'s current GPA is: "
+ gPAs[x]);
inputTruth = true;
break;
}
}
if (inputTruth == false) {
identInput = JOptionPane.showInputDialog(null, "The Student ID you entered "
+ savedIntID + "\nis not valid. \nPlease enter another Student ID: ");
}
}

Related

How do I stop my file being overwritten each time I Add to the file?

I am trying to make a list of players to add to a file, so I can store them and recall them when needed.
I have managed to write to the file, but each time I re-write to the file the last file entry gets overridden.
Has anyone got any idea how I can just save each entry to the file without it being overridden each time?
Any help would get greatly appreciated
Thanks in advance!!!!!!
package p;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Runner {
public static final Scanner input = new Scanner(System.in);
public static void main(String[] args) throws IOException {
FileWriter writer = new FileWriter("output.txt");
PlayerData player = null;
List<PlayerData> players = new ArrayList<>();
System.out.println("How many players do you want to register? : ");
int num = input.nextInt();
while (true) {
System.out.println("Plz enter Name : ");
String name = input.next();
writer.write("Name: " + name + System.lineSeparator());
System.out.println("Plz enter age : ");
String age = input.next();
writer.write("Age: " + age + System.lineSeparator());
System.out.println("Plz enter Player_id : ");
String player_id = input.next();
writer.write("Player_id: " + player_id + System.lineSeparator());
System.out.println("Plz enter agent_id : ");
String agent_id = input.next();
writer.write("Agent_id:" + agent_id + System.lineSeparator());
System.out.println("Plz enter status : ");
String status = input.next();
writer.write("Status: " + status + System.lineSeparator());
System.out.println("Plz enter position : ");
String position = input.next();
writer.write("Position: " + position + System.lineSeparator());
System.out.println("Plz enter valuation : ");
Double valuation = input.nextDouble();
writer.write("Value: " + valuation + System.lineSeparator());
System.out.println("\n");
player = new PlayerData(name, age, player_id, agent_id, valuation, status, position);
players.add(player);
System.out.println("Information Entered: \n" + player + "\n" + "Name : " + name + "\n" + "Age: " + age
+ "Player id: " + player_id + "\n" + "Agent id: " + agent_id + "\n" + "Player Value: " + valuation
+ "\n" + "Player Status:" + status + "\n" + "Player position:" + position + "\n");
writer.close();
if (players.size() == num)
break;
}
System.out.println(players);
}
}
FileWriter writer = new FileWriter("output.txt", true);

How to do, Do while loop for this code?

I have this java code:
public class Ages {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int value = 0;
String name;
int age;
System.out.print("Hey, what's your name? ");
name = keyboard.next();
System.out.println();
System.out.print("Ok, " + name + ", how old are you? ");
age = keyboard.nextInt();
System.out.println();
do{
if(age < 16){
System.out.println("You can't visit in the museum, " + name + ".");
if(age < 18);
System.out.println("You can't visit in the park, " + name + ".");
}
if (age < 25){
System.out.println("You can't visit if you have a car, " + name + ".");
}
if (age >= 25){
System.out.println("You can do anything, " +
name + ".");
}
while(age > 300);
System.out.println("It's not correct..Try Again, " + name +
".");
}
}
and I need that user write the wrong answer, he will get the question again "how old are you?", and after he get another tries..
what I goona do?
Thanks for the help!! :)
One the while block is not correct you have to use :
System.out.println("It's not correct..Try Again, " + name + ".");
do {
if (age < 16) {
System.out.println("You can't visit in the museum, " + name + ".");
if (age < 18);
System.out.println("You can't visit in the park, " + name + ".");
}
if (age < 25) {
System.out.println("You can't visit if you have a car, " + name + ".");
}
if (age >= 25) {
System.out.println("You can do anything, "
+ name + ".");
}
//while(age > 300);<<----------wrong position
System.out.println("It's not correct..Try Again, " + name + ".");
} while (age > 300);//<<----------correct position
Two
The while condition seams not correct, you have to check with min and max age, instead of just max, so you can use :
while (age < minAge || age > maxAge );
So if the age is less then the min OR great then the max repeat again
Three this if will not ever executed :
if (age < 18);//<<----------------note the ; it mean your if is end
System.out.println("You can't visit in the park, " + name + ".");
Four
Instead you can read the age inside your loop :
System.out.print("Hey, what's your name? ");
name = keyboard.next();
System.out.println();
do {
System.out.print("Ok, " + name + ", how old are you? ");
age = keyboard.nextInt();
System.out.println();
....
}while(..);
Hope this can gives you an idea about your problem.
1)You should use this condition : if (age >= 25 && age <= 300){ instead of
if (age >= 25){.
Otherwise the condition is true even if age is over 300 and you don't want to:
while(age > 300);
2)You should also allow the user to enter a new input if the value is not correct.
age = keyboard.nextInt(); should be in the loop.
3) You should allow the loop to finish.
In the while statement, you could specify the condition that requires a new input from the user :
while (age > 300)
This gives the code (not tested) :
int age;
do{
age = keyboard.nextInt();
if(age < 16){
System.out.println("You can't visit in the museum, " + name + ".");
}
else if(age < 18){
System.out.println("You can't visit in the park, " + name + ".");
}
else if (age < 25){
System.out.println("You can't visit if you have a car, " + name + ".");
}
if (age >= 25 && age <= 300){
System.out.println("You can do anything, " +
name + ".");
}
else{
System.out.println("It's not correct..Try Again, " + name + ".");
}
}
while (age > 300);
Try this, please:
public class Ages {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int value = 0;
int age;
System.out.print("Hey, what's your name? ");
String name = keyboard.next();
System.out.println();
while(true) {
System.out.print("Ok, " + name + ", how old are you? ");
age = keyboard.nextInt();
System.out.println();
if (age <= 300) {
break;
}
System.out.println("It's not correct..Try Again, " + name +
".");
}
if(age < 16) {
System.out.println("You can't visit in the museum, " + name + ".");
}
if(age < 18){
System.out.println("You can't visit in the park, " + name + ".");
}
if (age < 25){
System.out.println("You can't visit if you have a car, " + name + ".");
}
if (age >= 25){
System.out.println("You can do anything, " +
name + ".");
}
}
}

line of Java is printing duplicates

case 2:
System.out.println("Please enter Book ID: ");
String userinput2 = sc.next();
for (int i = 0; i < myBooks.size(); i++) {
if (myBooks.get(i).getBookID().contains(userinput2)) {
System.out.println("BookID: " + myBooks.get(i).getBookID() + "\nTitle: "
+ myBooks.get(i).getTitle() + "\nAuthor: " + myBooks.get(i).getAuthor());
System.out.println("Please enter new details of book");
System.out.println("Title: ");
String userinput7 = sc.next();
myBooks.get(i).setTitle(userinput7);
System.out.println("Author: ");
String u1 = sc.next();
myBooks.get(i).setAuthor(u1);
myBooks.get(i).setOnLoan(false);
myBooks.get(i).setNumLoans(0);
System.out.println("---------------------------------------------------");
System.out.println("The book has been successfully updated");
System.out.println("Book ID: " + myBooks.get(i).getBookID() + " " + "\nTitle: "
+ myBooks.get(i).getTitle() + " " + "\nAuthor: " + myBooks.get(i).getAuthor());
System.out.println("---------------------------------------------------");
}
else { System.out.println("Please enter a correct bookID");
}
}
I'm having a problem with my validation check. If the user enters a bookID that doesn't exist, instead of printing out "please enter a correct bookID" once, it prints it out 4 times, which amounts to the number of objects i have in the array list. Is there a way to sort this?
Your else statement is in the middle of the for statement
for (int i = 0; i < myBooks.size(); i++) {
if (myBooks.get(i).getBookID().contains(userinput2)) {
[[do stuff]]
}
else { System.out.println("Please enter a correct bookID");
}
}
It looks like it should be in the middle of the if statement
if (myBooks.get(i).getBookID().contains(userinput2)) {
for (int i=...) {
[[do stuff]]
}
}
else { System.out.println("Please enter a correct bookID");
}

java - issue with double, when user enter letter/signs, the program fails to run

I am a beginner and I am trying to make a simple calculator program using double variables, so that it allows users to add both int and double numbers to calculate. But whenever the user enters a String, the program fails. I have tried a lot to resolve this simple issue. I hope someone can help me.
Please enter first number: So when the user enters 25/25.5 everything works, but when user enters a letter such as e/f/k etc, the program fails. I have tried the following code after "Please enter first number":
if (user1 == aswin.nextDouble())
{
System.out.println("Continue");
}
else (user1 == Double.parseDouble(str))
{
System.out.println("Invalid Entry - Please enter Only numbers");
}
Following are the actual program, without the above code:
import java.util.Scanner;
import java.text.NumberFormat;
public class NewTwo_Calculator_IF_Statement {
public static void main (String [] args)
{
Scanner aswin = new Scanner (System.in);
double user1 = 0, user2 = 0, mult, div, sub, ad;
char user3;
boolean run = true;
String user;
System.out.println ("Welcome to ASWINS calculator" + '\n');
System.out.print ("Please enter First number - ");
user1 = aswin.nextDouble();
System.out.print("Please Enter Second number - ");
user2 = aswin.nextDouble();
System.out.println ('\n' + "Please choose following options" + '\n');
System.out.println ("Type either A/a/+ for Addition ");
System.out.println ("Type either S/s/- for Substraction");
System.out.println ("Type either D/d or / for Division ");
System.out.println ("Type M/m/* for Multiplication");
user3 = aswin.next().charAt(0);
mult = user1*user2;
ad = user1+user2;
sub = user1-user2;
div = user1/user2;
if (user3 == ('*') || user3 == ('m') || user3 == ('M'))
{
System.out.println('\t' + "Multiplication of " + user1 + " and " +user2 + " is = " + mult + '\n');
} else if (user3 == ('+') || user3 == ('a') || user3 == ('A'))
{
System.out.println ('\t' + "Addition of " + user1 + " and " +user2 + " is = " + ad + '\n');
} else if(user3 == ('-') || user3 == ('s') || user3 == ('S'))
{
System.out.println ('\t' + "Substraction of " + user1 + " and " +user2 + " is = " + sub + '\n');
} else if (user3 == ('/') || user3 == ('d') || user3 == ('D'))
{
System.out.println ('\t' + "Division of " + user1 + " and " +user2 + " is = " + div + '\n');
} else
{
System.out.println('\t' + "Invalid Input");
}
System.out.println ("Please Enter 'e' or type 'exit' to exit the program OR type anything else to stay on the page" + '\n');
user = aswin.next();
if (user.equalsIgnoreCase("e") || (user.equalsIgnoreCase("exit")))
{
System.out.println("Thanks for Entering -> " + user + " <-");
System.out.println ("You QUIT the page, Thanks and Hope you will use my(Aswin's) Calculator again");
System.exit(0);
}
else
{
System.out.println("Thanks for Entering -> " + user + " <-");
System.out.println (" You are STAYING on the page, Thanks " + '\n');
System.out.println ( "Thank you so much for using my calculator");
}
}
}
On the official documentation, it is mentioned that .nextDouble() throws a InputMismatchException when the next token (user input) does not match a float (such as when the user inputs a letter). You can handle such exception by using a try catch block:
try{
user1 == aswin.nextDouble()
}catch(InputMismatchException e){
// User input is invalid
System.out.println("Invalid Entry - Please enter Only numbers");
}
You can read more about catching and handling exceptions here.

Java Programming Simple If/Else statement project

Ok guys so I'm stuck trying to write some code in java, I cant get the code to display the pricing option for fullsize. I can't get the program to continue onto the second option I have listed as Case 2.
The project basically gives the user the option to ask if he is renting a car [Y or N]:
if Y is inputed the next question
it ask is "Compact of Full-size?",
if the user selects compact the project displays that the user has selected compact and
if the code displays fullsize the project displays that the user has selected fullsize.
Then it asks the user if they have a coupon if the users answer Y for the coupon the price is 7% off of 30.50.
If the user answers N the price is a normal 30.50. The fullsize normal price is 40.50 and the price with a coupon is 7% off of 40.50. The following is the code i have written currently.
The code:
public class CarRental {
public static void main(String[] args) {
for (int i = 0; i < 4; i++) {
System.out.println("Programmed by .");
double standardCompact = 30.50;
double couponCompact = ((30.50) - (30.50 * 0.07));
double standardFullSize = 40.50;
double couponFullSize = ((40.50) - (40.50 * 0.07));
//Scanner Input
Scanner input = new Scanner(System.in);
System.out.print("Rent a Car? [Y or N]: ");
//Response String
String response = input.next().toUpperCase();
if (response.equals("N")) {
System.out.println("You entered no. Bye. ");
} else if (response.equals("Y")) {
System.out.print("Compact or Full-Size? [C or F]: ");
//case1
response = input.next().toUpperCase();
if (response.equals("C")) {
System.out.println("You selected Compact. ");
} else if (response.equals("F")) {
System.out.println("You have selected Full-Size. ");
System.out.print("Have coupon? [Y or N]: ");
response = input.next().toUpperCase();
if (response.equals("N")) {
System.out.println("Price is" + " " + standardCompact + " " + "per day.");
} else if (response.equals("Y")) {
System.out.println("Price is" + " " + couponCompact + " " + "per day.");
//case 2
response = input.next().toUpperCase();
if (response.equals("F")) {
System.out.println("You have selected Full-Size.");
System.out.println("Have coupon? [Y or N]: ");
response = input.next().toUpperCase();
if (response.equals("N")) {
System.out.println("Price is" + " " + standardFullSize + " " + "per day.");
} else if (response.equals("Y")) {
System.out.println("Price is" + " " + couponFullSize + " " + "per day.");
}
}
}
You're missing some }s after your else clauses. Example:
response = input.next().toUpperCase();
if (response.equals("C")) {
System.out.println("You selected Compact. ");
//Put code that should only execute if you select Compact here.
}else if(response.equals("F")){
System.out.println("You have selected Full-Size. ");
//Put code that should only execute if you select Full-size here.
//Should have a } here!
//Put code that should always execute here.
Because you never close the block of code in the else clause, all of the code that follows is still part of the else, and therefore will only be executed if the else is selected, not under every circumstance as you had intended.
You are opening lots of brackets { but not closing them where you need }.
I usually not just handing the code, but I've noticed you done must of the job, but confused where to close the brackets and a little bit at the program flow.
I only changed it a bit, there is a lot that you can cut and reuse code.
public static void main(String[] args){
for(int i = 0; i < 4; i++) {
System.out.println("Programmed by .");
double standardCompact = 30.50;
double couponCompact = ((30.50)-(30.50 * 0.07));
double standardFullSize = 40.50;
double couponFullSize = ((40.50)-(40.50 * 0.07));
//Scanner Input
Scanner input = new Scanner(System.in);
System.out.print("Rent a Car? [Y or N]: ");
//Response String
String response = input.next().toUpperCase();
if (response.equals("N")){
System.out.println("You entered no. Bye. ");
}
else if (response.equals("Y")) {
System.out.print("Compact or Full-Size? [C or F]: ");
response = input.next().toUpperCase();
if (response.equals("C")) {
System.out.println("You selected Compact. ");
//case1
System.out.print("Have coupon? [Y or N]: ");
response = input.next().toUpperCase();
if (response.equals("N")) {
System.out.println("Price is" + " " + standardCompact + " " + "per day.");
}
else if (response.equals("Y")) {
System.out.println("Price is" + " " + couponCompact + " " + "per day.");
}
}
else if(response.equals("F")) {
System.out.println("You have selected Full-Size. ");
//case 2
System.out.print("Have coupon? [Y or N]: ");
response = input.next().toUpperCase();
if (response.equals("N")) {
System.out.println("Price is" + " " + standardFullSize + " " + "per day.");
}
else if (response.equals("Y")) {
System.out.println("Price is" + " " + couponFullSize + " " + "per day.");
}
}
}
}
}
The problem with this code is all your code is under the if statemente for Full-Size so the case 2 only executes when you select full-size , Yes to coupon and after showing the final message you press F again the code should look like this.
public class CarRental {
public static void main(String[] args){
for(int i=0; i<4; i++){
System.out.println("Programmed by .");
double standardCompact = 30.50;
double couponCompact = ((30.50)-(30.50 * 0.07));
double standardFullSize = 40.50;
double couponFullSize = ((40.50)-(40.50 * 0.07));
//Scanner Input
Scanner input = new Scanner(System.in);
System.out.print("Rent a Car? [Y or N]: ");
//Response String
String response = input.next().toUpperCase();
if (response.equals("N")){
System.out.println("You entered no. Bye. ");
}else if (response.equals("Y")) {
System.out.print("Compact or Full-Size? [C or F]: ");
//case1
response = input.next().toUpperCase();
if (response.equals("C")) {
System.out.println("You selected Compact. ");
System.out.print("Have coupon? [Y or N]: ");
response = input.next().toUpperCase();
if (response.equals("N")) {
System.out.println("Price is" + " " + standardCompact + " " + "per day.");
} else if (response.equals("Y")) {
System.out.println("Price is" + " " + couponCompact + " " + "per day.");
}
//case 2
}else if(response.equals("F")){
System.out.println("You have selected Full-Size. ");
System.out.println("Have coupon? [Y or N]: ");
response = input.next().toUpperCase();
if (response.equals("N")) {
System.out.println("Price is" + " " + standardFullSize + " " + "per day.");
} else if (response.equals("Y")) {
System.out.println("Price is" + " " + couponFullSize + " " + "per day.");
}
}
}
}
}
As you can see in the code above is really important to correctly close conditional blocks so the code really does what you expect it to do.
Using flow diagrams is a good support for learning how programming languages really work.

Categories