【问题标题】:Scanner input == null? [duplicate]扫描仪输入 == null? [复制]
【发布时间】:2016-06-12 21:55:32
【问题描述】:

我想说的是,如果你输入一个字符,它就会这样做;否则,如果扫描仪输入 == null 则改为执行此操作。我没有收到任何语法错误,我只需要知道如何措辞,这样如果您不输入任何字符并按 ENTER,它将进入我的默认设置。 这是我到目前为止所拥有的。

Shape sq = new Square(10);
                System.out.println("Choose character to fill your shape. A-Z, a-z, ! # $ % & ( ) * + Press ENTER.");
                characterChoiceSquare = input.next();
                if(characterChoiceSquare == input.next())
                {
                    for(int m = 0; m < shapeChars.length; m++)
                    }
                    {
                        if(characterChoiceSquare.equals(shapeChars[m]));
                        {
                            char[] c1 = characterChoiceSquare.toCharArray();
                            char[] shapeCharacter = new char[sq.getSizeInt()];
                            for(int i = 0; i < sq.getSizeInt(); i++) 
                            {
                                shapeCharacter[i] = c1[0]; // repeat the char input to fit shapeString
                            }
                            string = String.valueOf(shapeCharacter); //assign the value of the arraylist to shapeString

                            shapeString += string + "\n";

                            System.out.print(shapeString);
                        }
                    }
                }
                else if(characterChoiceSquare == null)
                {
                    System.out.print(sq.displayCharacters());
                }

【问题讨论】:

  • 您可以使用 .isEmpty() 作为您的条件,当使用时不输入任何内容,而是直接按回车键。
  • 我的 if - else 语句没有在我的代码中使用。这确实给了我错误。到目前为止,如果没有 if-else 的想法,它会打印两个选项。也许 if-else 不是办法。但我们的想法是要么选择一个字符,要么使用默认值,即随机字符形成相同的形状
  • 你的意思是 if(scanner.isEmpty()) ??
  • 那么您可以按照@Jonah Haney 的建议使用 switch case。
  • 这是扫描仪内置的还是我必须创建一个新方法?

标签: java if-statement null


【解决方案1】:

你可能想使用input.nextLine(),那么你的支票就是

else if (String.valueOf(characterChoiceSquare).equals("")){
    ...
}

或者,或者,甚至不做else-if 检查,只要有一个最终的else 语句,如果没有其他if 语句返回true。

按照我的建议,另一种方法是使用switch-case

switch (String.valueOf(characterChoiceSquare)){
    case "a":
        //do stuff
        break;
    case "b":
        //do stuff
        break;
    case "":
        //do stuff if characterChoiceSquare is empty
        break;
    default:
        //Do this if characterChoiceSquare does not match any cases
}

【讨论】:

  • 不会将 (characterChoiceSquare.isEmpty()) 作为字符串与 (characterChoiceChoiceSquare.toString().isEmpty()) 作为 char 甚至 (String.valueOf(characterChoiceSquare).isEmpty ))
  • @StephS 哦是characterChoiceSquare Character 还是String
  • @ Jonah - 这是一个字符
  • @StephS 我已经更新了我的答案以反映这一点。至于你原来的问题,不,不是。 characterChoiceSquare.isEmpty() 不存在。但是其他选项都是正确的。
  • 好吧,我尝试了 isEmpty,但它们不工作。他们只是像我一样什么都不做。
猜你喜欢
  • 2016-06-20
  • 2018-05-30
  • 2017-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-01
  • 2011-08-23
相关资源
最近更新 更多