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++;
}
Related
this is probably a really newbie issue, but I can't quite find an answer that was answered without using a for loop. I have one array set as a constant which contains the correct answers to the test. The program takes in user input and then compares it to the constant array and counts the amount of correct answers. I should not have to import any libraries and should complete the method with a while loop.
I want to iterate through the users input through the ANSWER constant and create a count for all of the correct answers.
Here is a snippet of my class (I've excluded the method that prompts the user for answers to keep things simple).\
public class DriverExam{
public static final char[] ANSWER = {'B','D','A','A','C','A','B','A','C','D','B','C','D','A','D','C','C','B','D','A',};
private char[] driversAnswers;
InputReader reader;
public DriverExam(){
reader = new InputReader();
driversAnswers = new char[20];
}
public int getTotalCorrectAnswers(){
int correct = 0;
int index = 0;
while (index < ANSWER.length){
index++;
if(driversAnswers.equals(ANSWER)){
correct++;
}
System.out.println(index);
System.out.println(correct);
}
return correct;
The issue is most likely to do with the if statement but I can't seem to find a way to iterate through an arrays indices and compare them to another array.
EDIT: My current method looks like this:
public int getTotalCorrectAnswers(){
int correctAnswer = 0;
int index = 0;
while(index < ANSWER.length){
if(ANSWER[index]==driversAnswers[index]){
correctAnswer++;
index++;
}
// System.out.println(index);
System.out.println(correctAnswer);
}
return correctAnswer;
For a couple of attempts I was getting some actual counts happening but it appeared that it would stop the counter once it encountered a different value. But as things stand now I am stuck with a result value of 0's
as already described in the comments, you cannot compare arrays like this. driverAnswers.equals(ANSWER) only compares the references, in this case it will return a false, because the references are different. If you want to check an array for equality you can use Arrays.equals(arr1, arr2). In this case the equals method is called on every element in the array. If the objects in the arrays override this method correctly, this method will return the desired result.
However, you did mention not to use other libraries.
The simplest solution would then be to iterate through each element and check for equality
EDIT: because you don't need the else case i made a little editing here
while(index < ANSWER.length){
if(driverAnswer[index] == ANSWER[index])
correct++
index++
}
first you to check the size of the both array must equal, if it so then you can directly use Arrays.equals method for all correct answer else you can loop through the right answer, look out the simple iteration below
int correctAnswer = 0;
if(ANSWER.length == driversAnswers.length){
if(Arrays.equals(ANSWER,driversAnswers))
System.out.println("correct answer: " + driversAnswers.length);
else{
for (int i=0;i<ANSWER.length;i++) {
if(ANSWER[i]==driversAnswers[i])
correctAnswer++;
}
System.out.println("correct answer: " + correctAnswer);
}
}
You can use while loop there instead of for
int correctAnswer = 0,index=0;
if(ANSWER.length == driversAnswers.length){
if(Arrays.equals(ANSWER,driversAnswers))
System.out.println("correct answer: " + driversAnswers.length);
else{
while (index<ANSWER.length) {
if(ANSWER[index]==driversAnswers[index])
correctAnswer++;
index++;
}
System.out.println("correct answer: " + correctAnswer);
}
}
USE THIS FOR YOUR REFERENCE
import java.util.Arrays;
class Test{
public static void main(String[] args) {
char[] ANSWER = {'B','D','A','A','C','A','B','A','C','D','B','C','D','A','D','C','C','B','D','A',};
char[] driversAnswers = {'x','D','A','A','C','A','B','A','C','D','B','C','D','A','D','C','C','B','D','A',};
int correctAnswer = 0,index=0;
if(ANSWER.length == driversAnswers.length){
if(Arrays.equals(ANSWER,driversAnswers))
System.out.println("correct answer: " + driversAnswers.length);
else{
while (index<ANSWER.length) {
if(ANSWER[index]==driversAnswers[index])
correctAnswer++;
index++;
}
System.out.println("correct answer: " + correctAnswer);
}
}
}
}
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
}
.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.
This question already has answers here:
Post increment operator not incrementing in for loop [duplicate]
(5 answers)
Closed 8 years ago.
It's supposed to count the number of matching pairs in the strings.
public class tests {
public static void main(String[] args) {
System.out.print("Please enter a word: ");
Scanner inpFirst = new Scanner(System.in);
String inputF = inpFirst.nextLine();
System.out.print("Please enter another word: ");
Scanner inpSecond = new Scanner(System.in);
String inputS = inpSecond.nextLine();
int lenghtF = inputF.length() - 1;
int lengthS = inputS.length() - 1;
int f = 0;
int s = 0;
int matchingPairs = 0;
while ((f < lenghtF) & (s < lengthS)) {
char testF = inputF.charAt(f);
char testS = inputS.charAt(s);
if (testF == testS) {
char testTwoF = inputF.charAt(f+1);
char testTwoS = inputS.charAt(f+1);
if (testTwoF == testTwoS)
matchingPairs = matchingPairs++;
}
System.out.println("jrfjtf");
f = f++;
s = s++;
}
System.out.println("The number of matching pairs is: " + matchingPairs);
}
}
Change the last two lines of the loops to f++ and s++.
Basically, setting
f = f++
doesn't increment the value, it sets f=f, you want just f++ instead.
As Masud has mentioned, change your operator from && and &. Most of the time (especially with if statements), you should be using the && operator.
You used & that is bitwise operator. Use conditional and (&&) operator instead of & in while loop.
Seems like you have an incremention problem.
1. Using the bitwise and operator - '&' seems to be ok. It just computes both sides of the condition and going the long way instead of making shortcuts like in "if(foo != null && foo.doOpperation) if foo is null , the right side won't be checked , that way you can avoid 'null refferance error'.
2. You are incrimenting in a wrong way, " f=f++" will keep f as it is .
Suggetions: Use && in the conditioning and "f++;" as incremention operator.
Another suggestion in this case is using a for loop, your condition is simple and the opperation on f and s is only inceementation.
This question already has answers here:
Creating hangman game without arrays [closed]
(3 answers)
Closed 9 years ago.
Logic:
This is how the output should look like. http://prntscr.com/1is9ht i need to find the index of guess in the orginalString. If that's true then it should replace the question mark at the index with the character read in the string guess. After that it should take out that char from the string "abcdefghijklmnopqrstuvwxyz".
If originalString doesn't contain guess than it should only take out that char from the string "abcdefghijklmnopqrstuvwxyz" I looked up this question on google and found a bunch of codes, they were all using arrays or something that I have not learned in the classes. So please don't use arrays. I am stuck at the if else statement. Is there any way to solve this problem without using Arrays.
int count=1;
while (count<=24){
Scanner keyboard = new Scanner(System.in);
int length;
String originalString;
String guess;
String option= "abcdefghijklmnopqrstuvwxyz";
String questionmarks;
System.out.println("Please enter a string");
originalString=keyboard.nextLine();
length=originalString.length();
questionmarks = originalString.replaceAll(".", "?");
System.out.println("Original String: "+originalString);
System.out.println("Guessed String: "+questionmarks);
System.out.println("Characters to choose from: "+option);
System.out.println("Please guess a character");
guess=keyboard.nextLine();
if (originalString.contains(guess)){
count++;
}
else{
option.replace(guess, "_");
count++;
System.out.println(option);
}
Please suggest me some code that doesn't implement array concept for my problem,
Any help will be appreciated
A few things that I noticed from a cursory glance:
.replace() returns a String, it will not modify option unless you do:
option = option.replace(guess, "_");
Also, since you don't want to use Arrays, I highly suggest that you use StringBuilder
EDIT 1 (based off of comment from duplicate thread):
You can use a StringBuilder to have a String that's initialized to all -. Then when someone guess a correct letter, you can replace the - with the guess.
StringBuilder sb_word = new StringBuilder(lengthOfOriginalString);
for (int i = 0; i < length; i++)
sb_word.append('-'); //add hyphens to StringBuilder, StringBuffer would also work
You should really use something like:
final char blank = '-';
Then, after someone makes a guess, if you've determined that the character at position i should be replaced by guess, you could do:
sb_word.setCharAt(i, guess.charAt(0));
EDIT 2:
while (bodyparts > 0 && !win) //play game while you have bodyparts and haven't won
{
System.out.printf("Word to guess: %s\nEnter a letter or word guess: " , sb_word);
guess = keyboard.next();
if (guess.length() == 1)
{
for (int i = 0; i < length; i++) //loop to see if guess is in originalString
if (Character.toLowerCase(word.charAt(i)) ==
Character.toLowerCase(guess.charAt(0)))
{ //it is, so set boolean contains to be true and replace blank with guess
sb_word.setCharAt(i, guess.charAt(0));
contains = true;
}
if (!contains)
{
bodyparts--;
System.out.printf("Incorrect, you have %d bodyparts left.\n", bodyparts);
}
else if (sb_word.indexOf(String.valueOf(blank)) == -1)
{ //all the letters have been uncovered, you win
win = true;
System.out.println(word);
}
else
{
contains = false;
System.out.println("Good guess.");
}
}
else
{
if (guess.equals(word))
win = true;
else
{
bodyparts = 0;
System.out.printf("Incorrect, you have %d bodyparts left.\n" , bodyparts);
}
}
}