如何在用户输入特定关键词后停止从扫描器读取?

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

How to stop reading from a scanner if the user inputs a specific keyword?

问题

我需要能够在控制台输入随机数量的整数,然后在完成时输入特殊字符比如Q。然而,我不确定如何验证输入是否为整数。

用户的目标是输入x个整数,然后将这些整数从客户端发送到服务器,服务器再通过一个简单的等式返回结果。我计划逐一发送这些整数,因为可以输入任意数量的整数。

我尝试过几种不同的方法。我尝试过使用hasNextInt方法。我尝试过使用nextLine,然后将每个输入添加到一个ArrayList,然后解析输入。

List<String> list = new ArrayList<>();
String line;

while (!(line = scanner.nextLine()).equals("Q")) {
    list.add(line);
}

list.forEach(s -> os.write(parseInt(s)));

这是我最初的另一个循环,它可以很好地验证输入,但是我不确定如何在完成时退出循环。

while (x < 4) {
    System.out.print("Enter a value: ");

    while (!scanner.hasNextInt()) {    
        System.out.print("Invalid input: Integer Required (Try again):");
    }
               
    os.write(scanner.nextInt());
    x++;
}

任何帮助都将不胜感激。谢谢。

英文:

I need to be able to enter a random number of integers into the console and then enter a special character such as Q when I am finished. However, I am not sure how to validate if the input is an int or not.

The point is for the user to enter x amount of ints, which get sent from client to server and the server returns the result from a simple equation. I plan on sending them one at a time as it can be any amount of ints entered.

I have tried several different ways. I have tried using hasNextInt. I tried nextLine then added each input to an ArrayList then parsed the input.

List&lt;String&gt; list = new ArrayList&lt;&gt;();
String line;
        
while (!(line = scanner.nextLine()).equals(&quot;Q&quot;)) {
    list.add(line);
}
        
list.forEach(s -&gt; os.write(parseInt(s)));

This is another loop I had originally which validates the input fine, but i'm not sure how to exit the loop when done.

while (x &lt; 4) {
    System.out.print(&quot;Enter a value: &quot;);

    while (!scanner.hasNextInt()) {    
        System.out.print(&quot;Invalid input: Integer Required (Try again):&quot;);
    }
               
    os.write(scanner.nextInt());
    x++;
}

Any help would be appreciated. Thanks

答案1

得分: 2

这里是代码翻译结果:

这是代码部分已经翻译完成

    Scanner scanner = new Scanner(System.in);
    List<Integer> list = new ArrayList<Integer>();
    
    while (scanner.hasNext()) {
        String line = scanner.nextLine();
    
        if (line.equals("Q")) {
            scanner.close();
            break;
        }
    
        try {
            int val = Integer.parseInt(line);
            list.add(val);
        } catch (NumberFormatException e) {
            System.err.println("请输入一个数字或者 Q 退出。");
        }
    }
英文:

Here you go:

Scanner scanner = new Scanner(System.in);
List&lt;Integer&gt; list = new ArrayList&lt;Integer&gt;();

while (scanner.hasNext()) {
	String line = scanner.nextLine();

	if (line.equals(&quot;Q&quot;)) {
		scanner.close();
		break;
	}

	try {
		int val = Integer.parseInt(line);
		list.add(val);
	} catch (NumberFormatException e) {
		System.err.println(&quot;Please enter a number or Q to exit.&quot;);
	}
}

答案2

得分: 2

按照以下方式执行:

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        List<Integer> list = new ArrayList<Integer>();
        String input = "";
        while (true) {
            System.out.print("Enter an integer (Q to quit): ");
            input = in.nextLine();
            if (input.equalsIgnoreCase("Q")) {
                break;
            }
            if (!input.matches("\\d+")) {
                System.out.println("This is an invalid entry. Please try again");
            } else {
                list.add(Integer.parseInt(input));
            }
        }
        System.out.println(list);
    }
}

一个示例运行:

Enter an integer (Q to quit): a
This is an invalid entry. Please try again
Enter an integer (Q to quit): 10
Enter an integer (Q to quit): b
This is an invalid entry. Please try again
Enter an integer (Q to quit): 20
Enter an integer (Q to quit): 10.5
This is an invalid entry. Please try again
Enter an integer (Q to quit): 30
Enter an integer (Q to quit): q
[10, 20, 30]

注:

  1. while(true) 创建一个无限循环。
  2. \\d+ 仅允许数字,即只允许整数。
  3. break 使循环中断。
英文:

Do it as follows:

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		List&lt;Integer&gt; list = new ArrayList&lt;Integer&gt;();
		String input = &quot;&quot;;
		while (true) {
			System.out.print(&quot;Enter an integer (Q to quit): &quot;);
			input = in.nextLine();
			if (input.equalsIgnoreCase(&quot;Q&quot;)) {
				break;
			}
			if (!input.matches(&quot;\\d+&quot;)) {
				System.out.println(&quot;This is an invalid entry. Please try again&quot;);
			} else {
				list.add(Integer.parseInt(input));
			}
		}
		System.out.println(list);
	}
}

A sample run:

Enter an integer (Q to quit): a
This is an invalid entry. Please try again
Enter an integer (Q to quit): 10
Enter an integer (Q to quit): b
This is an invalid entry. Please try again
Enter an integer (Q to quit): 20
Enter an integer (Q to quit): 10.5
This is an invalid entry. Please try again
Enter an integer (Q to quit): 30
Enter an integer (Q to quit): q
[10, 20, 30]

Notes:

  1. while(true) creates an infinite loop.
  2. \\d+ allows only digits i.e. only an integer number.
  3. break causes the loop to break.

huangapple
  • 本文由 发表于 2020年4月8日 01:30:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/61085897.html
匿名

发表评论

匿名网友

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

确定