java - 在do-while循环

时间:2016-07-19 11:44:38

标签: java arrays do-while

来自ruby / rails我在采用Java逻辑方面遇到了很多困难。

问题 - 如何在do-while循环中将值(从stdin读取)分配给整数数组,以便稍后在以后的方法中使用这些数组?

这是我的代码段:

void triAnglePerimeter() {
        //int[][] arrs;
        //int[] edge1, edge2, edge3 = new int[];
        do {
            System.out.print("X, Y for edge 1: ");
            int[] edge1 = {Ch3Ex.stdin.nextInt(),Ch3Ex.stdin.nextInt()};
            System.out.print("X, Y for edge 2: ");
            int[] edge2 = {Ch3Ex.stdin.nextInt(),Ch3Ex.stdin.nextInt()};
            System.out.print("X, Y for edge 3: ");
            int[] edge3 = {Ch3Ex.stdin.nextInt(),Ch3Ex.stdin.nextInt()};
            int[][] arrs = {edge1,edge2,edge3};

            if (!(TriangleHelpers.inputValidityChecker(arrs)))
                System.out.println("Wrong input. Retype."); 

        } while(!(TriangleHelpers.inputValidityChecker(arrs)));

        Triangle triAngle = new Triangle();
        triAngle.computeSides(arrs);

        System.out.printf("Triangle perimeter == %.2f\n", triAngle.perimeter());
    }

==================

Ch3Ex.stdin.nextInt(); - 从System.in读取的扫描程序对象

==================

控制台错误:

Tasks3.java:209: error: cannot find symbol
        } while(!(TriangleHelpers.inputValidityChecker(arrs)));
                                                       ^
  symbol:   variable arrs
  location: class Tasks3
Tasks3.java:212: error: cannot find symbol
        triAngle.computeSides(arrs);
                              ^
  symbol:   variable arrs
  location: class Tasks3
2 errors

如果我这样做:

  • 没有做什么,一切都很完美;

  • 在do-while上声明数组并在do-while中删除声明,只留下:

    edge1 = {Ch3Ex.stdin.nextInt(),Ch3Ex.stdin.nextInt()};

然后我明白了 Tasks3.java:199: error: illegal start of expression edge1 = {Ch3Ex.stdin.nextInt(),Ch3Ex.stdin.nextInt()};

  • 声明和内存分配在do-while之外:

    int [] side1 = new int [2];

并在do-while内部分别指定值:

side[0] = Ch3Ex.stdin.nextInt();

一切也很完美。

======

我的问题在于理解数组+循环的逻辑

1 个答案:

答案 0 :(得分:0)

解决方案是:

声明

int[][] arrs;
int[] edge1, edge2, edge3;

在do-while循环之外。

在do-while循环中执行以下操作:

edge1 = new int[]{Ch3Ex.stdin.nextInt(),Ch3Ex.stdin.nextInt()};
每个1-dim数组

arrs = new int[][]{edge1,edge2,edge3};

表示2-dim数组。