gpt4 book ai didi

Java 基本控制台编程 - 可以使用 hasNextLine 从控制台读取输入吗?

转载 作者:行者123 更新时间:2023-12-01 19:19:21 28 4
gpt4 key购买 nike

我看到的这段代码对我来说看起来很不自然。我通常会使用 hasNextLine() 而不是 boolean 变量 done,如 while 循环中的此代码所示,但现在我很困惑。我的问题是,当需要从控制台输入时,我可以用 hasNextLine() 替换显示变量 done 的逻辑,还是只能使用 hasNextLine () 当输入来自文件时?在输入来自控制台的情况下,使用 done 变量或 hasNextLine() 来实现此代码的更好实践方法是什么?谢谢。

// TCPClient.java

import java.net.*;
import java.io.*;
import java.lang.*;

public class TCPClient{

public static void main(String args[]){
Socket clientSock=null;
try{
int port_num = Integer.valueOf(args[1]).intValue(); //get server's port no.
clientSock = new Socket(args[0],(int)port_num); // args[0] is the server host name

/* String sock=clientSock.toString();
System.out.println(sock); */

PrintWriter oStream =
new PrintWriter(clientSock.getOutputStream(),true);

BufferedReader iStream =
new BufferedReader(new InputStreamReader
(clientSock.getInputStream()));

BufferedReader keyInput =
new BufferedReader(new InputStreamReader(System.in));

boolean done = false;
String answer = iStream.readLine();
if(answer != null)
System.out.println(answer);

while(!done){
String line = keyInput.readLine();
if(line.trim().equals("BYE"))
done = true;
oStream.println(line);
answer = iStream.readLine();
if(answer != null)
System.out.println(answer);
}

clientSock.close();
}catch(Exception e){
System.out.println(e);
}
}
}

最佳答案

@Voo 的解决方案中存在一个错误,因为 keyInput 上的 nextLine() 也可能返回 null。这是更正后的版本:

String line;
while ((line = keyInput.readLine()) != null &&
!line.trim().equals("BYE")) {
oStream.println(line);
answer = iStream.readLine();
if (answer != null) {
System.out.println(answer);
}
}
<小时/>

Can I replace the logic where the variable done is shown with hasNextLine() when input is expected from the console, or can I only use hasNextLine() when input comes from a file?

您可以将任何 InputStream 或任何 Readable(其中 Reader 是其子类型)包装在 Scanner 中,允许您对所有这些使用hasNextLine()。唯一需要注意的是,如果底层流来自控制台、管道、套接字或类似的东西,hasNextLine() 可能会无限期地阻塞等待输入。

Which is a better practice way of implementing this code where input comes from console, by using the done variable or hasNextLine()?

两者都可以,如上图所示的第三个选项也可以。这确实是一个品味问题……你认为看起来最简单的事情。 (就我个人而言,我不会使用 Scanner 只是,这样我就可以调用 hasNextLine() ...但这只是我的意见。)

使用 ScannerBufferedReader 之间的另一个显着区别是 Scanner 隐藏可能发生的任何 IOException调用 hasNext...() 并简单返回 false。对于 Scanner 作为轻量级用户输入解析器的典型用例来说,这是一件好事(因为您在 keyInput 上使用它),但可能不适用于其他用途-案例。

关于Java 基本控制台编程 - 可以使用 hasNextLine 从控制台读取输入吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5048290/

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