Program doesn't exit when I hit n or N? - java

I have the following homework problem:
Q1. Use nested for loops statements to draw empty boxes of any character (input from user). The boxes have the same number of rows and columns (input from the user; valid range: 5 to 21). Test for errors in input (including type)
SAMPLE OUTPUT:
Do you want to start(Y/N): y
How many chars/last row? n
Not an integer! Try again! How many chars/last row? fgfgfg
Not an integer! Try again! How many chars/last row? 7.6
Not an integer! Try again! How many chars/last row? 34
ERROR! Valid range 5 - 21. How many chars/last row? 7
What character? k
Do you want to continue(Y/N): y
I've written the below code, but it doesn't exit when I hit 'n' or 'N', and I'm not sure why. How would I fix this?
public static void main(String[] args) {
Scanner input = new Scanner(System. in );
char answer = 'n';
int row = 0;
char output = 'k';
do {
System.out.println("DO YOU WANT TO START Y OR N?");
answer = input.next().charAt(0);
System.out.println("enter the number of rows");
while (!input.hasNextInt()) {
System.out.println("Not an integer,try again ");
input.next();
}
row = input.nextInt();
while (row < 5 || row > 21) {
System.out.println("ERROR! Valid range 5 - 21. How many chars/last row?");
row = input.nextInt();
}
System.out.println("WHAT CHARACTER?");
output = input.next().charAt(0);
for (int i = 0; i < row; i++) { //nested for loop to create the box
System.out.print(output);
}
System.out.println();
for (int i = 0; i < row - 2; i++) {
System.out.print(output);
for (int j = 0; j < row - 2; j++) {
System.out.print(" ");
}
System.out.print(output);
System.out.println();
}
for (int i = 0; i < row; i++) {
System.out.print(output);
}
System.out.println();
System.out.println();
System.out.println("DO YOU WANT TO CONTINUE ? Y OR N");
answer = input.next().charAt(0);
} while (answer == 'Y' || answer == 'y');
input.close();
System.out.println("game stop");
}

You need to add condition for N after Do you want to start(Y/N): and Do you want to continue(Y/N):
System.exit(0) is used to terminate the program.
Put this code
System.out.println("DO YOU WANT TO START Y OR N?");
answer = input.next().charAt(0);
if(answer == n || answer == N){
System.exit(0);
}
And this for Do you want to continue(Y/N):
System.out.println("DO YOU WANT TO CONTINUE ? Y OR N");
answer = input.next().charAt(0);
if(answer == n || answer == N){
System.exit(0);
}
Edit
If you want to print 'Game Stop' if the answer is N, then use Thread.sleep(timeInMilliseconds); before System.exit(0)
if(answer == n || answer == N){
Thread.sleep(5000); //This will make console wait for 5 seconds before exiting.
System.out.println("Game Stop."); //game stop will be printed for 5 seconds
System.exit(0);
}

The simplest way to do this is:
Check for input "N" INSIDE the loop, and break out of the while loop, possibly like so:
if ((answer == 'n') || (answer == 'N')) {
break;
}
Also, you're checking for y/n input 2 times in this program. A better method of writing this would be to use a normal while loop instead of a do-while loop; clearly, in the question if you input N right at the beginning you shouldn't be running through the program at all. A Do-While loop is useful to ensure that the program runs at least once (which is not what should happen here; the program should only run if the input is valid eg: "y"). While using a DW-loop is "ok", a while loop would serve the purpose better here.
Your loop can be written like so instead:
// you need this line to initially print the y/n question.
System.out.println("DO YOU WANT TO START Y OR N?");
// get an input and check if it is not n
while (Character.toUpperCase(input.next().charAt(0)) != 'N') {
// do stuff here
System.out.println("DO YOU WANT TO CONTINUE ? Y OR N"); // ask for next input
}

Related

Repeating a statement in while loop Java

Sorry for the newbish question, am quite new with Java.
So I want to display an error message when user input is outside of the bounds (Lesser than 0, greater than 100) which I've managed to do but I also want that the user can try again but my current code only continues with the execution of the program.
This is what I have now:
import java.util.Scanner;
public class storeQuota {
public static void main(String [] args) {
Scanner input = new Scanner (System.in);
int quotas [] = new int [100];
int NumberOfWorkers = 100;
for (int i = 0; i<numberOfWorkers; i++) {
if (i == 0) {
System.out.print("Enter the quota for the 1st student: ");
}
else if (i == 1) {
System.out.print("Enter the quota for the 2nd student: ");
}
else if (i == 2) {
System.out.print("Enter the quota for the 3rd student: ");
}
else if (i >= 3) {
System.out.print("Enter the quota for the " + (i+1) + "th student: ");
}
while (true) {
quotas[i] = input.nextInt();
if (quotas[i] > 100 || quotas[i] < 0)
System.out.println("Error - Can only be between 0 and 100.");
break;
}
}
//Printing all quotas.
System.out.println("Thank you for your input. Your entered quotas are: ");
for (int i=0; i<numberOfWorkers; i++)
{
System.out.print(quotas[i] + ", ");
}
input.close();
}
}
With this code, the error message is correctly displayed when a user inputs an int that isn't between 0 and 100 but the user will be unable to try again, the program continues to ask for the next quoata.
I think the problem is located in this line
break;
after
System.out.println("Error - Can only be between 0 and 100.");
which always breaks the while loop. Instead you only want to break the while loop if the input is in valid range. I would not use while(true) but some sort of conditional variable which is set to false in the while loop if the input is in valid range, also because while(true) is not a good programming practice from my point of view.
Your problem is using Break;
rather than using that, you should change the while(true) to while(false), you've also forgot to add curly brackets around the if statement.
boolean x = true;
while (x){
quotas[i] = input.nextInt();
if (quotas[i] > 100 || quotas[i] < 0){
System.out.println("Error - Can only be between 0 and 100.");
x = false;
}
}
also I suggest learning exceptions as they would make this 10x easier.
When executed, "break" breaks the loop you are currently in. In your code, break is executed irrespective of what the input is resulting in the unwanted result.
Simplest solution would be (closest to your original code):
while(true) {
quotas[i] = input.nextInt();
if (quotas[i] > 100 || quotas[i] < 0) {
System.out.println("Error - Can only be between 0 and 100.");
} else {
break;
}
}
Here, the loop will break only if correct input is entered.
You haven't used curly braces in if condition.
while (true) {
quotas[i] = input.nextInt();
if (quotas[i] > 100 || quotas[i] < 0) {
System.out.println("Error - Can only be between 0 and 100.");
break;
}
}

I can't figure out to print if input is empty or not

So I made a program, which loops 2 questions from an array. What I want to happen here is to prompt if the user entered blank or empty, and also if the user inputs any other letter, number or symbol aside from a, b, and c.
What's happening here is whenever I input a on the first question it also prints "That answer can't be blank" which it shouldn't since I entered a valid input.
for(int i = 0; i < question.length; i++){
do{
System.out.print(question[i].prompt + "\nAnswer: ");
answer = s.nextLine();
if(!answer.equalsIgnoreCase("a") &&
!answer.equalsIgnoreCase("b") &&
!answer.equalsIgnoreCase("c")){
System.out.println("Invalid input!\n");
} if(!answer.isEmpty()){
System.out.println("The answer can't be blank.\n");
}
} while(!answer.equalsIgnoreCase("a") &&
!answer.equalsIgnoreCase("b") &&
!answer.equalsIgnoreCase("c") &&
!answer.isEmpty());
if(answer.equalsIgnoreCase(question[i].answer)){
score++;
}
}
your code should look something like this...
for(int i = 0; i < question.length; i++){
do{
System.out.print(question[i].prompt + "\nAnswer: ");
answer = s.nextLine();
if(answer.isEmpty()){
System.out.println("The answer can't be blank.\n");
}else if(!answer.equalsIgnoreCase("a") &&
!answer.equalsIgnoreCase("b") &&
!answer.equalsIgnoreCase("c")){
System.out.println("Invalid input!\n");
}
} while(!answer.equalsIgnoreCase("a") &&
!answer.equalsIgnoreCase("b") &&
!answer.equalsIgnoreCase("c") &&
!answer.isEmpty());
if(answer.equalsIgnoreCase(question[i].answer)){
score++;
}
}
What I have changed in the code: removed multiple ifs, instead used if-else, and removed ! from !answer.isEmpty().
Hoping this will help you :-)
happy coding

How to show an input is invalid in this java code

I'm trying to make it so that when the user enters anything but y/n it'll say error and when they enter n it'll say have a great day. This is what I have so far, but I keep running into trouble.
This is the assignment:
Write a program that gets an integer from the user, say x, and then
prints an x by x square, and it prints that square x number of times.
For example, if the user enters 4, your program will print a 4x4
square four distinct times. Specifics:
The user enters a value 3-15. Input validation: only accept 3-15.
Allow the user to repeat the program if desired. Input validation: Y
or N only, but also allow lowercase entries.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("*******************************************************\n"
+ "*******************SQUARE GENERATOR********************\n"
+ "*******************************************************\n"
+ "\nThis program will let you enter an integer between\n"
+ "3-15 and print out that many squares of that dimension.\n");
char answer = 'y';
while (answer == 'y' || answer == 'Y') {
System.out.println("Enter the square size --> ");
int x = keyboard.nextInt();
while (x < 3 || x > 15) {
System.out.println("Error: Select a number between 3 and 15 inclusive: ");
x = keyboard.nextInt();
}
for (int i = 0; i < x; i++) {
for (int j = 0; j < x; j++) {
for (int k = 0; k < x; k++) {
System.out.print("X");
}
System.out.println("");
}
System.out.println("");
}
System.out.println("Would you like to try again Y/N? --> ");
answer = keyboard.next().charAt(0);
}
answer = 'n';
while (answer == 'n' || answer == 'N') {
System.out.println("Program ending. Have a great day.");
}
keyboard.close();
}
}
You can solve this problem by only using one while loop. You use a break condition to inidicate that the loop should terminate (in your example if the user enters 'n').
Here is an example how I would try to solve this problem:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("*******************************************************\n"
+ "*******************SQUARE GENERATOR********************\n"
+ "*******************************************************\n"
+ "\nThis program will let you enter an integer between\n"
+ "3-15 and print out that many squares of that dimension.\n");
boolean exit = false; // define the boolean variable
char answer = 'y';
while (!(exit)) { // start the while loop
if (answer == 'y' || answer == 'Y') { // if the user enters 'y' proceed with your code
System.out.println("Enter the square size --> ");
int x = keyboard.nextInt();
while (x < 3 || x > 15) {
System.out.println("Error: Select a number between 3 and 15 inclusive: ");
x = keyboard.nextInt();
}
for (int i = 0; i < x; i++) {
for (int j = 0; j < x; j++) {
for (int k = 0; k < x; k++) {
System.out.print("X");
}
System.out.println("");
}
System.out.println("");
}
System.out.println("Would you like to try again Y/N? --> ");
answer = keyboard.next().charAt(0);
} else if (answer == 'n' || answer == 'N') { // if the user enters 'n' exit the program and the loop
System.out.println("Program ending. Have a great day.");
exit = true;
} else { // display an error message when something else is typed
System.out.println("You entered an unvalid char, please answer by saying Y/N!");
answer = keyboard.next().charAt(0);
}
}
System.out.println("Reached end of program!");
keyboard.close();
}
Since this looks like homework I won't post the full answer but you can change the
while (answer == 'n' || answer == 'N')
to
if (answer == 'n' || answer == 'N')
Also close the scanner inside the if block above. The else case to the above is where you would throw the error. Hope its clear.
EDIT
Another thing I would like to add is that you can remove answer = 'n'; before the if condition above. That will already be read by
System.out.println("Would you like to try again Y/N? --> ");
answer = keyboard.next().charAt(0);

Why does my program ask for a symbol 2 times instead of one(ignores first symbol)?

This is simple Hangman game:
public static void main(String[] args) {
String[] words = {"writer", "that", "program"};
int wordNumber = (int) (Math.random() * words.length);
System.out.print("Enter a letter in word ");
for (int i = 0; i < words[wordNumber].length(); i++)
System.out.print('*');
System.out.print(" > ");
Scanner input = new Scanner(System.in);
char letter;
do {
letter = input.nextLine().charAt(0);
boolean asterisksInWord = false;
String[] discoveredElements = new String[words[wordNumber].length()];
int countOfTries = 0;
int arrayCount = 0;
int asteriskCount = 0;
System.out.print("Enter a letter in word ");
do {
asterisksInWord = false;
boolean contain;
if (asteriskCount != 1) {
asteriskCount = 0;
for (char item : words[wordNumber].toCharArray()) {
contain = Arrays.asList(discoveredElements).contains(String.valueOf(item));
if (contain) {
System.out.print(item);
} else if (item == letter) {
System.out.print(item);
discoveredElements[arrayCount] = String.valueOf(item);
arrayCount++;
} else {
System.out.print('*');
asterisksInWord = true;
asteriskCount++;
}
}
}
if (asterisksInWord) {
System.out.print(" > ");
letter = input.nextLine().charAt(0);
if (asteriskCount != 1)
System.out.print("Enter a letter in word ");
} else
System.out.println("The word is " + words[wordNumber] +
" You missed " + (countOfTries + 2 - words[wordNumber].length()) + " time(s)");
countOfTries++;
} while (asterisksInWord);
System.out.print("Do you want to guess another word? Enter y or n >");
} while (input.nextLine().charAt(0) == 'y');
}
The log of it's run is
Enter a letter in word **** > t
Enter a letter in word t**t > h
Enter a letter in word th*t > a
The word is that You missed 0 time(s)
Do you want to guess another word? Enter y or n >y
y
Enter a letter in word **** >
My question is why does it ignores first symbol 'y' when asking "Do you want to guess another word?".
I'tried to create some test programs with same do-while conditions but they don't ask for character 2 times like that program.
The program asks for your input two times, because you have programmed it like that. After printing - "Do you want to guess another word? Enter y or n >" - you do input.nextLine() inside the while condition as well as as the first statement after do , so it asks for input twice.
Maybe you can move the question Enter the letter in the word to the inner do loop instead of doing that in the if condition if (asterisksInWord) { .
Also, according to your current logic, it does not ignore your first symbol, that is the real one that decides whether to exit the loop or not, the next input is actually your first guess.

While loop in Java with Multiple conditions

Can someone help me figure out why the while statement isn't working? The loop does stop after i = 3 but won't stop if continueSurvey = 0. It runs but it won't quit the loop if I change continueSurvey to O. Even if I step into the processes and I can see that the variable is 0, the loop continues.
import java.util.Scanner;
public class SurveyConductor
{
public static void main(String[] args)
{
Survey a = new Survey();
a.display();
a.enterQuestions();
int continueSurvey = 1;
int i = 0;
while ((continueSurvey != 0) && (i < 3))
{
for (int row = a.getRespID(); row < 3; row++)
{
System.out.println("Respondent " + (row+1) + " Please tell us how you would rate our: ");
for (int col = 0; col < 3; col++)
{
Scanner input = new Scanner(System.in);
System.out.println(a.presentQuestion(col) + ": ");
System.out.println("Enter your response (1-Strongly Disagree, 2-Disagree, 3-Neutral, 4-Agree, 5-Strongly Agree): ");
int response = input.nextInt();
if ((response < 1) || (response >5))
{
while ((response < 1) || (response > 5))
{
System.out.println("Your response must be between 1 and 5. Please try again.");
System.out.println(a.presentQuestion(col) + ": ");
System.out.println("Enter your response (1-Strongly Disagree, 2-Disagree, 3-Neutral, 4-Agree, 5-Strongly Agree): ");
response = input.nextInt();
}
}
a.logResponse(row,col,response);
System.out.println();
}
a.displaySurveyResults();
System.out.println();
System.out.println("The top rated question is Question #" + a.topRatedQuestion() + ".");
System.out.println("The bottom rated question is Question #" + a.bottomRatedQuestion() + ".");
System.out.println();
Scanner input2 = new Scanner(System.in);
System.out.println("Are there any more repondents (0 - No, 1 - Yes): ");
continueSurvey = input2.nextInt();
a.generateRespondentID();
i++;
}
}
}
}
You need to add a break inside your for loop. IE,
if(continueSurvey == 0)
break;
This will exit the for loop and allow the while loop to exit.
The part where you ask if the user wants to continue is inside this for loop
for (int row = a.getRespID(); row < 3; row++)
not just your while loop. This means it will keep asking until the for loop is done, only quitting when it finally gets back around to the while loop condition.
Your condition in the while loop is:
((continueSurvey != 0) && (i < 3))
which means that the inner block of the while loop will be executed if and only if continuSurvey != 0 and i < 3 in the same time. You have inner loops which have different conditions. I would search for the problem in the inner loops using a debugger. If this answer is not enough for you, then please specify what would you want to achieve.
if you want to exit the loop if either continueSurvey is 0 OR i=3
you have to write the while loop like this:
while((continueSurvey != 0) || (i < 3)) {
...
}
the && (and) operator symbolises that both conditions have to be true in order for the loop to exit not one of them (|| or).

Categories