gpt4 book ai didi

java - 使用标准/输出流作为字符串输入/输出

转载 作者:太空宇宙 更新时间:2023-11-04 15:01:46 24 4
gpt4 key购买 nike

我有一个作业,指出“您可以假设输入将来自流中的标准输入。您可以假设标记可以访问所有标准库”。

如何读取多行/输入并将所有输入保存为一个字符串,然后从函数输出该字符串?

目前这是我的功能,但它无法正常工作,在一个阶段它没有读取超过一行,现在它根本不起作用。

public static String readFromStandardIO() {

String returnValue = "";

String newLine = System.getProperty("line.separator");
System.out.println("Reading Strings from console");

// You use System.in to get the Strings entered in console by user
try {
// You need to create BufferedReader which has System.in to get user
// input
BufferedReader reader = new BufferedReader(new InputStreamReader(
System.in));
String userInput;
System.out.println("Enter text...\n");
while (!(reader.readLine() == reader.readLine().trim())) {
userInput = reader.readLine();
returnValue += userInput;
}

System.out.println("You entered : " + returnValue);
return returnValue;

} catch (Exception e) {

}
return null;
}

感谢您的帮助!

最佳答案

问题是您调用了 reader.readLine() 三次,因此您最终会比较两个完全不同的字符串,然后记录另一个字符串。

此外,使用 == 来比较字符串通常是不受欢迎的(因为用 == 比较对象会询问它们是否是同一个实际对象(是的,Java 在这方面对字符串很宽容,但仍然不受欢迎))。

您需要做一些更类似于:

public static String readFromStandardIO() {

String returnValue = "";

System.out.println("Reading Strings from console");

// You use System.in to get the Strings entered in console by user
try {
// You need to create BufferedReader which has System.in to get user
// input
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String userInput;
System.out.println("Enter text...\n");
while (true) {
userInput = reader.readLine();
System.out.println("Finally got in here");
System.out.println(userInput);
returnValue += userInput;
if (!userInput.equals(userInput.trim())) {
break;
}
}

System.out.println("You entered : " + returnValue);

} catch (Exception e) {

}
return returnValue;

}

关于java - 使用标准/输出流作为字符串输入/输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22492184/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com