Java返回输入的文本
我在stackoverflow上的第一篇文章。 任务是: 写一个返回字符串的方法,该方法没有参数。该方法将从键盘上读取一些单词。输入以单词END结尾。方法应将整个文本作为长行返回:Java返回输入的文本,java,java.util.scanner,Java,Java.util.scanner,我在stackoverflow上的第一篇文章。 任务是: 写一个返回字符串的方法,该方法没有参数。该方法将从键盘上读取一些单词。输入以单词END结尾。方法应将整个文本作为长行返回: "HI" "HELLO" "HOW" "END" Make使方法返回字符串 HIHELLOHOW 我的代码是: import java.util.*; public class Upg13_IS_IT_tenta { String x, y, c, v; public String text(){
"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新手,所以我希望得到帮助并解释我做错了什么。谢谢 您可以这样做:
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;
}
也许你想要像这样的东西
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;
}
您现在所做的是构建一个只能处理一个特定输入的程序。 您可能希望实现更可重用的目标:
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个字母END的字符串