gpt4 book ai didi

java - 字符串数组的结束输入

转载 作者:行者123 更新时间:2023-12-03 20:29:33 25 4
gpt4 key购买 nike

我正在尝试输入一个字符串数组(每个字符串都是一个问题)我的代码如下:

void read_quest()throws IOException
{
System.out.println("enter the questions(enter null to end input operation)");
for(int i = 0;; i++)
{
question[i]=in.readLine();
if(question[i].equals("\0")==true)
{
n=i-1;
break;
}
}
}

但是循环永远不会退出我正在使用 bluej,因为它用于学校项目(我们只能使用 bluej)提前致谢

最佳答案

在 Java 中,您不必处理 "\0" .此外,它 might be hard for the user to input NUL character反正。

方法in.readLine()返回 String这是用户输入的,不包括终止它的行尾字符。

  • 如果您想检查用户是否在未输入任何文本的情况下按下 Enter,请将输入与空字符串 "" 进行比较像这样:
    if ("".equals(question[i]))

  • 如果你想检查 Ctrl+D ( End of transmission character ), 与 \4 比较as said in this post :
    if ("\4".equals(question[i])) .
    注意:无法在 Eclipse 中对此进行测试,用户无论如何都必须在 Ctrl+D 后按 Enter 键

请注意,如果用户使用 Ctrl-C , 你的 readLine()将返回 null ,您的程序将在不久后退出。


旁注:

  • 你不需要==true ,因为 x.equals(y)已经是 boolean .

  • "literal".equals(variable)variable.equals("literal") 更安全: 如果你的 variablenull , 第一个版本只产生 false没有崩溃,而第二个版本抛出 NullPointerException .

关于java - 字符串数组的结束输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23361865/

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