【问题标题】:I can´t print out 0 . Can someone tell me why?我无法打印出 0 。有人能告诉我为什么吗?
【发布时间】:2021-05-31 08:16:33
【问题描述】:

我无法打印出 0 。谁能告诉我为什么?

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner read = new Scanner(System.in);
        System.out.print("Number: ");
        int number = read.nextInt();
        //your code goes here
        while (number >= 0) {
            if(number % 3 == 0) {
                number--;
                continue;
            }
            System.out.println(number);
            number--;
        }
    }
}

【问题讨论】:

  • 将循环更改为number > 0
  • 0 % 3 == 0true 并被if 消费,因此无法打印0
  • while (number >= 0) { if (number == 0) { } else if (number % 3 == 0) { number--;继续; } System.out.println(number);数字 - ; }

标签: java loops if-statement while-loop continue


【解决方案1】:

你继续传递 0 并且永远不会输出它:

if(number % 3 == 0) {
   number--;
   continue;
}

0 % 3 == 0 // TRUE

您需要使用当前的逻辑对0 案例进行特殊处理。我会把它留给你来解决。

【讨论】:

  • 谢谢!我做到了,它有效,但它是对的吗?我可以把 if 语句留空吗?
  • while (number >= 0) { if (number == 0) { } else if (number % 3 == 0) { number--;继续; } System.out.println(number);数字 - ; }
猜你喜欢
  • 2021-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-14
  • 1970-01-01
  • 2021-12-08
  • 1970-01-01
相关资源
最近更新 更多