Topic
4 replies Latest Post - ‏2009-02-03T14:31:52Z by SystemAdmin
SystemAdmin
SystemAdmin
210 Posts
ACCEPTED ANSWER

Pinned topic need help with my code

‏2009-01-08T15:26:49Z |
i dont know what i'm doing wrong, but if of you can help me it would be of great help :)

// The "Culminating" class.
import java.awt.*;
import hsa.Console;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;
public class Culminating
{
static Console c; // The output console

public static void main (String[] args) throws IOException
{
c = new Console ();

String questions[] = new String [5];
String answers[] = new String [5];
String guess;
answers [1] = "blue";
questions [1] = "What colour are blueberries?";
InputStreamReader converter = new InputStreamReader (System.in);
BufferedReader in = new BufferedReader (converter);
for (int i = 1 ; i < 6 ; i++)
{

System.out.println (questions [1]);
guess = c.readString ();
in.readLine ();
if (guess == answers [1])
{
System.out.println ("You're right!");

}

}

// Place your program here. 'c' is the output console
} // main method
} // Culminating class
Updated on 2009-02-03T14:31:52Z at 2009-02-03T14:31:52Z by SystemAdmin
  • SystemAdmin
    SystemAdmin
    210 Posts
    ACCEPTED ANSWER

    Re: need help with my code

    ‏2009-01-08T15:41:40Z  in response to SystemAdmin
    also its mainly the input stage in the loop that doesnt work, so far everything else works good
    • SystemAdmin
      SystemAdmin
      210 Posts
      ACCEPTED ANSWER

      Re: need help with my code

      ‏2009-01-09T02:30:08Z  in response to SystemAdmin
      The first thing I noticed was that String comparison in Java should normally be done using "myString.equals(anotherString)", not using "myString == anotherString".
  • SystemAdmin
    SystemAdmin
    210 Posts
    ACCEPTED ANSWER

    Re: need help with my code

    ‏2009-02-03T11:52:50Z  in response to SystemAdmin
    change "if (guess == answers [1])" with "if (guess.equals(answers[1])", problem will be solved
    if you use former, java compares hashcode of 2 strings, and returns false
    • SystemAdmin
      SystemAdmin
      210 Posts
      ACCEPTED ANSWER

      Re: need help with my code

      ‏2009-02-03T14:31:52Z  in response to SystemAdmin
      >> change "if (guess == answers [1])" with "if (guess.equals(answers[1])", problem will be solved
      >> if you use former, java compares hashcode of 2 strings, and returns false

      The former will not compare hashcodes. In fact if it did compare hashcodes, it would return true since .equals(..) returns true. The former compares the address of the references. Since the address of reference 'guess' is not the same as the address of reference 'answere[1]' it returns false.