Java hasNextLine()与断开\n

Java hasNextLine()与断开\n,java,Java,我想用(hasNextLine())编写一个while循环来运行代码,我希望当我连续输入两行新行(用键盘上的“回车”按钮)时,它会中断 我是否可以在没有任何中断条件的情况下中断循环,如string.equals(quit)等 但是,System.out.println(sc.hasNextLine())将始终返回true以打破循环。这可以按照您想要的方式做一些事情 基本上,如果你想读台词,你需要读台词。您不能使用hasNextLine然后再使用nextInt,它们不能很好地协同工作 Scanne

我想用(
hasNextLine()
)编写一个while循环来运行代码,我希望当我连续输入两行新行(用键盘上的“回车”按钮)时,它会中断

我是否可以在没有任何中断条件的情况下中断循环,如string.equals(quit)等


但是,
System.out.println(sc.hasNextLine())
将始终返回
true
以打破循环。

这可以按照您想要的方式做一些事情

基本上,如果你想读台词,你需要读台词。您不能使用
hasNextLine
然后再使用
nextInt
,它们不能很好地协同工作

Scanner scn = new Scanner(System.in);
String line;
int empty = 0;
int input;
while(true)
{
  line=scn.nextLine().trim();
  if(line.equals(""))
  {
    ++empty;
    if(empty==2) break;
  }
  else
  {
    empty=0;
    input = Integer.parseInt(line);
    // ... do stuff with input
  }
}

它将始终变为真,直到文件结束,并且当它变为真时,循环不会中断


但是你所要做的就是测试一个空行。

你必须在每一行之前记录下其他字符的数量。当该值为零时,迭代将中断。
Scanner scn = new Scanner(System.in);
String line;
int empty = 0;
int input;
while(true)
{
  line=scn.nextLine().trim();
  if(line.equals(""))
  {
    ++empty;
    if(empty==2) break;
  }
  else
  {
    empty=0;
    input = Integer.parseInt(line);
    // ... do stuff with input
  }
}