Why is my condition never met? [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
Take a loot at the bottom in my for loop. It's probably a simple logical error but for some reason 'if' condition is never met. Sorry for asking basic stuff but I've searched and searched and can't seem to find the answer. Thanks for helping a noob.
Scanner scan = new Scanner(System.in);
System.out.println("How large would you like the array to be? (number)");
int arraySize = scan.nextInt();
scan.nextLine();
String [] myArray = new String [arraySize];
int i = 0;
if (arraySize <= 0 ) {
System.out.println("Please enter a positive integer for the array size. Rerun program when ready.");
} else {
while (i < myArray.length) {
System.out.println("Please type a string to be entered in the array");
myArray[i] = scan.nextLine();
i++;
}
System.out.println("Array contents: " + Arrays.toString(myArray));
}
System.out.println("What element would you like would you like to find in the array by performing a linear search?");
String search = scan.nextLine();
for (int j = 0; j < myArray.length; j++) {
if (myArray[j] == search){
int location = j + 1;
System.out.println("The element, " + search + " was found in the array, in which the linear search looped " + location + " times to find it." );
j = myArray.length;
}
}

You should always use .equals() and not == operator for String comparison. == operator will evaluate to true only when both the references are pointing to same String instance. To check whether String contents are equal you can use .equals() or equalsIgnoreCase().
So change your search condition from
if (myArray[j] == search)
to
if (myArray[j].equals(search))

You're using == instead of .equals which doesn't check if strings are equal. .equals will check that the values are equal, not just the reference numbers like this:
if( myArray[j].equals(search)){

Related

not executing the if statement even when the condition is true [duplicate]

This question already has answers here:
What is the difference between == and equals() in Java?
(26 answers)
Closed 5 months ago.
I have made a java code to play hangman game. I have given the user 15 chances to guess the word and once the user has guessed the correct answer it should execute the if statement but it does not. I have tried to solve this problem many times but it is never working. I would appreciate it if you could tell me the problem and give a suitable solution without making much change in my code.
My code:
import java.util.*;
public class game
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
String list[] = {"apple", "banana", "mango", "kiwi", "coconut", "papaya", "lichi", "strawberry", "orange", "cherry"};
int rand = (int)(Math.random()*9)+0;
String word = list[rand];
String ask = "_";
for(int i = 1; i < word.length();i++){
ask = ask + "_";
}
System.out.println(ask);
System.out.println("hint: It is a fruit");
ArrayList<String> ans = new ArrayList<String>();
for (char i : ask.toCharArray()){
ans.add("_");
}
for (int j = 1; j<=15; j++){
System.out.println("Enter a character: ");
String input = in.next();
char alt = input.charAt(0);
int x = 0;
for (char i : word.toCharArray()){
if(alt == i){
ans.set(x, input);
}
x++;
}
for (String i : ans){
System.out.print(i);
}
int y = 0;
ArrayList<String> answer = new ArrayList<String>();
for (char i : word.toCharArray()){
answer.add("_");
}
for(char i : word.toCharArray()){
String alternate = String.valueOf(i);
answer.set(y, alternate);
y++;
}
if (ans == answer){
System.out.println("\nyou win");
break;
}
System.out.println("\n"+ans);
System.out.println(answer
);
}
}
}
Due to so many many unsuccessful attempts my code may have some unnecessary lines which are making the long.
when you use == it compares whether these two reference variables are pointing to the same object or not.
if you want to compare their content then you should use the equals() method which compares the content of the object, not the object itself.
use ans.equals(answer) instead of ans== answer
Try using equals() method instead of ==.
if (ans.equals(answer)){

Not understanding the condition

I'm having problem with the condition that is in the for loop, I don't understand it, I know what it does, but I can't understand the logic of the code condition, can someone please explain it to me the logic of the condition:
if(smallWord == null || bigWord.compareTo(smallWord)<0)
/*2. Enter the Exercise2 class that performs this function:
1. Instructs the user to type a number [at least four (4): to use while loop] which indicates how many
words / sentences will be typed, and using for loop to ask the user to type those words / sentences.
2. Find and display on the console which word / sentence is the smallest (comes first alphabetically). */
import java.util.Scanner;
public class Exercise2 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Type a number greater than 4");
int size = scan.nextInt();
while (size < 4) {
System.out.println("Type a number greater than 4");
size = scan.nextInt();
}
scan.nextLine();
String smallWord = null;
for (int i = 0; i < size; i++) {
System.out.println("Shtypni fjaline e " + (i + 1) + ": ");
String bigWord = scan.next();
if (smallWord == null || bigWord.compareTo(smallWord) < 0) {
smallWord = bigWord;
}
}
System.out.println("The smallest word/sentence alphabetically is: " + smallWord);
}
}
The condition ensures that bigWord will be assigned to smallWord if:
smallWord == null
Or
bigWord is 'lesser' than smallWord (because compareTo() returns a value less than 0 if the string is lexicographically less than the argument)
The purpose of the for loop as a whole is to find the word that is lexicographically the smallest.
The way this is done is to compare each new word (bigWord) to the smallest one found so far (smallWord).
So the if test says 'if either no smallest word has been found so far, or this new word is smaller than the one found so far, then this new word is the smallest one we have right now'.

Writing a program that takes input from a user as an array and compares it to another array to check for correct answers using a while loop

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

Reading from a file to compare characters

I need to compare test answers that I read from a file. The file looks like this:
1st line = Answer key
3rd Line and below = Student ID + Student answers to test
TTFTFTTTFTFTFFTTFTTF
ABC54102 T FTFTFTTTFTTFTTF TF
DEF56278 TTFTFTTTFTFTFFTTFTTF
ABC42366 TTFTFTTTFTFTFFTTF
ABC42586 TTTTFTTT TFTFFFTF
I put the answer key (1st line) in a String called ansKey with .nextLine(). I then print the student ID in a loop and put that student's answers in another String and pass both to a method:
Scanner inFile = new Scanner(file);
while(inFile.hasNextLine())
{
//Student ID
System.out.print("\t" + inFile.next());
//Student Answers
studentAnswers = inFile.nextLine();
System.out.print("\t" + studentAnswers);
//Get examGrade
testGrade = examGrade(ansKey, studentAnswers.trim());
//Display scores
System.out.println(testGrade);
}
In my method I have a for loop to compare:
public static String examGrade(String ansKey, String studentAnswers)
{
for(int i = 0; i < studentAnswers.length(); i++)
{
if(ansKey.charAt(i) == studentAnswers.charAt(i))
score += 2;
else if(studentAnswers.charAt(i) == ' ')
score += 0;
else
score -= 1;
}
}
All of this works perfectly fine. Except my professor doesn't want me to use trim(). If I take it out, I get ArrayIndexOutOfBounds. The reason I use trim() is because studentAnswers has a space in front when I read it with .nextLine(); I can't use .next() as some of the answers have spaces in between them.
I don't believe I can use anything I haven't used in my code already (Classes not seen here, arrays, etc..). I can use StringBuffer and StringTokenizer though. Not sure how those classes would help me however. Any help would be appreciated!
Ok so if you can't use trim() or substring(), you'll have to go with arithmetic
public static String examGrade(String ansKey, String studentAnswers)
{
//Now only go up to the answer key length
for(int i = 0; i < ansKey.length(); i++)
{
//shift the index we are checking the student answers by 1
int j = i + 1;
if(ansKey.charAt(i) == studentAnswers.charAt(j))
score += 2;
else if(studentAnswers.charAt(j) == ' ')
score += 0;
else
score -= 1;
}
}

Java. Why is my code returning an infinite loop? [duplicate]

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.

Categories