2014-11-21 126 views
0

我的第一篇文章在stackoverflow上。 任務是: 編寫一個方法,該方法返回一個字符串,該方法沒有參數。該方法將從鍵盤讀取一些單詞。該輸入字「END」的方法應該返回這整個文本作爲一長排結束:Java返回輸入文本

"HI" "HELLO" "HOW" "END" 

提出的是,這樣的方法會返回一個字符串

HIHELLOHOW 

我的代碼是:

import java.util.*; 
public class Upg13_IS_IT_tenta { 
    String x, y, c, v; 
    public String text(){ 
     System.out.println("Enter your first letter"); 
     Scanner sc = new Scanner(System.in); //Can you even make this outside main? 
     x = sc.next(); 
     y = sc.next(); 
     c = sc.next(); 
     v = sc.next(); // Here I assign every word with a variable which i later will return. (at the    bottom //i write return x + y + c;). This is so that i get the string "HIHELLOWHOW" 

     sc.next(); 
     sc.next(); 
     sc.next(); 
     sc.next(); // Here I want to return all the input text as a long row 

     return x + y + c; 
    } 
} 

我知道,我的代碼有很多在它的錯誤,我是新來的Java,所以我想這樣的幫助和什麼我解釋我做錯了。謝謝!

回答

0

你可以做這樣的事情:

 public String text(){ 

     InputStreamReader iReader = new InputStreamReader(System.in); 
     BufferedReader bReader = new BufferedReader(iReader); 

     String line = ""; 
     String outputString = ""; 
     while ((line = bReader.readLine()) != null) { 
      outputString += line; 
     } 

     return outputString; 
     } 
0

也許你想要的東西,像

public String text() { 
    String input; 
    String output = ""; 
    Scanner sc = new Scanner(System.in); 
    input = sc.next(); 
    while (! input.equals("END")) { 
     output = output + input; 
     input = sc.next(); 
    } 
    return output; 
} 
0

你現在做的是建立一個程序,只能處理一個特定的輸入。 您可能希望瞄準更多的東西可重用:

public String text(){ 
     System.out.println("Talk to me:"); 
     Scanner sc = new Scanner(System.in); 
     StringBuilder text = new StringBuilder(); 

     while(!text.toString().endsWith("END")) 
     { 
      text.append(sc.next()); 
     } 

     return text.toString().substring(0, text.toString().length()-3); 
    } 

這將構建一個字符串出你輸入的,停止時字符串以「END」結尾,並返回字符串沒有最後3個字母(」結束」)。