【问题标题】:Working on a random challenge, but having a problem with进行随机挑战,但遇到问题
【发布时间】:2021-04-27 06:45:04
【问题描述】:

//Java嵌套循环,如果用户输入小于1且大于11则必须显示错误信息。实现java嵌套for循环。

import java.util.Scanner;

class Main {
    public static void main(String args[]) {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter the size: ");
        int size = input.nextInt();
        if (size < 1 && size > 11)
            System.out.println("INVALID NUMBERS");

        for (int rows = size; size > 0; rows++) {
            for (int colums = size; colums < 11; colums++) {
                System.out.print("#");
            }
        }
        System.out.println();
    }
}

标签

【问题讨论】:

标签: java loops nested


【解决方案1】:
if(size<1 && size>11)

size 不能同时小于 1 和大于 11。

这里需要一个逻辑 OR:

if(size<1 || size>11)

【讨论】:

    【解决方案2】:

    不完全确定您的意思,但据我了解,这就是您要查找的内容?

      int size=input.nextInt(); 
      if(size<1 || size>11) {
       System.out.println("INVALID NUMBERS");
      }
       else{
        for (int rows=size;size>0;rows++){ 
          for(int colums=size;colums<11;colums++){ 
            System.out.print("#"); 
        } 
      } 
    }
    

    【讨论】:

    • 谢谢,没关系,我只是发现我的结构不对。非常感谢。
    【解决方案3】:

    首先问题不是很详细,也没有提到最终结果应该是什么样子。

    据我了解,当输入的大小大于 0 时,此代码将导致无限循环,因为以下行:- for (int rows = size; size > 0; rows++) ,循环将是无限的,因为测试条件总是大于零。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-22
      • 2021-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-09
      相关资源
      最近更新 更多