2016-02-29 201 views
-1

我想说如果你输入一个字符,它会这样做;否则,如果扫描仪输入== null做,而不是。我没有收到任何语法错误,我只需要知道如何说出这一点,以便如果你不输入任何字符并按下ENTER键,那么它将会进入我的默认设置。 这是我到目前为止。扫描仪输入== null?

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()); 
       } 
+0

你可以使用.isEmpty()作为条件时,而不是仅仅打流入使用不输入任何内容。 –

+0

我的if - else语句没有被用在我的代码中。这确实给了我错误。到目前为止,没有if-else的想法,它会打印这两个选项。也许如果 - 其他不是这样。但想法是选择一个字符或去默认这是随机字符形状相同 – StephS

+0

你的意思是如果(scanner.isEmpty())? – StephS

回答

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 
} 
+0

不会(characterChoiceSquare.isEmpty())作为字符串是相同的(characterChoiceChoiceSquare.toString()。的isEmpty()),为char或偶数(将String.valueOf(characterChoiceSquare) .isEmpty)) – StephS

+0

@StephS哦'characterChoiceSquare'是一个'Character'还是'String'? –

+0

@ Jonah - 这是一个字符 – StephS