Java计数,它将每一个可被3整除的数字替换为hop,将每一个可被5整除的数字替换为hop

Java计数,它将每一个可被3整除的数字替换为hop,将每一个可被5整除的数字替换为hop,java,Java,Java计数,它将每一个可被3整除的数字替换为hop,将每一个可被5整除的数字替换为hop public class Hoppity { public static void main(String[] args) { int count = 1; while(count <= 25) { System.out.println(count); count++; } if (count

Java计数,它将每一个可被3整除的数字替换为hop,将每一个可被5整除的数字替换为hop

public class Hoppity {

     public static void main(String[] args)
   {
      int count = 1;

      while(count <= 25) {
         System.out.println(count);
         count++;
      }

      if (count % 3==0) {
         System.out.println("Hop");
      }
      else if (count % 5==0) {
         System.out.println("Hoppity");
      }


   }
}
公共类{
公共静态void main(字符串[]args)
{
整数计数=1;

而(count您的代码将不会输出任何内容,除了数字1到25

当您到达
System.out.println
语句时,
count
将是26,它既不除以3也不除以5


解决方案是将
if
语句放在
while
循环中。更好的方法是,使用
for
循环,将
count
变量的作用域放在循环中。(
for(int count=1;count通常我会说,找出答案。但是如果你真的被卡住了。你的if在循环之外。注意大括号

public static void main(String[] args){ 

    int count = 1;

    while(count <= 25) {

       if (count % 3==0) {
         System.out.println("Hop");
       }else if (count % 5==0) {
         System.out.println("Hoppity");
       }else{
         System.out.println(count);
       }
    count++;
   }//end while
}//end main
publicstaticvoidmain(字符串[]args){
整数计数=1;

虽然(count),但你应该解释为什么你决定用15来打印“Hop”而不是“Hop\n hoppity”。这是真的。OP并没有在那里谈论想要的行为。我想我应该让他或她来解决这个问题。我可以对此表示同情。这个答案很有用,+1。