1

For some reason, my (basic) program always prints the text I reserved for my else statement. I am a newb when it comes to Java, so if I am making an obvious mistake I apologize. I also searched high and low for an answer, but couldn't find one. Could you take a look at this:

package test;

import java.util.Scanner;

public class tutorial_7 {

    private static Scanner x;

        public static void main(String args []) {
            x = new Scanner(System.in);

            System.out.print("Apples, or oranges: ");
            String bog = x.next();

            if (bog == "Apples") {
                System.out.print(1);
            }
            if (bog == "Oranges") {
                System.out.print(2);
            }
            else {
                System.out.print(3);
            }
        }
    }
}

Why is the text reserved for my if statements never being output? Everything seems to be fine.

Regards, JavaNoob

4

2 に答える 2

4

文字列の比較には使用しないでください==。オブジェクトの識別のためです。

文字列の比較は、次のequals()ようなメソッドで行う必要があります。

if (bog.equals ("Oranges")) {
于 2013-09-02T02:16:02.987 に答える
1

Javaで文字列を比較するにはどうすればよいですか?

 if (bog.equals("Apples")){
    System.out.print(1);
  }
  if (bog.equals("Oranges")){
      System.out.print(2);
  }
  else{
    System.out.print(3);
  }
于 2013-09-02T02:16:12.503 に答える