2016-02-29 173 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