JAVA Reorganizing While loop in array when considering user input. - java

My program basically allows the user to enter grades (elements) which are stored in a Gradebook (array). The user also has the option to change the grades (elements) in the Gradebook (array).
My issue is that once the while loop loops and the user is asked "Make more changes? Enter Yes or No" If I enter yes, then the user asked which grade to change, is allowed to replace the grade, and the modified gradebook prints. However, if I enter "no" just the gradebook prints. Is there a way I can get the program to print "Good bye!" (signaling the end of the program) if the user enters no? I believe I'm supposed reorganize my code and set a while-loop with boolean = false? But I'm not sure how to get started...
Any help would be greatly appreciated. Thank you.
System.out.println("Make changes? Enter Yes or No");
String makeChanges = input.next();
if (makeChanges.equals("no")) {
System.out.println("Good bye!");
}
while (makeChanges.equalsIgnoreCase("Yes")) {
// Ask user if what grade they would like to change
//int index = NumberReader.readPositiveInt(input, "Enter the index of the grade to be changed: (1 to " + grades + ") : ", "Invalid index input", index);
int index = NumberReader.readCappedPositiveInt(input, "Enter the index of the grade to be changed: (1 to " + grades + ") : ", "Invalid index input", numOfGrades);
System.out.println("Enter grade (limit to two decimal places)" + ": ");
// offset the index by one
mogrades[index - 1] = NumberReader.readPositiveDouble(input, "Enter grade " + index + " :",
"Invalid data entered");
System.out.println("The Grade book contains: ");
printArray(mogrades);
System.out.println("Make more changes? Enter Yes or No");
makeChanges = input.next();
System.out.println(makeChanges);
System.out.println("The Grade book contains: ");
printArray(mogrades);
}
}

Break statements are used to exit loops. You could try this in the while loop:
if (makeChanges.equalsIgnoreCase("No")) {
System.out.println("Good Bye!");
break;
}
If you want to exit the entire program, use System.exit(0);
if (makeChanges.equalsIgnoreCase("No")) {
System.out.println("Good Bye!");
System.exit(0);
}
Here is a simple program demonstrating how this would work:
import java.util.Scanner;
public class Simple {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String makeChanges = "Yes";
while (makeChanges.equalsIgnoreCase("Yes")) {
System.out.println("Make more changes? Enter Yes or No:");
makeChanges = input.next();
if (makeChanges.equalsIgnoreCase("No")) {
System.out.println("Good Bye!");
System.exit(0);
}
}
}
}
And here is the output from the command line:
daniel#4.3:StackOverflow$ javac Simple.java
daniel#4.3:StackOverflow$ java Simple
Make more changes? Enter Yes or No:
Yes
Make more changes? Enter Yes or No:
Yes
Make more changes? Enter Yes or No:
No
Good Bye!

Related

IDE prints both lines before I can parse user's inputs

so I am currently having difficult trying to fix this. In short, I'm trying to create a banking application for a class. I'm writing a method to print and get user's inputs but the print lines print out both lines before I can get inputs. Here is my implementation.
boolean done = false;
while(!done) {
System.out.println("Welcome to Running Bank"
+ "\nWhat would you like to do?"
+ "\n1-Create Account"
+ "\n2-Log-In"
+ "\n3-Exit");
choice = scanner.nextInt();
switch(choice) {
case 1:
System.out.println("Input your username(No more than 15 characters: ");
Username = scanner.nextLine();
System.out.println("Input your password(Must be at least 8 characters and not over 24): ");
Password = scanner.nextLine();
}
}
}
What I expected it to do was to print out "Input your username" then after I get the user's input for it then to print the next line. However, what happening right now is that both lines get print before I can put in anything.
Thank you in advanced.
boolean done = false;
while(!done) {
System.out.println("Welcome to Running Bank"
+ "\nWhat would you like to do?"
+ "\n1-Create Account"
+ "\n2-Log-In"
+ "\n3-Exit");
choice = scanner.nextInt();
scanner.nextLine();
switch(choice) {
case 1:
System.out.println("Input your username(No more than 15 characters: ");
Username = scanner.nextLine();
System.out.println("Input your password(Must be at least 8 characters and not over 24): ");
Password = scanner.nextLine();
}
}
}
This should work now. I have added a scanner.nextLine() after inputing choice

After input, println prints nothing out

I am making a game and it prompts you for your name and after you type in your name it asks you to confirm it by typing "N" or "Y". After pressing N it doesn't print anything back out although it does take in input but doesn't prompt you to do so as it doesn't print anything else. Only Y works. I have tried everything but it doesn't work.
This is the code I have done to confirm the name:
private static void comfirmName() {
System.out.println("Is " + name + " your name?");
try {
Thread.sleep(1000);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
System.out.println("Y/N");
if (input.nextLine().toUpperCase().equals("Y")) {
System.out.println("There is something you should know...");
}
if (input.nextLine().toUpperCase().equals("N")) {
System.out.println("Enter your name:");
name = input.nextLine();
System.out.println("Is " + name + " your name?");
}
if (!input.nextLine().toUpperCase().equals("N") && !input.nextLine().toUpperCase().equals("Y")) {
System.out.println("Please enter Y or N");
}
}
This is the output:
Welcome to Enchanted Mage!
Here we will venture into the dangers of this planet!
First of all, you must tell me your name, venturer!
Type in your name:
ots wng
Hello there ots wng!
Is ots wng your name?
Y/N
n
otswng
nothing is hapening
ummm
Please enter Y or N
BUILD SUCCESSFUL
There are no errors but it is really annoying to get any output out.
Just add an input before entering the ifs, just like that:
String inputAnswer = input.nextLine().toUpperCase();
and to be cleaner, just change the input.nextLine inside the ifs to the variable you just created, like that:
if(inputAnswer.equals("Y")){
System.out.println("There is something you should know...");
}
I just tested that and it works. feel free to ask anything else!
Read only once the confirmation.
private static void comfirmName() {
System.out.println("Is " + name + " your name?");
System.out.println("Y/N");
String confirmation = input.nextLine().toUpperCase(); //Read only once the user confirmation
if (confirmation.equals("Y")) {
System.out.println("There is something you should know...");
}
if (confirmation.equals("N")) {
System.out.println("Enter your name:");
name = input.nextLine();
System.out.println("Is " + name + " your name?");
}
if (!confirmation.equals("N") && !confirmation.equals("Y")) {
System.out.println("Please enter Y or N");
}
}
Output
Is Dan your name?
Y/N
n
Enter your name:
Dan
Is Dan your name?

Line of code in while loop executing at wrong time

Program code:
public static void main(String[] args) throws IOException {
System.out.print("Welcome to my guessing game! "
+ "Would you like to play (Y/N)? ");
yesOrNoAnswer = (char)System.in.read();
if(yesOrNoAnswer == 'Y') {
System.out.print("\n\nGuess the number (between 1 and 10): ");
while(AnswerIsCorrect == false) {
guess = System.in.read();
if(guess == correctAnswer) {
AnswerIsCorrect = true;
}
else {
System.out.print("\nYou guessed wrong! Please try again: ");
}
}
System.out.print("You guessed correct! Congratulations!"
+ "\n\nPress any key to exit the program . . .");
System.in.read();
}
}
Expected output:
Welcome to my guessing game! Would you like to play (Y/N)? Y
Guess the number (between 1 and 10):
Actual output:
Welcome to my guessing game! Would you like to play (Y/N)? Y
Guess the number (between 1 and 10):
You guessed wrong! Please try again:
When I input 'Y' at the first question (would you like to play) it proceeds to output, "Guess the number between 1 and 10: " This is a good output. However, before I can enter a number, it instantly outputs, "You guessed wrong! Please try again: "
How can I fix this code to achieve the expected output?
The problem lies at your usage of System.in.read().
System.in.read() will read characters one by one and return them as ints. If I enter 1, System.in.read() will return 49 because that's what the character 1 is encoded to.
The reason why it immediately prints that your guess is wrong without letting you type anything is that System.in.read() reads new line characters as well. If there is anything unread, it will read that, instead of asking for new input. There is a new line character after the Y you entered, so it reads that new line character.
You should instead use a Scanner:
Scanner scanner = new Scanner(System.in); // create a new scanner
System.out.print("Welcome to my guessing game! "
+ "Would you like to play (Y/N)? ");
yesOrNoAnswer = scanner.nextLine().charAt(0); // reading the first character from the next line
if(yesOrNoAnswer == 'Y') {
System.out.print("\n\nGuess the number (between 1 and 10): ");
while(AnswerIsCorrect == false) {
guess = Integer.parseInt(scanner.nextLine()); // get an int from the next line
if(guess == correctAnswer) {
AnswerIsCorrect = true;
}
else {
System.out.print("\nYou guessed wrong! Please try again: ");
}
}
System.out.print("You guessed correct! Congratulations!"
+ "\n\nPress any key to exit the program . . .");
scanner.nextLine();
}
Scanner.nextLine() will return the input the user typed as a string and it ignores new line characters.

How Do I prompt the user to re-enter his/her input if it doesn't meet my condition?

I am trying to get the user to enter the number of adults, and for the program to continue running, the condition is (adults>0). How do I rewrite my code so that if the user enters any value that is <=0, it displays the message "Wrong input, Try again!" and allows the user to re-enter the input.
Here's my code so far:
if (achoice.equals("1")) {
System.out.println(" ");
System.out.print("\tEnter number of adults: ");
int adults = input.nextInt();
Like this:
do {
System.out.println(" ");
System.out.print("\tEnter number of adults: ");
int adults = input.nextInt();
} while (adults <= 0);

printing to screen counter value of an array in system.out.print.ln

I am trying to enter Strings into an array Input by user - using Scanner.
I am prompting user for total amount of students and saving this in a variable to determine array length.
Each loop I would like to ask the question "what is the name of student" (and their position in counter) ie student #1 student# 2 etc
The below code seems to be working as is.
System.out.println("what is first name of student")
when I add to the end of this + counter+ I get an error message "illegal start of expression"
Please help, and find entire code below. Thanks
public class Student
{
public static void main(String[]args)//Main method
{
Scanner input=new Scanner(System.in);
int studentNumber;// declare a variable to store # students
System.out.println( "Please enter the number of students.");
noStudent=input.nextInt();//take in user input for number of racers
while (noStudent<2 || noStudent>20)// validate users
{
//while users input is invalid, alert user and prompt user for a valid number
System.out.println("Invalid input please re-enter a number between 2 and 20.");
noStudent=input.nextInt();
}
String[] nameArray = new String[noStudent];
for(int counter = 0; counter<nameArray.length; counter++)
{
System.out.println("please enter first name of student " + i+);
nameArray[counter] = input.next();
}
}//end main
}//end class
try to do (if it's java):
for(int counter = 0; counter<nameArray.length; counter++)
{
System.out.println("please enter first name of student " + (counter+1));
nameArray[counter] = input.next();
}
System.out.println("please enter first name of student " + i+);
Should be
System.out.println("please enter first name of student " + counter);
Also, I think you may want to declare the variable noStudent instead of studentNumber. You're using noStudent a bunch of times, but I don't see it declared. And I see studentNumber declared, but I don't see it ever used.
int noStudent;
System.out.println( "Please enter the number of students.");
noStudent=input.nextInt();

Categories