Loop in a loop and If statement? - java

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.

Related

How to check for Duplicate strings on an array

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++;

Repeated letters logic not working in java

I am working on a version of hangman, and I need to include a condition that checks if a letter guess was already used. My repeated letters if statement is not working correctly. Any advice?
NOT FULL CODE. ONLY A PIECE IS SHOWN
char[] repeatedLetters = new char[26];
int incorrect = 0;
while (incorrect < 7)
{
System.out.println("\nGuess a letter: ");
char guess = kb.next().toUpperCase().charAt(0); // case insensitive
for (int i = 0; i < repeatedLetters.length; i++)
{
if (repeatedLetters[i] == guess) {
System.out.println("You already guessed " + guess + ".");
System.out.println("Guess a letter: ");
guess = kb.next().toUpperCase().charAt(0);
}
else
repeatedLetters[i] = guess;
}
Personally, I would suggest using a List instead of array.
List<Character> repeatedLetters = new ArrayList<>();
int incorrect = 0;
while (incorrect < 7)
{
System.out.println("\nGuess a letter: ");
char guess = kb.next().toUpperCase().charAt(0); // case insensitive
if (validateCharacter(guess) && repeatedLetters.contains(guess)) {
System.out.println("You already guessed " + guess + ".");
continue;
}
else {
repeatedLetters.add(guess);
}
// Other things
}
If you are not allowed to use a list, then you need to move the else block outside of the for loop, use a labelled while loop, and also manually count the number of repeated characters.
int repeatedCount = 0;
getInput : while (incorrect < 7) {
// ......
for (int i = 0; i < repeatedCount; i++) {
if (repeatedLetters[i] == guess) {
System.out.println("You already guessed " + guess + ".");
continue getInput;
}
}
repeatedLetters[repeatedCount] = guess;
repeatedCount++;

Applying do while loops

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

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.

For loop - validating input, program crashes (.hasNextInt())

I am writting a program in java that adds 5 numbers (positive integers) entered by the user using a for loop.
I have managed to make it work when the right input is given and even when negative integers are given, but the program crashes when a non int is entered.
Any help is appreciated!
for (int i = 0; i < 5 ; i++ ) {
if (myScanner.hasNextInt()) {
x = myScanner.nextInt();
if (x < 0) {
System.out.println("Invalid input, enter again:");
x = myScanner.nextInt();
}
}
else {
System.out.println("Invalid input, enter again:");
x = myScanner.nextInt();// this works in the nested if but not here, why?
}
sum += x;
}
System.out.println("Sum is: " + sum);
}//end class
You check whether the scanner has a next integer and then afterwards, still ask for an integer which it doesn't have...
Here's a corrected version:
for (int i = 0; i < 5 ; i++ ) {
if (myScanner.hasNextInt()) {
x = myScanner.nextInt();
if (x < 0) {
System.out.println("Invalid input, enter again:");
} else {
sum += x;
}
}
else {
// get whatever is on the scanner, since we know it isn't and int
String crud = s.next();
System.out.println("Invalid input "+crud+" enter again:");
}
}
InputMismatchException is being thrown, try this logic where the x = myScanner.nextInt is being called from one place,
int count = 0;
while (true)
{
try
{
if (myScanner.hasNextInt())
{
x = myScanner.nextInt();
if (x < 0)
{
System.out.println("Invalid input, enter again:");
}
}
else
{
System.out.println("Invalid input, enter again:");
continue;
}
}
catch(Exception e)
{
System.out.println("Invalid input, enter again:");
continue;
}
count++;
sum += x;
if(count==5)break;
}

Categories