java - 如何在数组中正确打断?

标签 java arrays

我有一个关于中断输入的问题,因为我的代码输入两次“-1”来停止输入,实际上我想输入一次“-1”来停止输入,然后显示数组输出.

下面是我的代码:

import java.util.Scanner;

public class NewTMA {
    public static float[][] clone(float[][] a) throws Exception {
        float b[][] = new float[a.length][a[0].length];

        for (int i = 0; i < a.length; i++) {
            for (int j = 0; j < a[0].length; j++) {
                b[i][j] = a[i][j];
            }
        }
        return b;
    }

    public static void main(String args[]) {

        Scanner sc = new Scanner (System.in);
        System.out.println("enter row size");
        int row =  Integer.parseInt(sc.nextLine());
        System.out.println("enter column size");
        int column = Integer.parseInt(sc.nextLine());

        System.out.println ("Type float numbers two-dimensional array of similar type and size with line break, end by -1:");
        float[][] a = new float[row][column];

        for (int i=0; i<row; i++) {
            for (int j=0; j<column; j++) {
                String line = sc.nextLine();
                if ("-1".equals(line)) {
                    break;
                }
                a[i][j]=Float.parseFloat(line);
            }
         }

        System.out.println("\n The result is:");

        try {
            float b[][] = clone(a);

            for (int i = 0; i < a.length; i++) {
                for (int j = 0; j < a[0].length; j++) {
                    System.out.print(b[i][j] + " ");
                }
                System.out.println();
            }

        } catch (Exception e) {
            System.out.println("Error!!!");
        }
    }
}

下面是我的输出:

   run:
 enter row size
 3
 enter column size
 2
 Type float numbers two-dimensional array of similar type and size with line breaks. end by -1:
 1.4
 2.4
 -1
 -1

 The result is:
 1.4 2.4 
 0.0 0.0 
 0.0 0.0 
 BUILD SUCCESSFUL (total time: 13 seconds)

实际上我只想输入一次“-1”来停止输入,但我不知道为什么输出显示两次“-1”来停止输入。希望有人能帮助我找出我做错的部分。谢谢。

最佳答案

break 跳出最内层循环,因此外层循环再次迭代并再次读取输入。

要打破外部循环,请使用标签:

outerLoop: // label the outer for loop
for (int i=0; i<row; i++){
    for (int j=0; j<column; j++) {
        String line = sc.nextLine();
        if ("-1".equals(line)) {
            break outerLoop; // break from the outer for loop
    }
    ...
 }

您可以使用任何 Java 允许的标签名称(为了清楚起见,我将其称为“outerLoop”)

关于java - 如何在数组中正确打断?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58551484/

相关文章:

java - 捕获 NumberFormatException

java - Android 模拟器的准确性和预测运行时间

java - Spring Security初学者的问题。构建失败

python - 在python中应用具有周期性边界条件的圆形掩模

c++ - 我的数组在 C++ Visual Studio 中仅显示 300 个元素

java - 加载 jdbc :odbc driver? 时,Class 类中的 forName() 方法做了什么

java - 有没有更好的方法来设置 JPanel 图形的初始位置?)

javascript - 将对象附加到 Javascript 数组

javascript - 如何将查询结果推送到node.js中的数组变量?

php - 数组在 foreach 中不断重复