java - 在 do-while 循环中将值添加到整数

标签 java loops if-statement do-while

我无法让 do-while 循环成功地将整数更改为 if 语句内的值。如果我输入“y”或“n”,它将正确退出循环,但整数的值将保持为 0。

我使用子字符串来允许用户输入“yes”或“YEs”等内容,甚至“Y3$ir” "并且仍然等同于 java 的 'y'。

代码:

import java.util.Scanner;
public class aTaskforAll
{
    public static void main (String [] args)
    {
        Scanner scan = new Scanner(System.in);
        String readAll;

        int readAllOption = 0;

        do {
            System.out.print("Do you want the words printed? (y/n) ");
            readAll = scan.nextLine();
            System.out.println(readAll.substring(0));

            if ((readAll.substring(0) == "y") || (readAll.substring(0) == "Y"))
                readAllOption = 1;
            else if ((readAll.substring(0) == "n") || (readAll.substring(0) == "N"))
                readAllOption = 2;
        }
        while (readAllOption != 0);

        System.out.println(readAllOption);    //Tester

        //Go on to do task in response to readAllOption = 1 or 2
    }
}

最佳答案

String.substring(int)方法并不像您想象的那样执行。

以下是文档内容:

Returns a new string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string.

因此,readAll.substring(0)将为您提供一个子字符串,该子字符串基本上包含原始字符串中的所有字符。

适合您的用例的正确方法是 String.substring(int,int)

来自文档

Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex.

因此,readAll.substring(0, 1) 将为您提供一个仅包含第一个字符的子字符串。

或者使用 String.startsWith(String) 会更好(更干净)方法

if (readAll.startsWith("y") || readAll.startsWith("Y"))
    //...
<小时/>

另一个问题是使用 == 进行对象(在您的情况下为字符串)相等性检查:

//...
if ((readAll.substring(0) == "y") || (readAll.substring(0) == "Y"))
//...
else if ((readAll.substring(0) == "n") || (readAll.substring(0) == "N"))
//...

不要使用==,使用.equals方法来进行相等性检查。 == 用于身份检查,这意味着仅比较引用。

<小时/>

此外,您应该在每次迭代开始时重置 readAllOption 的值:

do {
    readAllOption = 0;

退出循环。

关于java - 在 do-while 循环中将值添加到整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15264296/

相关文章:

java - Android Fragment刷新不起作用

python - Python - 合并两个字典列表,只返回第二个列表中的最后一个字典

java - 循环遍历java递归引用

Java:获取变量输出值的总和

java - if语句不执行

python - 数组和 if 语句

java - 这个设计模式是什么?

打开 netbeans 时出现 java.lang.IndexOutOfBoundsException

java - Eclipse 无法加载 SWT 库

ios - 使用 BOOL 替换冗长的代码