【问题标题】:How to stop scanner after 6 reading 6 integers?6读取6个整数后如何停止扫描仪?
【发布时间】:2014-09-06 14:23:34
【问题描述】:

我现在正在学习 Java,但遇到了一个问题。该程序决定第三个点是否在笛卡尔坐标系中的矩形内。第一个点是矩形的左上角,第二个点是右下角。您必须像这样输入它:a b c d e f,其中左(a,b)和右(c,d)。 E和f是第三点的点。我希望扫描仪在 6 个整数后停止,因此无需填写非整数,例如“结束”。这是我的代码的一部分:

import java.util.Scanner;

public class Rectangle {
    Scanner scanner = new Scanner(System.in);

    void insideRectangle() {

        int coordinate;
        int a;
        int b;
        int c;
        int d;
        int e;
        int f;

        System.out.println("Please fill in the numbers (6 maximum), with spaces in between");

        a = 0;
        b = 0;
        c = 0;
        d = 0;
        e = 0;
        f = 0;

        while ( scanner.hasNextInt() ) {
            coordinate = scanner.nextInt();
            a = coordinate;
            coordinate = scanner.nextInt();
            b = coordinate;
            coordinate = scanner.nextInt();
            c = coordinate;
            coordinate = scanner.nextInt();
            d = coordinate;
            coordinate = scanner.nextInt();
            e = coordinate;
            coordinate = scanner.nextInt();
            f = coordinate;
        }

        if ( a > c ) {
          System.out.println("error");
        } else if ( b < d) {
          System.out.println("error");
        } else if ( e >= a && c >= e && f <= b && d <= f ) {
          System.out.println("inside");
        } else {
          System.out.println("outside");
        }
    } 
}

【问题讨论】:

  • while 循环在 每个 循环通过时读取 6 个坐标。只需杀死循环并保留身体。 (另外,您可以省去重复的coordinate 变量,直接分配给a..f,即使是那些也应该重构,但这可能是未来的一段时间。)
  • 删除循环即可。
  • 感谢您的帮助,它成功了。我这周刚开始;-)

标签: java


【解决方案1】:

试试:

int[] values = new int[6];
int i = 0;
while(i < values.length && scanner.hasNextInt()) {
    values[i++] = scanner.nextInt();
}

那么数组包含你的 6 个值。

【讨论】:

    【解决方案2】:

    我喜欢@Jean Logeart 的方法,但我会改用for 循环:

    int[] values = new int[6];
    for (int i = 0; i < values.length && scanner.hasNextInt(); ++i) {
        values[i] = scanner.nextInt();
    }
    

    为了完整起见,您可以将数组值分配给您的 abc 变量以保持其余代码正常工作:

    int a = values[0];
    int b = values[1];
    int c = values[2];
    int d = values[3];
    int e = values[4];
    int f = values[5];
    

    请注意,即使扫描器发现的值少于 6 个,这也会起作用,因为数组值被初始化为 0。

    最后提示:要测试实现,可以从字符串创建Scanner,例如:

    Scanner scanner = new Scanner("3 4 5 6 7 8 9 10 11");
    

    【讨论】:

      猜你喜欢
      • 2021-03-06
      • 1970-01-01
      • 1970-01-01
      • 2014-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多