首页 > 解决方案 > 3 print hippity 的倍数和 4 print hop 的倍数?

问题描述

//Name of Program:  HippityHop.java
//Entered by:   No Name
//Date:  10/19/2020

import java.util.Scanner;  // Needed for the Scanner class


public class HippityHop
{
public static void main(String[] args)
{
 
  
 // get scanner to read input
 Scanner keyboard = new Scanner(System.in);
  
for(int x=1; x <= 100; x++){
  if(x % 3 && x % 4) {
     System.out.println(x);
  }else{
     if(x % 3 == 0){
        System.out.println("Hippity");
     }
     if(x % 4 == 0){
        System.out.println("Hop");
        
        }
      }
  }

} }

我正在尝试创建一个程序,它在 3 的倍数上打印“Hippity”,在 4 的倍数上打印“hop”。我似乎遇到了错误的操作数错误。我能做些什么来修复它?

标签: java

解决方案


以下表达式:

if(x % 3 && x % 4) {

是不是一个合适的。正在做x%3的是计算模数。您从未将其与任何东西进行比较,因此它会引发错误的操作数错误。就像在现实生活中说的:

if x modulus 3 then do this

或者,只是为了论证(并使其更容易理解),就像说:

if x subtract 3 then do this

相反,它应该是if(x%3!=0 && x%4!=0),像这样:

import java.util.Scanner;  // Needed for the Scanner class


public class HippityHop
{
public static void main(String[] args)
{
 
  
 // get scanner to read input
 Scanner keyboard = new Scanner(System.in);
  
for(int x=1; x <= 100; x++){
  if(x % 3 !=0 && x % 4 !=0) {
     System.out.println(x);
  }else{
     if(x % 3 == 0){
        System.out.println("Hippity");
     }
     if(x % 4 == 0){
        System.out.println("Hop");
        
        }
      }
  }
} }

推荐阅读