Java返回输入的文本

时间:2014-11-21 12:21:21

标签: java java.util.scanner

我在stackoverflow上的第一篇文章。 任务是: 编写一个返回String的方法,该方法没有参数。该方法将从键盘读取一些单词。输入以单词“END”结尾,该方法应将整个文本作为长行返回:

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

make是为了让方法返回字符串

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的新手,所以我想帮助并解释我做错了什么。谢谢!

3 个答案:

答案 0 :(得分: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;
      }

答案 1 :(得分: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;
}

答案 2 :(得分: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);
    } 

这会从您的输入中构建一个 String ,当String以" END"结束时停止。并返回没有最后3个字母的字符串(" END")。