使用java“if”时遇到问题陈述

发布于 2024-11-19 04:04:19 字数 928 浏览 2 评论 0原文

我试图通过编写一个简单的每周计划程序来自学java,代码中的if语句让我很伤心,这是我的代码:

import java.util.Scanner;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class Week
{
 public static void main(String[] args) throws IOException
 {
   Scanner inorout = new Scanner(System.in);
   System.out.println("Do you want to read or write (r/w)");
   String decision = inorout.nextLine();
   System.out.println(decision);
   if(decision == "r")
   {
     System.out.println("It has gone into the if");
     Scanner namer = new Scanner(System.in);
     System.out.println("What is the name of the week you want to read?");
     String r = namer.nextLine();
     Scanner s = new Scanner(new File(r + ".txt"));
     System.out.println("What is Your Name?");
     String name = s.nextLine();
     System.out.println("Welcome " + name);
   }    
 }
}

当我使用Drjava编译程序并输入“r”时,它不会运行如果声明,我不知道出了什么问题,非常感谢您的帮助

I'm trying to teach myself java by writing a simple weekly planner program and the if statment in my code is giving me grief, here is my code:

import java.util.Scanner;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class Week
{
 public static void main(String[] args) throws IOException
 {
   Scanner inorout = new Scanner(System.in);
   System.out.println("Do you want to read or write (r/w)");
   String decision = inorout.nextLine();
   System.out.println(decision);
   if(decision == "r")
   {
     System.out.println("It has gone into the if");
     Scanner namer = new Scanner(System.in);
     System.out.println("What is the name of the week you want to read?");
     String r = namer.nextLine();
     Scanner s = new Scanner(new File(r + ".txt"));
     System.out.println("What is Your Name?");
     String name = s.nextLine();
     System.out.println("Welcome " + name);
   }    
 }
}

When I compile the program using Drjava and input "r" it doesn't run the if statment, and i'm at a loss as to whats wrong, help would be much appriciated

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

银河中√捞星星 2024-11-26 04:04:19

Java 中的字符串通常使用 equals 进行比较,而不是使用 ==

Strings in Java are compared usually with equals not with ==.

£冰雨忧蓝° 2024-11-26 04:04:19

字符串决策不会与文字“r”具有引用相等性。您需要使用String.equals方法。

The String decision will not have reference-equality with the literal "r". You need to use String.equals method.

无法回应 2024-11-26 04:04:19

您应该使用decision.equals("r")

== 检查对象引用的相等性,而不是对象本身的相等性。

You should use decision.equals("r").

== check for equality of the references to the objects, not for equality of the objects themselves.

我恋#小黄人 2024-11-26 04:04:19

正如其他人所说,您需要使用 if(decision.equals("r")) 而不是 if(decision == "r")

下面是关于 Java 中字符串引用如何工作的简要说明:

String 类保留当前正在使用的字符串池,如果将文字 "r" 分配给decisiondecision 使用 .intern() 内部化(放入字符串池中),它将从字符串池中获取它,并且参考文献将是相等的。但由于 decision 是在运行时使用用户输入设置的,因此它不会自动内化,并且引用不会相等。

简而言之,在某些情况下,decision == "r" 可以计算为 true。但不要依赖它。使用 .equals() 代替。

As others have said, you need to use if(decision.equals("r")) instead of if(decision == "r").

Here's a brief explanation on how string references work in Java:

The String class keeps a pool of strings that are currently in use, and if a literal "r" was assigned to decision, or decision was internalized (put into the string pool) using .intern(), it will fetch it from the string pool and the references will be equal. But because decision is set at runtime using user input, it will not be internalized automatically, and the references will not be equal.

In short, in some situations decision == "r" can evaluate to true. But don't rely on it. Use .equals() instead.

悲凉≈ 2024-11-26 04:04:19
if(decision == "r")

== 检查对象相等性,字符串相等性
您需要使用 equals() 方法

if(decision.equals("r"))
if(decision == "r")

== checks for object equality, not string equality
you instead need to use the equals() method

if(decision.equals("r"))
如若梦似彩虹 2024-11-26 04:04:19

只是想指出,虽然许多答案中建议的 decision.equals("r") 效果很好,但同样有效的是:

if ("r".equals(decision)) {
   //do something...
}

这样做的好处是你没有担心 "r" 是否为 null。另请注意,在这种情况下,您可能希望进行不区分大小写的比较(因此用户可以根据需要键入“R”),例如:

if ("r".equalsIgnoreCase(decision)) {
   //do something...
}

Just want to point out that while the decision.equals("r") suggested in many answers will work just fine, it is equally valid to say:

if ("r".equals(decision)) {
   //do something...
}

The benefit of this is that you don't have to worry about "r" ever being null. Also note that you may want to do a case-insensitive comparison in this case (so the user can type 'R' if they want), like:

if ("r".equalsIgnoreCase(decision)) {
   //do something...
}
凤舞天涯 2024-11-26 04:04:19

尝试使用类似的东西:

if(decision.equals("r"))

Try using something like:

if(decision.equals("r"))
几度春秋 2024-11-26 04:04:19

你应该使用equals方法来比较两个字符串,字符串是一个对象,这是一个引用,equals()方法会比较两个字符串的内容,但是==会比较两个字符串的地址,

所以,你应该这样写:

if ("r".equals(decision)) {
//do something code...
}

you should use the equals method to compare the two strings,the string is a object,this is a reference,the equals() method will compare the content of two strings,but the == will compare the address of two strings

so,you should write like this:

if ("r".equals(decision)) {
//do something code...
}
请恋爱 2024-11-26 04:04:19

相等与身份

您检查相同引用 (==) 或相等对象 (.equals()) )。

原始数据类型(Int、Float 等)和引用与 ==、复杂数据类型(任何普通或自定义类、String、任何可通过 new 手动实例化的对象)进行比较) 必须与 object1.equals(object2) 进行比较。

例如,字符串可能会返回 == 误报,如在此可运行示例中所示:(复制并粘贴到文件 StringComparisonMain.java 中,编译,运行)

/**
 * Difference between identity and equality in java.
 */
public class StringComparisonMain {

    public static void main(String[] args) {

        /*
         * 
         * CREATE TWO DIFFERENT REFERENCES TO TWO DIFFERENT BUT EQUAL STRING
         * OBJECTS
         * 
         * 'two' must be created like this else test will create false
         * positives: one = "asdf"; two = "asdf"; ... will falsely yield 'true'
         * for identity check. This is due to optimizations going in inside the
         * JRE, I believe.
         */
        String one = "bla";
        String two;
        two = "b" + "l";
        two = two + "a";
        String three = "bla";

        /*
         * ACTUAL TESTING CODE
         */
        System.out.println("different reference leading to equal objects:");
        stringCompare(one, two);
        System.out.println("as above, but false positive: (!)");
        stringCompare(one, three);

        // changing to same references to the same String object
        one = two;

        System.out.println("identical references to same single object:");
        stringCompare(one, two);

        // different Strings (and ofc different objects...)
        one = "test";

        System.out.println("different Strings/objects:");
        stringCompare(one, two);

        System.out.println("\nDONE!");

    }

    private static void stringCompare(String stringOne, String stringTwo) {

        // first test for identity (reference to same object)
        if (stringOne == stringTwo) {
            System.out.println("== true");
        } else {
            System.out.println("== false");
        }

        // second test for equality (two referenced objects are equal)
        if (stringOne.equals(stringTwo)) {
            System.out.println("equals true");
        } else {
            System.out.println("equals false");
        }

        // there is not just 'System.out.println' out there...
        System.out.print("\n");
    }
}

Equality vs. Identity

You check for identical references (==), or equal objects (.equals()).

Primitive data types (Int, Float, etc.) and references are compaired with ==, complex data types (any normal or self-defined class, String, any object intantiatable by hand via new) have to be compaired by object1.equals(object2).

Strings for example can return false positives for ==, as can be seen in this runnable example here: (copy&paste into File StringComparisonMain.java, compile, run)

/**
 * Difference between identity and equality in java.
 */
public class StringComparisonMain {

    public static void main(String[] args) {

        /*
         * 
         * CREATE TWO DIFFERENT REFERENCES TO TWO DIFFERENT BUT EQUAL STRING
         * OBJECTS
         * 
         * 'two' must be created like this else test will create false
         * positives: one = "asdf"; two = "asdf"; ... will falsely yield 'true'
         * for identity check. This is due to optimizations going in inside the
         * JRE, I believe.
         */
        String one = "bla";
        String two;
        two = "b" + "l";
        two = two + "a";
        String three = "bla";

        /*
         * ACTUAL TESTING CODE
         */
        System.out.println("different reference leading to equal objects:");
        stringCompare(one, two);
        System.out.println("as above, but false positive: (!)");
        stringCompare(one, three);

        // changing to same references to the same String object
        one = two;

        System.out.println("identical references to same single object:");
        stringCompare(one, two);

        // different Strings (and ofc different objects...)
        one = "test";

        System.out.println("different Strings/objects:");
        stringCompare(one, two);

        System.out.println("\nDONE!");

    }

    private static void stringCompare(String stringOne, String stringTwo) {

        // first test for identity (reference to same object)
        if (stringOne == stringTwo) {
            System.out.println("== true");
        } else {
            System.out.println("== false");
        }

        // second test for equality (two referenced objects are equal)
        if (stringOne.equals(stringTwo)) {
            System.out.println("equals true");
        } else {
            System.out.println("equals false");
        }

        // there is not just 'System.out.println' out there...
        System.out.print("\n");
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文