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).
Related
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 how to correctly write my for loop statement that will give me the correct score. I bolded the code that is what I can't figure out how to write correctly. Anytime I run my program I end up with the first result of (rslt < 3) no matter what numbers I enter.
package module1.assignment;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String options[] = {
"mild or spicy",
"tea or coffee",
"breakfast or " +
"brunch",
"summer or winter",
"paper or plastic"
};
int answers[] = new int[options.length];
String result[] = new String[answers.length];
boolean bool = true;
while (true) {
for (int i = 0; i < options.length; i++) {
System.out.println("Enter 0 for the preference on the left\n" +
"Enter 1 for the preference on the right");
System.out.println("Do you prefer " + options[i] + "?");
answers[i] = scanner.nextInt();
System.out.println("Do you prefer " + options[i + 1] + "?");
answers[i] = scanner.nextInt();
System.out.println("Do you prefer " + options[i + 2] + "?");
answers[i] = scanner.nextInt();
System.out.println("Do you prefer " + options[i + 3] + "?");
answers[i] = scanner.nextInt();
System.out.println("Do you prefer " + options[i + 4] + "?");
answers[i] = scanner.nextInt();
break;
}
for (int i = 0; i < answers.length; i++) {
result[i] = [answers[i]];
}
int rslt = getScore(result);
if (rslt < 3)
System.out.println("You prefer life to be calm and organized");
else if (rslt > 3)
System.out.println("You prefer life to be spontaneous and active.");
else
System.out.println("You prefer a good balance in life");
System.out.println("Enter 0 to exit program or 1 to run again");
int out = scanner.nextInt();
if (out == 0)
bool = false;
if (!bool)
System.exit(0);
}
}
static int getScore(String[] result) {
int score = 0;
for (int i = 0; i < result.length; i++) {
switch (result[i]) {
case "spicy":
score++;
break;
case "coffee":
score++;
break;
case "breakfast":
score++;
break;
case "winter":
score++;
break;
case "paper":
score++;
break;
}
}
return score;
}
}
I have modified your code according to my understanding of the code.
It works just exactly like you may have wanted.
package module1.assignment;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[][] options = {
{"mild", "spicy"},
{"tea", "coffee"},
{"brunch", "breakfast"},
{"summer", "winter"},
{"plastic", "paper"}
};
int[] answers = new int[options.length];
do {
System.out.println("Enter 0 for the preference on the left\n" +
"Enter 1 for the preference on the right");
for (int i = 0; i < options.length; i++) {
System.out.println("Do you prefer " + options[i][0] +
" or " + options[i][1] + "?");
answers[i] = scanner.nextInt();
}
int result = getScore(answers);
if (result < 3)
System.out.println("You prefer life to be calm and organized");
else if (result > 3)
System.out.println("You prefer life to be spontaneous and active.");
else
System.out.println("You prefer a good balance in life");
System.out.println("Enter 0 to exit program or 1 to run again");
} while (scanner.nextInt() != 0);
}
static int getScore(int[] answers) {
int score = 0;
for (int answer : answers) if (answer == 1) score++;
return score;
}
}
To Fix Your Code
In the first for-loop, you are supposed to loop through the options array. But somehow you unfold the loop within the loop body. To prevent the whole thing loop again, you break the loop immediately. To fix the first loop, write it like this instead. Properly loop through each element, no need to unfold it, no need to break it.
System.out.println("Enter 0 for the preference on the left\n" + "Enter 1 for the preference on the right");
for (int i = 0; i < options.length; i++) {
System.out.println("Do you prefer " + options[i] + "?");
answers[i] = scanner.nextInt();
}
In the second loop, you are supposed to retrieve the selected string from answers and write the string to results. Without modifying your data structure, this can be achieved by using split(" or ") on the option, which gives you an array of string which you can use the answer as index to access. Note that this does not prevent array index out of bound exception if user enter anything other than 0 or 1, which you should totally do, but is out of scope of this question.
for (int i = 0; i < answers.length; i++) {
result[i] = options[i].split(" or ")[answers[i]] ;
}
And there you go.
To Solve Your Task
Alternatively, redesigning the data structure and logic to get rid of the unnecessary string manipulation and comparison is more ideal. You don't even need the result and answers array, simply add up the user input will do (if the user follows your instruction)
int rslt = 0;
System.out.println("Enter 0 for the preference on the left\n" +
"Enter 1 for the preference on the right");
for (int i = 0; i < options.length; i++) {
System.out.println("Do you prefer " + options[i] + "?");
rslt += scanner.nextInt();
}
Inside the loop, you continue assigning the result to the same index in the answers list, rather than assigning the result to another index for each input. Because you are not iterating anything, you don't even need the loop. Replace the entire while loop with the code below. Please upvote and accept answer if it solves/helps you with your problem.
System.out.println("Enter 0 for the preference on the left\n" +
"Enter 1 for the preference on the right");
System.out.println("Do you prefer " + options[0] + "?");
answers[0] = scanner.nextInt();
System.out.println("Do you prefer " + options[1] + "?");
answers[1] = scanner.nextInt();
System.out.println("Do you prefer " + options[2] + "?");
answers[2] = scanner.nextInt();
System.out.println("Do you prefer " + options[3] + "?");
answers[3] = scanner.nextInt();
System.out.println("Do you prefer " + options[4] + "?");
answers[4] = scanner.nextInt();
Also, please note this:
for (int i = 0; i < answers.length; i++) {
result[i] = [answers[i]];
}
won't work. Instead of result[i] = [answers[i]];, do result[i] = Integer.parseInt(answers.get(i)).
This is part causing the unexpected behaviour: result[i] = [answers[i]];
From what I understood, you want to implement this:
For each option, store the user choice like 0 or 1, 0 for left, 1 for right
For each user choice, store the string value of the choice, i.e., for the 1st question if the user inputs 0, mild should be captured
Calculate scores by comparing string value of user input against a branching construct, switch case here
The problem is in step 2, the current code result[i] = [answers[i]]; does not express this operation properly.
answers[i] stores the user choice 0 or 1, step 1 operation. So to convert it to the corresponding choice in string step 2 operation, something like this should be done
(options[i].split(" or "))[answers[i]]
Explanation:
Pick up the complete string for each answer
Divide the string into two parts(array with 2 indexes 0 and 1), left and right, using a delimiter, " or " in this case
pick up the left or right based on the value stored in answers[i](the user input)
This should let the code behave as expected :)
There are other aspects that can be improved in the code though, as others have already suggested.
I'm kind of new to java and I'm trying to make a guessing game that looks for User01's duplicate. I'm encountering a problem and I have no idea how do I fix this. My goal is to check if User01 has already entered that specific word. Here is my code as of right now:
public static void main(String[] args) throws InterruptedException{
int k = x;
boolean Given = false;
boolean Given2 = false;
//Playerone and x are in Global Declarations.
for(int j = 0; j < x; j++, k--){
if(j == 0){
System.out.print("Please enter " + k + " words that Player 2 will Guess:");
Playerone[j] = input.nextLine();
System.out.println(j);
}
else if(j == x-1){
System.out.print("Last one:");
Playerone[j] = input.nextLine();
System.out.println(j);
}
else {
System.out.print(k + " more words:");
Playerone[j] = input.nextLine();
System.out.println(j);
}
do {
int Duplicates = 0;
while(Duplicates > j && Playerone[Duplicates] == Playerone[j]){
Duplicates++;
}
Given2= Duplicates < j;
if(Given2 == false){
Given2 = true;
System.out.println("It's already given");
Playerone[j] = input.nextLine();
}
}while(Given2 = true);
}
I tried placing do below the start of for-loop, and it doesn't fixed the problem I'm having.
There is a problem with the condition:
Duplicates>j
which is always false and doesn’t allow Duplicates++
also Duplicates=0; Happens every time User1 gives a word so this will never work to count Duplicates anyway.
Fist of all move Duplicates=0; before the fist for loop
So what I would instead of the last do...while is :
Given=false;
for(int c=0;c<=j;c++){
while(Playerone[j]==Playerone[c])
//duplicate found
System.out.println(“Already exists”);
Playerone[j]=input.nextLine();
Given=true;
}
//these loop also prevent user to give again a word that already exists
}
if(Given) Duplicates++;
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);
My code is currently unable to start at the beginning of the program which is 'Please type in...'. I want the code to be able to return to the beginning statement everytime choice 1 or 2 is executed. The while statement does not satisfy this as I cant use the while statement before 'choice' is declared. I understand that I'm suppose to be using a do while loop but everytime I try to implement it - it gives me an error with braces.
The following is a snippet of my code:
System.out.println("Please type in 1 for a customer to view their portfolio, 2 to trade stocks or 3 to exit the application");
int choice = Integer.parseInt(input.nextLine());
{
while (!"3".equals(choice));
{
if (choice == 1) {
System.out.println(mycustomers[menuchoice].toString());
return;
}
if (choice == 2) {
String StockSelect = "Please select a stock";
for (int i = 0; i < mystocks.length; i++) {
// [i] is the element we are accessing
StockSelect += " " + i + " " + (mystocks[i].getSymbol());
}
System.out.println(StockSelect);
int stockchoice = Integer.parseInt(input.nextLine());
System.out.println("Select 1 to buy or 2 to sell?");
int choice2 = Integer.parseInt(input.nextLine());
if (choice2 == 1) {
System.out.println("How many stocks would you like to buy ");
int volumebought = Integer.parseInt(input.nextLine());
for (int i = 0; i < numofstocks; i++) {
mycustomers[menuchoice].setBalance(
mycustomers[menuchoice].getBalance() - (volumebought * mystocks[i].getprice()));
mycustomers[menuchoice].setPortfolio();
}
System.out.println(mycustomers[menuchoice].toString());
return;
}
if (choice2 == 2) {
System.out.println("How much stocks would you like to sell ");
int volumesold = Integer.parseInt(input.nextLine());
for (int i = 0; i < numofstocks; i++) {
mycustomers[menuchoice].setBalance(
mycustomers[menuchoice].getBalance() + (volumesold * mystocks[i].getprice()));
mycustomers[menuchoice].setPortfolio();
}
System.out.println(mycustomers[menuchoice].toString());
return;
}
}
if (choice == 3) // how to exit application
{
System.out.println("Thank you for using the application");
System.out.println("The current state of all customers are:");
for (int i = 0; i < mycustomers.length; i++) {
System.out.println(mycustomers[i].toString());
}
System.out.println("The current state of all stocks are:");
for (int i = 0; i < mystocks.length; i++) {
System.out.println(mystocks[i].toString());
}
System.exit(0);
}
}
}}}
How would I implement the do-while loop so that it goes back to the initial statement every time after executing the code - if only if the input is not 3?
Ask for input inside the while loop, like this:
choice = Integer.parseInt(input.nextLine());