What condition to break out of loop when enter is hit in standard input in Java?

huangapple go评论81阅读模式
英文:

What condition to break out of loop when enter is hit in standard input in Java?

问题

我想逐词读取一行字符串输入(这就是为什么我使用 while 和 scanner.next() 而不是 scanner.nextLine())。读取工作正常,但我无法从循环中跳出,因为我似乎找不到一个好的条件。它一直从命令行接收输入。提前感谢您的帮助。这是代码:

import edu.princeton.cs.algs4.StdRandom;
import java.util.Scanner;

public class RandomWord {

    public static void main(String[] args) {
        String x = null, winner = null;
        Scanner sc = new Scanner(System.in);
        int i = 1;
        while(true)
        {
            x = sc.next();
            if (!sc.hasNext())
            {
                break;
            }
            System.out.println(x);
            if(StdRandom.bernoulli(1/i))
            {
                winner = x;
            }
            i++;
        }
        sc.close();
        System.out.println(winner);
    }
}

我尝试了各种函数,但都没有成功。

英文:

I want to read from a line of string input word for word (that's why im using a while and scanner.next() instead of scanner.nextLine()). Reading works just fine, but I can't break from the loop cause i can't seem to find a good condition for that. It keeps taking input from the command line. Thanks in advance. Here is the code:

import edu.princeton.cs.algs4.StdRandom;
import java.util.Scanner;

public class RandomWord {

	public static void main(String[] args) {
		String x = null, winner = null;
		Scanner sc = new Scanner(System.in);
		int i = 1;
		while(true)
		{
			x = sc.next();
			if (!sc.hasNext())
			{
				break;
			}
			System.out.println(x);
			if(StdRandom.bernoulli(1/i))
			{
				winner = x;
			}
			i++;
		}
		sc.close();
		System.out.println(winner);
	}
}

I tried various functions but none worked.

答案1

得分: 2

.hasNext()之前调用.next()完全违反了.hasNext()调用的目的。

我建议在while条件中使用sc.hasNext()

要仅读取一行输入,可以很容易地通过两个扫描器实现。
一个用于读取一行控制台输入,另一个用于处理该输入。
这会导致输入在整行输入之前不被处理。

import edu.princeton.cs.algs4.StdRandom;
import java.util.Scanner;

public class RandomWord {

    public static void main(String[] args) {
        String x = null, winner = null;
        final Scanner scl = new Scanner(System.in);
        int i = 1;
        final Scanner sc = new Scanner(scl.nextLine());
        while(sc.hasNext())
        {
            x = sc.next();

            System.out.println(x);
            if(StdRandom.bernoulli(1/i))
            {
                winner = x;
            }
            i++;
        }
        sc.close();
        scl.close();
        System.out.println(winner);
    }
}
英文:

Having a .next() call before a .hasNext() completely defeats the purpose of the .hasNext() call.

I would suggest using sc.hasNext() as the while condition.

To only read one line of input can be very easily achieved with two scanners.
One to read one line of console input, and another one to process that input.
This has the side-effect, of the input not being processed until the whole line is inputted.

import edu.princeton.cs.algs4.StdRandom;
import java.util.Scanner;

public class RandomWord {

    public static void main(String[] args) {
        String x = null, winner = null;
        final Scanner scl = new Scanner(System.in);
        int i = 1;
        final Scanner sc = new Scanner(scl.nextLine());
        while(sc.hasNext())
        {
            x = sc.next();

            System.out.println(x);
            if(StdRandom.bernoulli(1/i))
            {
                winner = x;
            }
            i++;
        }
        sc.close();
        scl.close();
        System.out.println(winner);
    }
}

答案2

得分: 0

如果您想要能够读取多行输入,可以使用以下方式:

while (sc.hasNext()) {
    x = sc.next();
    // ...
}

在新的一行开头按下ctrl-D(在Linux上)或ctrl-Z(在Windows上)来表示输入结束。

否则,如果您只想读取一行,请使用C0D3 M4513R的答案

英文:

If you want to be able to read more than one line of input, you can do

while (sc.hasNext()) {
    x = sc.next()
    ...
}

And end your input by pressing ctrl-D (on Linux) or ctrl-Z (on Windows) at the start of a new line to signal end of input.

Otherwise, if you want to read only one line, use C0D3 M4513R's answer.

答案3

得分: -1

Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Press Enter to continue...");
String input = scanner.nextLine();
if (input.equals("")) {
break;
}
}
System.out.println("Loop exited.");

英文:
 Scanner scanner = new Scanner(System.in);
    while (true) {
        System.out.println("Press Enter to continue...");
        String input = scanner.nextLine();
        if (input.equals("")) {
            break;
        }
    }
    System.out.println("Loop exited.");

答案4

得分: -1

你可以阅读整行并使用StringTokenizer获取标记,然后在迭代过程中将它们分配给x:

public static void main(String[] args) {
    String x = null, winner = null;
    Scanner sc = new Scanner(System.in);
    StringTokenizer tokenizer = new StringTokenizer(sc.nextLine());
    int i = 1;
    while(tokenizer.hasMoreTokens())
    {
        x = tokenizer.nextToken();
        System.out.println(x);
        if(StdRandom.bernoulli(1/i))
        {
            winner = x;
        }
        i++;
    }
    sc.close();
    System.out.println(winner);
}
英文:

You can read the whole line and use StringTokenizer to get the tokens and assign them to x while iterating:

public static void main(String[] args) {
    String x = null, winner = null;
    Scanner sc = new Scanner(System.in);
    StringTokenizer tokenizer = new StringTokenizer(sc.nextLine());
    int i = 1;
    while(tokenizer.hasMoreTokens())
    {
        x = tokenizer.nextToken();
        System.out.println(x);
        if(StdRandom.bernoulli(1/i))
        {
            winner = x;
        }
        i++;
    }
    sc.close();
    System.out.println(winner);
}

huangapple
  • 本文由 发表于 2023年6月19日 17:19:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/76505258.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定