2017-10-06 65 views
0

這很難解釋,但我正在嘗試創建一個程序,只能將以句號,問號或感嘆號結尾的每個單詞的字母大寫。輸入任何標記後,只有在第二次輸入標記時才能得到結果。換句話說,我必須打兩次才能得到結果,我不知道爲什麼。我仍然在自己的工作,但我堅持這個問題。具有特定要求的句子資本家

import java.util.*; 

public class SentenceCapitalizer 
{ 
    public static void main(String[] args) 
    { 
     Scanner keyboard = new Scanner(System.in); 
     System.out.print("Input a sentence: "); 
     String line = keyboard.nextLine(); 

     String wrong = keyboard.nextLine(); 
     String[] check = {".!?"}; 
     String upper_case_line=""; 
     Scanner lineScan = new Scanner(line); 

     for (String sent : check) 
     { 
      if (sent.startsWith(wrong)) 
      { 
       System.out.println("cant use .?!"); 
      } 
      else 
      { 


      /* if (line.startsWith(" "))//if starts with space 
       System.out.println("good"); 
      else 
       System.out.println("bad"); 
      */ 

      //if (int i = 0; i < line.length; i++) 
      //{char c = line.chartAt(i); 
       while(lineScan.hasNext()) 
       { 
        String word = lineScan.next(); 
        upper_case_line += Character.toUpperCase(word.charAt(0)) + 
          word.substring(1) + " "; 
       } 

       System.out.println(upper_case_line.trim()); 
      } 
     } 

    } 
} 

回答

0

解決方案

嘿只是你的問題的快速解決方案。將字符串轉換爲字符數組,然後檢查字符數組中的'。!?'如果它發現價值,那麼它會使下一封信成爲大寫!

public class SentenceCapitalizer { 

public static void main(String[] args) { 
    //Scanner, Variable to hold ouput 
    Scanner keyboard = new Scanner(System.in); 
    System.out.print("Input a sentence: "); 
    String line = keyboard.nextLine(); 

    //Char array, boolean to check for capital 
    char [] lineChars = line.toCharArray(); 
    boolean needCapital = false; 

    //String to hold output 
    String output = ""; 

    //Check for period in line 
    for (int i = 0; i < lineChars.length; i++) { 

     //Make sure first char is upper case 
     if (i == 0) { 
      lineChars[i] = Character.toUpperCase(lineChars[i]); 
     } 

     //Check for uppercase if char is not space 
     if (needCapital && Character.isLetter(lineChars[i])) { 
      lineChars[i] = Character.toUpperCase(lineChars[i]); 
      needCapital = false; 
     } 

     if (lineChars[i] == '.' || lineChars[i] == '?' || lineChars[i] == '!') { 
      needCapital = true; 
     } 

     //Add character to string 
     output += lineChars[i]; 
    } 

    //Output string 
    System.out.println (output); 
} 
} 
+0

謝謝你的工作 –

+0

@SirNicholas沒問題!樂意效勞! – cunniemm

相關問題