2017-04-07 66 views
-5
import java.util.Scanner; 

public class Shout { 
    public static void main(String[] args) { 
     String str1; 
     String str2 = ""; 

     Scanner keyboard = new Scanner(System.in); 

     StringBuilder output = new StringBuilder(); 

     while (keyboard.hasNextLine()) { 
      str1 = keyboard.nextLine(); 
      StringBuilder sb = new StringBuilder(str1); 
      output.append(sb.toUpperCase().toString()).append("\n"); 
     } 
     System.out.print(output.toString()); 
    } 
} 

我正在尋找轉換多行輸入,直到EOF(ctrl + d)爲大寫。什麼可以用來打印出大寫相同的多行?例如,輸入和輸出將如下所示:如何將多行字符串輸入轉換爲大寫字母直到EOF?

car 
bus 
taxi 
CAR 
BUS 
TAXI 

重複行中的大寫。

+2

你的代碼有什麼問題? – Jens

+0

簡單,用大寫字母寫出來。 – mallaudin

+0

這段代碼並不理想,但它應該可以工作。問題是什麼? – EJP

回答

0

把每一行都放到Hashmap中,並且每次你檢查行時是否在hashmap中找到了相同的字符串。如果沒有,只需正常打印並添加到散列表。否則打印爲大寫。

代碼應該看起來與此類似。

Map<String> lines = new HashMap(); 
while (keyboard.hasNextLine()) { 
     str1 = keyboard.nextLine(); 
     StringBuilder sb = new StringBuilder(str1); 
     if(lines.get(str1)==null){ 
      // not found, put to hashmap and print normally. 
      lines.put(str1); 
      output.append(sb.toString().append("\n"); 
     }else{ 
      // found, so this line is repetitive, print the uppercase version. 
      output.append(sb.toUpperCase().toString()).append("\n"); 
     } 
} 
相關問題