2014-11-21 127 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个字母(”结束”)。