为了账号安全,请及时绑定邮箱和手机立即绑定

如何在数组中正确打断?

如何在数组中正确打断?

当年话下 2023-12-13 16:29:41
我有一个关于中断输入的问题,因为我的代码输入两次“-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”来停止输入。希望有人能帮助我找出我做错的部分。谢谢。
查看完整描述

2 回答

?
哔哔one

TA贡献1854条经验 获得超8个赞

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”)


查看完整回答
反对 回复 2023-12-13
?
浮云间

TA贡献1829条经验 获得超4个赞

另一种方法是放置一个标志作为参数是否满足的指示:


 for (int i=0; i<row; i++){

    /* this is the flag */

    boolean isInputNegative = false;

    for (int j=0; j<column; j++){

       String line = sc.nextLine();

       if ("-1".equals(line)){

           isInputNegative = true;

           break;

       }

       a[i][j]=Float.parseFloat(line);

   }

   /* here is the checking part */

   if (isInputNegative) {

       break;

   }

}


查看完整回答
反对 回复 2023-12-13
  • 2 回答
  • 0 关注
  • 71 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信