Applying do while loops - java

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());

Related

Loop in a loop and If statement?

I am a beginner programming, I want to ask multiple questions using arrays and tell the user whether he got each question right or wrong, which I managed to get it running, but now how do I implement the code so that the user will only have up to 3 attempts to get a question right.
for(int n = 0; n <QArray.length; n++)
{
System.out.println("Question" + (n+1));
System.out.println(QArray[n]);
String ans = scanner.nextLine();
if (ans.equalsIgnoreCase(AArray[n]))
{
System.out.println("That is correct!");
}
else
{
System.out.println("That is incorrect!");
}
}
So if I correctly understand your goal, you've a list of questions, and whilst they have made fewer than three failed attempts at them, you would like for the users to get to try and answer them?
Using your existing style, you could do something like
for(int n = 0; n < QArray.length; n++)
{
System.out.println("Question" + (n+1));
System.out.println(QArray[n]);
int incorrectAnswers = 0;
while(incorrectAnswers < 3)
{
String ans = scanner.nextLine();
if (ans.equalsIgnoreCase(AArray[n]))
{
System.out.println("That is correct!");
break;
}
else
{
System.out.println("That is incorrect!");
incorrectAnswers++;
}
}
}
Depending how the data is displayed and transferred and concerns regarding security etc, it would make for easier to manage code to have a QuestionAnswer object that contains the question and the answer, as well as a method for what constitutes a valid answer (e.g. case insensitive, or maybe you want to accept multiple words etc, whatever works for your case), so you could end up with code that looks like the below.
for(int i = 0; i < questionAnswerArray.length; i++)
{
QuestionAnswer qa = questionAnswerArray[i];
System.out.println("Question " + (i+1));
System.out.println(qa.getQuestion());
int incorrectAnswers = 0;
while(incorrectAnswers < 3)
{
String ans = scanner.nextLine();
if (qa.isValidAnswer(ans))
{
System.out.println("That is correct!");
break;
}
else
{
System.out.println("That is incorrect!");
incorrectAnswers++;
}
}
}
Try to use while with the number of attempt you need:
for (int n = 0; n < QArray.length; n++) {
System.out.println("Question" + (n + 1));
System.out.println(QArray[n]);
int attempt = 3;
while (attempt > 0) {
System.out.print("Please enter the answer: ");
String ans = scanner.nextLine();
if (ans.equalsIgnoreCase(AArray[n])) {
System.out.println("That is correct!");
break;
} else {
System.out.println("That is incorrect!");
}
attempt--;
}
}
Put a second loop inside the first.
for(int n = 0; n < QArray.length; n++) {
boolean correct = false;
for(int m = 0; m < 3; m ++) {
String ans = scanner.nextLine();
if (ans.equalsIgnoreCase(AArray[n])) {
System.out.println("That is correct!");
correct = true;
break;
} else {
System.out.println("That is incorrect!");
}
}
if(!correct) {
//something
} else {
//something else
}
}
Note the break;. That command will exit the inner for-loop (which contains the scanner input) when a correct answer is submitted. If the user doesn't get the right answer in 3 tries, the for-loop will end by reaching the end of its counter.

Java scanner - allowing a certain number of ints

Really struggling to find the answer to this.
I'm creating a game where it asks how many players there are and the max number of players the user can enter is 3 (either 1, 2 or 3). Is this creating a for loop or can I just enter a parameter in the scanner function?
Code below:
System.out.println(" How many players are there? ");
int numberOfPlayers = scan.nextInt();
Player[] players = new Player[numberOfPlayers]; //this is where the players scores are stored
int currentPlayer = 0; //because arrays start at 0: +1 is added
for (int i = 0; i < numberOfPlayers; i++) {
System.out.println("What is player " + (i + 1) + " called?");
String playerName = scan.next();
players[i] = new Player(playerName);
You can use Scanner's nextLine() which reads the newline instead of next() as shown below:
System.out.println(" How many players are there? ");
int numberOfPlayers = Integer.parseInt(scan.nextLine());
Player[] players = new Player[numberOfPlayers];
for (int i = 0; i < numberOfPlayers; i++) {
System.out.println("What is player " + (i + 1) + " called?");
String playerName = scan.nextLine();
players[i] = new Player(playerName);
}
I suggest to use Integer.parseInt(scan.nextLine()) with a loop for example :
int numberOfPlayers = 0;
boolean correct = false;
do {
try {
System.out.println(" How many players are there? ");
numberOfPlayers = Integer.parseInt(scan.nextLine());
if (numberOfPlayers >= 1 && numberOfPlayers <= 3) {
correct = true;
}
} catch (NumberFormatException e) {
}
} while (!correct);
So if the user enter incorrect number or a number > 3 or < 1 it will ask the user to enter the number again until the the user enter the correct number 1,2,3

Why is this infinte loop happening?

Guys I really need some help here :(
I need to create a contact list in which I need to be able to create, edit, delete, show and search contacts.
But after I enter number 1 (to include a new number) and type the name and number, it goes to an infinite loop and I was wondering if you guys could help me figure out why it's happening and how to fix it.
I'm pretty sure it has something to do with this block at the end of the code:
while (op!=6)
System.out.println();
But when I remove it, the loop just doesn't happen. Instead of an infinite loop it just doesn't loop at all. I've been trying for literally hours now and I can't seem to figure it out at all.
(also I'm not allowed to use array list here)
Sorry for my english and thank you already!
import java.util.Scanner;
public class Vetor45 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] name = new String[1000];
String nname, auxname;
int[] tel = new int[1000];
int ntel, op, cont, i, k, auxtel;
cont = 0;
k = 0;
for (i = 0; i < 1000; i++) {
name[i] = "Empty";
tel[i] = 0;
}
{
System.out.println("contact list:");
System.out.println("1. include a new number");
System.out.println("2. edit a number");
System.out.println("3. delete a number");
System.out.println("4. print all numbers");
System.out.println("5. search by name");
System.out.println("6. exit");
System.out.println("Option:");
op = scanner.nextInt();
System.out.println("");
if (op == 1) {
if (k <= 999) {
while (name[k] != "Empty") {
k++;
}
System.out.println("Enter a name:");
name[k] = scanner.next();
System.out.println("Enter a number:");
tel[k] = scanner.nextInt();
k++;
}
else {
System.out.println("complete");
}
}
else {
if (op == 2) {
i = 0;
System.out.println("enter a name:");
nname = scanner.next();
while (nname != name[i] && i < k - 1) {
i++;
}
if (nname == name[i]) {
System.out.println("enter the new number:");
ntel = scanner.nextInt();
tel[i] = ntel;
}
else {
System.out.println("name not registred");
}
}
else {
if (op == 3) {
k--;
i = 0;
System.out.println("enter a name:");
nname = scanner.next();
while (nname != name[i] && i < k) {
i++;
}
if (nname == name[i]) {
name[i] = "Empty";
tel[i] = 0;
} else {
System.out.println("name not registred");
}
}
else {
if (op == 4) {
for (i = 0; i <= k - 2; i++) {
for (cont = i + 1; cont <= k - 1; cont++) {
if (name[i] == name[cont]) {
auxname = name[i];
name[i] = name[cont];
name[cont] = auxname;
auxtel = tel[i];
tel[i] = tel[cont];
tel[cont] = auxtel;
}
}
}
System.out.println("phone list:");
for (i = 0; i < 1000; i++) {
if (name[i] != "Empty") {
System.out.println("name: " + name[i]);
System.out.println("tel: " + tel[i]);
}
}
}
else {
if (op == 5) {
i = 0;
System.out.println("enter a name:");
nname = scanner.next();
while (nname != name[i] && i < k) {
i++;
}
if (nname == name[i]) {
System.out.println("name: " + nname);
System.out.println("Tel: " + tel);
} else {
System.out.println("name not registred");
}
} else {
if (op == 6) {
System.out.println("exiting");
} else {
System.out.println("option not available");
}
}
}
}
}
}
System.out.println();
}
while (op != 6)
System.out.println();
}
}
You don't even have a do/while loop in this code, here is what a do/while loop loops like:
do{
//loop
}while(op != 6); //don't forget semi colon
You need to develop some standard for braces, and such. As it is right now, it's really hards to read this code.
Yes, as surmised by both you and #Amadan, the while (op != 6) is the problem. In general, when you're looping, something in the loop has to modify something in the condition you're looping on or something in the loop has to modify the normal control flow (so a return, break, etc.), so when you see while (op != 6), you should think "op is the only variable in the condition, so something inside the loop has to modify op or there has to be some other way to get out of the loop."
I think what you want to do is put a do before the big block before the while and then have the while at the end of the block, so you're doing this:
do
{
...
op = scanner.nextInt();
...
} while (op != 6);
That will read an int into op, do some stuff with it, and then bail out if the user entered 6.
The loop while (op!=6) is being run without any changes to op being allowed inside it.
//Rest of the code
System.out.println();
}
while (op!=6)
System.out.println();
}
}
The loop should be evealuated at the beginning of what you need to execute and have everything you want to do in the loop (including changing op) inside it:
for (i=0; i<1000; i++)
{name[i]="Empty"; tel[i]=0;}
while (op!=6)
{
System.out.println("contact list:");
//Rest of the code
You will probably have to move some braces round when you do this also. But I'm not going to go through the whole thing/ that's outside the scope of the question.

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).

Checking for user input to be only integers in Java

I'm doing lottery game for my assignment (user inputs 6 number, i will generate 8 unique winning numbers and 2 last numbers are supplementary). I need help with user input checking if input numbers are from 1 to 45 and input must be int, when input is not integer it throws an error.
This programming way is procedure way, how can i change it into object oriented way? I know that I must make methods in another java file and then link it back to this main. Can you suggest me how to do it?
I have tried try and catch, if and else (for input check) but i don't know how to check user input when it's in array. Thank you for help.
Here is my code:
class Lottery {
public static void main ( String[] args ) {
System.out.println("\nWelcome to the Lottery game.");
System.out.println("You can enter numbers from 1 to 45.");
// User input into an array
int[] input = new int[6];
Scanner scanner = new Scanner(System.in);
System.out.println("\nPlease enter your 6 lucky numbers: ");
for(int j = 0; j < 6; j++) {
input[j]=scanner.nextInt();
}
int check = scanner.nextInt();
if(check < 0 && check > 45) {
System.out.println("\nERROR: Please enter only numbers from 1 to 45!");
}
// Printing out unique winning numbers from random generator
System.out.println("\nWinning numbers: ");
MultiRandomGenerator mrg = new MultiRandomGenerator();
int[] set;
set = mrg.getSet();
for (int i = 0; i < set.length; i++) {
System.out.print(set[i] + " ");
}
// Loops for counting how many numbers user has guessed right
int count = 0; // for 6 numbers
int scount = 0; // for 2 last supplementary numbers
for(int i = 0; i < input.length; i++) {
for(int k = 0; k < set.length; k++) {
if (k < 6) {
if (set[k] == input[i]) {
count++;
} else {
if (set[k] == input[i]) {
scount++;
}
}
}
}
}
System.out.print("\n\nYou guessed right " + count + " winning numbers.");
System.out.print("\nYou guessed right " + scount + " suplementary numbers.");
// If statments for printing out winning prizes
if (count == 6) {
System.out.println("\nYou have won 1st price!");
} if (count == 5 && scount == 1) {
System.out.println("\nYou have won 2st price!");
} if (count == 5) {
System.out.println("\nYou have won 3st price!");
} if (count == 4) {
System.out.println("\nYou have won 4st price!");
} if (count == 3 && scount == 1) {
System.out.println("\nYou have won 5st price!");
} if (count == 1 && scount == 2) {
System.out.println("\nYou have won 6st price!");
} else {
System.out.println("\nSorry, you didn't won anything.");
}
}
}
Sample code to go through array and find the invalid user input.
set = mrg.getSet();
String[] userDataStatus = new String[45];
for (int i = 0; i < set.length; i++)
{
try
{
String inputdata = set.get(i);
if(inputdata != null && inputdata.trim().length() > 0)
{
int currentNumber = Integer.parseInt(userdata);
userDataStatus[i] = "Y";//Y represent valid number
}
}
catch (NumberFormatException ex )
{
userDataStatus[i] = "N";//If it throws exception then save as 'N'
}
}
Use the above String array and display error messaage to users.
You can check in your loop, something like
int val;
try
{
input[j] = Integer.parseInt( scanner.nextString() );
}
catch (NumberFormatException ex )
{
}

Categories