i have loops in all my other applications, but this just wont seem to work.
public void loanBook() {
boolean loop3 = true;
System.out.println("So you wanna loan a book? Excellent choice.");
while (loop3) {
for (int i=0; i<books.size(); i++) {
System.out.println("Search for the book you're looking for: ");
String book = in.nextLine();
if (books.get(i).toString().contains(book) == true) {
System.out.println("Looking for: " + books.get(i).toString() + "?");
System.out.println("press y to loan book or n to try again");
String choice1 = in.next();
if (choice1.equalsIgnoreCase("y")) {
for (int j=0; j<customers.size(); j++) {
if (customers.get(j).getSignedIn() == true) {
customers.get(j).booksLoaned.add(books.get(i));
Timer.delayFunction();
System.out.println(customers.get(j).printBookList());
System.out.println("Returning to main menu");
----> loop3 = false; doesnt work for some reason
}
}
}
}
}
System.out.println("Couldnt find book");
}
}
It keeps repeating the loop3 even though i set it to false. It should go back to the main menu afterwards, but it wont.
I tried to isolate the problem, and no problem. I've been looking at the code for an hour now and i cant seem to find any problem. Anybody got a clue?
the isolated problem that worked:
public void loanBook() {
boolean loop = true;
while (loop) {
System.out.println("lol");
-----> loop = false; works fine
}
System.out.println("lol");
}
my System out prints work just fine so i know it gets through my loops correctly.
You have 3 nested loops. The other loop (the while loop) terminates when loop3 becomes false.
However, you are setting loop3 to false deep within the inner most loop, which means the while loop won't check the value of loop3 until the 2 inner for loops finish.
If you want to break from all the loops, you'll need some break statements and or additional conditions. For example:
while (loop3) {
for (int i=0; i<books.size() && loop3; i++) {
System.out.println("Search for the book you're looking for: ");
String book = in.nextLine();
if (books.get(i).toString().contains(book)) {
System.out.println("Looking for: " + books.get(i).toString() + "?");
System.out.println("press y to loan book or n to try again");
String choice1 = in.next();
if (choice1.equalsIgnoreCase("y")) {
for (int j=0; j<customers.size() && loop3; j++) {
if (customers.get(j).getSignedIn()) {
customers.get(j).booksLoaned.add(books.get(i));
Timer.delayFunction();
System.out.println(customers.get(j).printBookList());
System.out.println("Returning to main menu");
loop3 = false;
}
}
}
}
}
System.out.println("Couldnt find book");
}
This will leave both inner loops when loop3 becomes false, which will allow the outer loop to terminate immediately.
You want to break out of the while loop as soon as you set it to false. You could do that with labels
public void loanBook() {
boolean loop3 = true;
System.out.println("So you wanna loan a book? Excellent choice.");
while (loop3) {
outerloop: // added
for (int i=0; i<books.size(); i++) {
System.out.println("Search for the book you're looking for: ");
String book = in.nextLine();
if (books.get(i).toString().contains(book) == true) {
System.out.println("Looking for: " + books.get(i).toString() + "?");
System.out.println("press y to loan book or n to try again");
String choice1 = in.next();
if (choice1.equalsIgnoreCase("y")) {
for (int j=0; j<customers.size(); j++) {
if (customers.get(j).getSignedIn() == true) {
customers.get(j).booksLoaned.add(books.get(i));
Timer.delayFunction();
System.out.println(customers.get(j).printBookList());
System.out.println("Returning to main menu");
loop3 = false;
break outerloop; // added
}
}
}
}
}
System.out.println("Couldnt find book");
}
}
Related
Condition 1: if you input more than or equal to 10 straight heads and are able to show in the input then the return is "Streak is found"
Condition 2: if you input less than 10 straight heads then the return is "Streak is broken"
However, I have a problem with condition 1 where it didn't execute to the output.
The code:
import java.util.LinkedList;
import java.util.Iterator;
import java.util.Scanner;
public class LinkedListProgram2
{
public static void main (String [] args)
{
Scanner input = new Scanner (System.in);
LinkedList<String> cointoss = new LinkedList<String>();
boolean head = true;
boolean tail = false;
boolean streak = true;
int streakcount = 0;
System.out.println ("Welcome to the Program #2 ");
//ask for the boolean value. It can be head and tail or true and false.
System.out.print ("\nEnter the boolean value (head=true, tail=false): ");
for (int i = 0; i<18; i++)
{
cointoss.add(input.next());
}
Iterator<String> it = cointoss.iterator();
while (it.hasNext())
{
if(streakcount >= 10)
{
streak = true;
System.out.println ("Streak is found! ");
break;
}
else if(streakcount < 10)
{
streak = false;
System.out.println ("Streak is broken! ");
break;
}
}
}
}
2 logic needs to be added atleast.
Increment the streakcount when true is found
Resetting the counter when false is found
You can have the outer if condition inside the while loop to print broken for every instance or let it be outside while to be printed at the end of loop
while (it.hasNext()) {
String val = it.next();
if (val.equals("true"))
streakcount++;
else
streakcount = 0;
if (streakcount >= 10) {
streak = true;
System.out.println("Streak is found! ");
break;
}
}
if (!streak) {
System.out.println("Streak is broken! ");
}
You miss something in your code, you need to check the input value, and increase streakcount, untested example code:
while (it.hasNext()) {
String val = it.next();
if (val.equals("true")) {
streakcount++;
if (streakcount >= 10) {
streak = true;
System.out.println ("Streak is found! ");
break;
}
}
else if (val.equals("false")) {
streak = false;
System.out.println ("Streak is broken! ");
break;
}
}
There are more action to do, check different input value, or do you need to find streak if it is not from starting array...
According to your description, this is actually a small program that counts specific strings, and doesn't even need LinkedList
I modified your code and now it should satisfy the two conditions you proposed
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
LinkedList<String> cointoss = new LinkedList<String>();
boolean head = true;
boolean tail = false;
boolean streak = true;
int streakcount = 0;
System.out.println("Welcome to the Program #2 ");
// ask for the boolean value. It can be head and tail or true and false.
System.out.println("Enter the boolean value (head=true, tail=false): ");
for (int i = 0; i < 18; i++) {
String next = input.next();
if (next.equals("true") || next.equals("head")) {
streakcount++;
}
cointoss.add(next);
}
if (streakcount >= 10) {
System.out.println("Streak is found! ");
} else {
System.out.println("Streak is broken! ");
}
}
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 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.
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.
the program will ask the user to enter the code of the item he wants to search for. if the item's code exists it will print it to the screen and all works fine until here. The problem is when the user enters code that not exists, the program won't work. it doesn't print "Item not found"
here is the code
public void searchItem(){
boolean invalidInput;
int q = -1;
do {
try {
boolean found = false;
invalidInput = false;
System.out.println("Enter the item's code you want to search for : ");
q = s.nextInt();
out: for (int i = 0; i<items.length; i++){
if(q == items[i].getCode()){
System.out.println(items[i].toString());
found = true;
System.exit(2);
}
counter++;
}
if(!found)
System.out.print("Item not found");
} catch (InputMismatchException e) {
System.out.println("Please enter a valid code [Numbers Only]");
s.next();
invalidInput = true; // This is what will get the program to loop back
}
} while (invalidInput);
}
If i use this (condensed form) of your code it works, and prints "Item not found" as we would expect... So the problem is somewhere else I feel....
Please provide further information about what happens if you enter a missing (but valid) item number!
public static void main(String[] args) {
boolean invalidInput;
int q = -1;
int[] items = { 1, 2, 3, 4 };
do {
boolean found = false;
invalidInput = false;
System.out.println("Enter the item's code you want to search for : ");
q = 5;
for (int i = 0; i < items.length; i++) {
if (q == items[i]) {
System.out.println(items[i]);
found = true;
System.exit(2);
}
}
if (!found)
System.out.print("Item not found");
} while (invalidInput);
}