首页 > 解决方案 > 在 Java 中,我创建了表柜员,以便我们可以获得任意数量的表。但是我在这里创建的for循环并没有停止并且无限运行

问题描述

我试图制作一个程序,它可以告诉您选择的任意数量的表格。但是我创建的循环并没有停止并无限运行

public static void main(String[] args) {
    System.out.println("Enter the number you want to take table of print");
    Scanner sc = new Scanner(System.in);
    // sc multi starts from 1 and is increase everytime the loop will start so that we can multiply it with number increased//
    
    int scintmulti = 1;
    
    // scnintll is the number which is scint * 10 because we have to take the table until it we reach the scint x 10
    
    int scintll = sc.nextInt()*10;

    for (int scint = sc.nextInt(); scint <= scintll; scintmulti++) {
        System.out.println(scint + "*" + scintmulti + "=" + scint * scintmulti);

        sc.close();
    }

}}

标签: javafor-loop

解决方案


看起来 的值scint总是相同的。这就是无限循环的原因。

在 for 循环中初始化只发生一次,这意味着scint = sc.nextInt();只在开始时调用。您可能希望增加 of 的值scint而不是scintmultifor 循环结束。

编辑:我猜这是你想从上面的代码片段中实现的。现在循环终止一次scintll

public static void main(String[] args) {
    System.out.println("Enter the number you want to take table of print");
    Scanner sc = new Scanner(System.in);
    // sc multi starts from 1 and is increase everytime the loop will start so that we can multiply it with number increased//

    int scintmulti = 1;

    // scnintll is the number which is scint * 10 because we have to take the table until it we reach the scint x 10

    int scintll = sc.nextInt()*10;

    for (int scint = sc.nextInt(); scint <= scintll; scint++, scintmulti++) {
        System.out.println(scint + "*" + scintmulti + "=" + scint * scintmulti);

        sc.close();
    }

}

推荐阅读