gpt4 book ai didi

java - 为什么此代码不允许我输入新的内容?

转载 作者:行者123 更新时间:2023-12-01 10:42:29 25 4
gpt4 key购买 nike

这是代码:

public class Pr3 
{
public Pr3 ()
{
String x = "";
String Line = "";
Scanner sc = new Scanner (System.in);
do
{
System.out.println ("Please enter your sentence");
String NewLine = sc.nextLine();
Line = Line + " " + NewLine;
System.out.println ("Your new Line is: " + Line);
System.out.println ("Do you want to enter a new sentence? Enter Y for yes and N for no");
x = sc.next();
} while (!"N".equals(x) && "Y".equals(x));
exit(0);
}
}

这是输出:

  • 请输入您的句子
  • 夏甲
  • 您的新线路是:Hagar
  • 您想输入新句子吗?输入 Y 表示是,输入 N 表示否
  • 请输入您的句子
  • 您的新线路是:Hagar
  • 您想输入新句子吗?输入 Y 表示是,输入 N 表示否

最佳答案

改变

x = sc.next();

x = sc.nextLine();

为了消耗行尾字符。

除此之外,

Line = Line + " " + NewLine;

将把新行连接到之前的所有行。我不确定这就是您想要的(基于您打印的 System.out.println ("Your new Line is: "+ Line);)。

最后一件事:

while (!"N".equals(x) && "Y".equals(x));

是多余的。如果x等于"Y",它不等于"N",所以这样写就足够了:

while ("Y".equals(x));

关于java - 为什么此代码不允许我输入新的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34369871/

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