Java - loop in GUI repeats instead of counting iterations - java

I am working on a Java quiz, which interprets data input by the user about one dimension of an array (questions) and verifies them against the second dimension (correct answers). After creating it in CLI, I have added jFrame capabilities, and left it with the intention of checking the way it works through the IDE console output (System.out.println) and adding the jFrame output later. However, the loop designed for answer checking does not function as intended.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
Console input = System.console();
Random r = new Random();
int randq = r.nextInt(4);
String answer;
String[][] Qs = new String[4][2];
Qs[0][0] = "A?";
Qs[0][1] = "A";
Qs[1][0] = "B?";
Qs[1][1] = "B";
Qs[2][0] = "C?";
Qs[2][1] = "C";
Qs[3][0] = "D?";
Qs[3][1] = "D";
for (int counter = 0; counter < 4;) {
randq = r.nextInt(4);
jLabel1.setText(Qs[randq][0]);
add(jTextField1);
answer = jTextField1.getText();
if (answer.equals(Qs[randq][1])) {
System.out.println("Correct!");
jTextField1.setText("");
}
else {
System.out.println("Incorrect, the answer was " + Qs[randq][1]);
jTextField1.setText("");
}
counter = counter + 1;
}
}
Entering "A" against "A?" outputs:
Correct!
Incorrect, the answer was A
Incorrect, the answer was D
Incorrect, the answer was D
The aim is for the program to repeat for the number of questions, but instead it repeats itself times the number of questions EVERYTIME it gets a question. Furthermore, for some reason, it does not interpret any of the answers after the first one, as you can see with "Incorrect, the answer was A".
I can't tell what's wrong just through reading line-by-line. Thank you in advance.

You need to break out of your loop once the correct answer has been found.
if (answer.equals(Qs[randq][1])) {
System.out.println("Correct!");
jTextField1.setText("");
break;
}
Also it is very strange that this line
counter = counter + 1;
is at the end of that loop.
Not sure if you wrote this but you could remove that line by making the loop as follows
for(int counter = 0; counter < 4; counter++) {
// Do work
}

Related

I'm trying to make a hangman game, but I'm getting hung up on things like arrays [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
import java.util.Scanner;
import java.util.ArrayList;
public class hangman {
public static void ttt(String inputWord) {
int wordLength = inputWord.length();
String blanks = "";
for (int i = 0; i < wordLength; i++) {
blanks = blanks.concat("_ ");
}
// System.out.print(wordLength);
System.out.println(blanks);
int points = 0;
int counter = 0;
ArrayList<String> usedChars = new ArrayList<String>();
while (points < wordLength) {
Scanner reader = new Scanner(System.in);
System.out.println("Guess: ");
String guess = reader.next();
// int checker = 0;
// for(int k = 0; k < usedChars.size(); k++) {
// if(usedChars.get(k) != guess) {
// checker = checker + 1;
// }
// else {}
// }
// if(checker == usedChars.size()) {
for (int i = 0; i < wordLength; i++) {
if (guess == inputWord.substring(i, i + 1)) {
points = points + 1;
usedChars.add(guess);
System.out.println("hit"); // this is me trying to see if
// this part is working
} else {
}
}
System.out.println("Used letters: " + usedChars);
// }
// else {
// System.out.print("Sorry, that letter has already been used");
// }
counter = counter + 1;
if (counter == 5) {
points = wordLength;
}
}
System.out.println("Game over");
}
public static void main(String[] args) {
ttt("to");
}
}
Don't worry about the commented out code, that's just me going over the top trying to prevent duplicate guesses, but it's more important that I get the rest of the code to work first.
Anyway, the only part of my code that seems to be working is the counter part. You can try it yourself, but it seems like all it does it take 5 guesses (5 lives, kind of random) and print game over.
edit: in hindsight i need to revisit that counter part, because it should only increase for incorrect guesses
The first thing I noticed was that my array isn't working correctly. It's not .add()'ing like I ask it to add my guesses. (Source: https://beginnersbook.com/2013/12/java-arraylist-add-method-example/)
Then, the more serious problem of the code not even being able to record correct guesses :/
I'm starting to code in my school's java class and decided to try this on my own for fun, any help would be greatly appreciated! :P
change the following boolean expression
guess == inputWord.substring(i, i + 1)
to
guess.equals(inputWord.substring(i, i + 1))
because guess is a String object. using '==' operator will only compare the reference, not the value.
also you might want to use
String guess = reader.nextLine();
instead of
String guess = reader.next();

Show Characters shared between two strings

For a Java exercise I'm writing a program where the user enters two strings. The program then checks to see if the two strings share any similar characters and outputs them to the screen.
For example is Terrarium and Terraform are the two strings it should print t e r r a r. However when I run my program it always simply outputs all the characters in the first string. (In this case T e r r a f o r m.)
I suspect I'm creating a logical error based on a limited understanding of loops. But when I search for answers people seem to always use a similar method to my own.
Here is the code for your viewing:
import java.util.Scanner;
public class CountMatches
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println(" Please enter a String >> ");
String stringA = keyboard.nextLine();
System.out.println(" Please enter another String >> ");
String stringB = keyboard.nextLine();
for(int counter = 0; counter < stringA.length(); counter++ )
{
char compareA = stringA.charAt(counter);
char compareB = stringB.charAt(counter);
//System.out.println(compareA);
//System.out.println(compareB);
//System.out.println("");
if(compareA != compareB)
{
System.out.println("");
}
else if(compareA == compareB);
{
System.out.println(compareA);
System.out.println("");
}
}
}
}
else if(compareA == compareB);
Get rid of the semicolon on this line and it should work. I would also get rid of the first if statement just keep the second one.
You have two problems with this code.
First,
for(int counter = 0; counter < stringA.length(); counter++ )
If the two string are of different length, you could get an exception by going off the end of the other string. So, do this:
int len = stringA.length();
if (len > stringB.lengh()) len = stringB.length();
Next, the reason you code fails is because you have a ; at the end of your else. Your code should be:
if(compareA != compareB)
{
System.out.println("");
}
else // Don't need the == here
{
System.out.println(compareA);
System.out.println("");
}
Good luck with this.

Writing loops that add a string to a string one at a time

I want to write a loop to print a double line (===) across the screen, one (=) at a time. I'm still really new to Java and I'm practicing loops right now. I want my result to look something like this:
=
==
===
====
and so on.
This is what I have so far. . .
int twoLines = 0;
while (twoLines < 10)
{ System.out.println("=");
twoLines = twoLines + 1;
}
What do I need to do to this in order to add one "=" at a time ?
I know this is super basic to most of you, but I'm still figuring this stuff out. Thank you in advance for any advice.
The key idea is to modify the string you want to print after each iteration inside the while loop. This will work:
int twoLines = 0;
String string = "=";
while (twoLines < 10)
{
System.out.println(string);
string = string + "=";
twoLines = twoLines + 1;
}
int twoLines = 1;
while (twoLines <= 10)
{
int i = 1;
while(i <= twoLines) {
System.out.println("=");
i = i + 1;
}
System.out.println(""); // next line
twoLines = twoLines + 1;
}
You can use two loops to achieve this. The inner loop prints the symbol "=" and the outer loop prints a new line.
int i=0;
while (i < 10) {
int j=0;
while (j < i){
System.out.print("=");
j++;
}
//print a new line
System.out.println("\n");
i++;
}
Ok, have you managed to run this code and had a look at what it prints?
Currently your code is just printing "=" once per line, can you see how this statement
System.out.println("=");
never changes? Every time the loop is run, this statement is called, with the same "=" in the print statement.
We need a way to change that print statement, so that each time the loop runs, what it prints is different.
So if we store the "=" in a variable and and print that variable, we can add another "=" to that variable every time the loop runs.
int twoLines = 0;
string output = "="
while (twoLines < 10){
// first print the output
System.out.println(output);
// then change the output variable, so that the next loop
// prints a longer string
output += "=";
// then increment the twoLines variable
twoLines++;
}
The line;
output += "=";
is a little short cut for concatenation. Concatenation is the process of adding strings together. By using the '+=' operator, I'm saying that I want to add the string "=" to the end of the string output.
The line;
twoLines++;
is another little shortcut for incrementing a variable. The '++' operator adds 1 to the variable.
So in short, you just want to look at how you can change the print statement to reflect the change you want to see each time the loop is run.
I'm not sure if you are looking to print the = characters on a single line, one iteration at a time. If that's the case, then you may not want to use system.out.println (as this prints a new line on every invocation).
First, please note that if the above assumption is true, then this is possibly a duplicate of the following SO question: How can I print to the same line?
That said, perhaps this is a naive solution to what you are looking for:
import java.util.concurrent.TimeUnit;
import java.lang.InterruptedException;
public class OneLine {
public static void main(String[] args) throws InterruptedException {
// Prints "="'s to the terminal window, one iteration at a time,
// on one line.
int twoLines = 0;
while (twoLines < 10) {
System.out.print("=");
twoLines = twoLines + 1;
TimeUnit.MILLISECONDS.sleep(100);
}
System.out.println("");
}
}

.equals() in java doesn't work?

.equals() in java dosent work? There is a problem with my program, for some reason in the while loop part it is always active even if the String a = answer[r]
import java.util.Scanner;
public class security {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
String q1[] = {"mother midd name","Father name","your pit name","First school name"};
String a[] = {"Zakia","Mohamed","Dog","Kaliop"};
AskQ(q1,a);
}
public static void AskQ(String q[],String answers[]) {
int r = (int) (Math.random() * q.length) + 1;
for (int i = 0; i < answers.length; i++) {
int c = 1;
System.out.print("please enter your " + q[r] + "?");
String a = sc.nextLine();
do {
c++;
System.out.print("Wrong! try again:");
a = sc.nextLine();
if(c == 2){
System.out.print("only one attempt lift! enter your pass:");
a = sc.nextLine();
c++;
}
if(c == 3){
System.exit(0);
}
c++;
} while (!a.equals(answers[r]));
System.out.println("you are in");
break;
}
}
}
From what I am seeing, your code first sets c equal to 1 in the for-loop, then asks for an answer to a question, then goes into the do-while loop. Inside of the do-while loop it increments c to 2, then takes in another answer to a question, then checks to see if c is equal to 2. Since c is equal to 2 it asks for an aswer to another question then it increments c to 3. Finally, it checks to see if c is equal to 3 (which it is) and exits the program.
I suggest using a while loop over a do-while loop since it looks like you want to check to see if the user entered in the correct answer BEFORE you do any checking and error-handling. If you use a do-while loop, you are doing the error handling before it ever even checks to see if the user entered in the correct answer.
More over, i'd suggest using your second if-statement as an else-if statement.

testing true/false for while conditions using ! || and && operators

I'm having a little trouble grasping the difference between ! || and && when they are tested in a while condition. In the example below I want the program to ask a question "do you see a four on the screen?" then if the person answers no the program continues and keeps asking. If the user enters the answer "yes" the program exits but mine does not.
In my while loop condition am I telling the while loop to continue only if both i is less than 5 and the answer to the question is not yes? How is the correct way of thinking about ! || and && when used inside the context of a while loop?
import acm.program.*;
public class WhileConditionTestProgram extends ConsoleProgram{
public void run(){
String question = ("do you see a four on the screen? ");
int i = 1;
while(i <= 20 && !(question.equals("yes"))){
String question = readLine("do you see a 4 on the screen?: ");
i++;
}
}
}
Apart from the obvious issue of variable re-declaration, you should also consider using a do-while loop, since you are reading the user input at least once.
So, you can better change your loop to:
int i = 0;
String answer = "";
do {
answer = readLine("do you see a 4 on the screen?: ");
i++;
} while (i <= 20 && !answer.equalsIgnoreCase("yes"));
Note: I have used equalsIgnoreCase just for safer side, since you are reading input from user. You never know what combination of letters it passes.
In your while condition you are testing answer not question try that:
while(i <= 20 && !(answer.equals("yes"))){
answer = readLine("do you see a 4 on the screen?: ");
i++;
}
The problem with this code:
String question = ("do you see a four on the screen? ");
int i = 1;
while(i <= 20 && !(question.equals("yes"))){
String question = readLine("do you see a 4 on the screen?: ");
i++;
}
Is that you're redefining the question variable inside the while function. As an example, this will print "1", and not "2":
String question = "1";
int i = 1;
while (i <= 20) {
String question = "2";
i++;
}
System.out.println("Question is: " + question); // This will print "1"!
When you say String question = "2" you are declaring a brand new variable called question and setting it to "2". When you get to the end of the while loop, that variable goes out of scope and the program throws its data away. The original question is untouched. Here is a corrected version of that code snippet:
String question = ("do you see a four on the screen?");
int i = 1;
while(i <= 20 && !(question.equals("yes"))){
question = readLine("do you see a 4 on the screen?: ");
i++;
}
These operators work in a while loop the same way as they work everywhere else.
The && and || operators perform Conditional-AND and Conditional-OR operations on two boolean expressions.
Try this:
String answer = "";
int i = 1;
while(i <= 20 && !(answer.equalsIgnoreCase("yes"))){
answer = readLine("do you see a 4 on the screen?: ");
i++;
}

Categories