java - 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”。我似乎遇到了错误的操作数错误。我能做些什么来修复它?
解决方案
以下表达式:
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");
}
}
}
} }
推荐阅读
- javascript - 如何将空格字符从字母的前面移动到后面
- ruby - 如何基于哈希值合并哈希数组但不合并值而不是覆盖
- asp.net-core - 为什么从测试转移到 Asp.Net-Core 应用程序的生产完全不起作用
- sql - 从 postgresql 上的 json 数组中的每个 json 查询值
- javascript - 当前端和后端分开时,我如何根据数据库中的记录来呈现不同的按钮
- python - Python在组内重新采样和插值
- android - 是否可以覆盖 Dagger-2 构造函数注入进行测试?
- mysql - 对表列表中的每个条目运行查询
- java - 在 MyBatis for IBM DB2 中执行多个 INSERT 语句
- r - 如何将包含 0 和 cumsum 的新向量添加到数据帧?