public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
for(int i = n; i >= 0; i = n / 10)
{
i = i % 10;
if(i == 1)
System.out.print("Has 1");
n /= 10;
}
System.out.print("Has No 1");
}
它正在使用"有1"但是当没有数字1时它没有打印任何东西。缺少什么?
答案 0 :(得分:2)
您当前代码的逻辑将无法实现您希望实现的目标。因为它进入无限循环(对于具有1而非1个数字的两种情况),因为当mapply(function(tableau.m, filename){
p <- ggplot(tableau.m, aes(variable,Name)) +
geom_tile(aes(fill = value), colour = "white") +
scale_fill_distiller(palette = "YlGnBu",limits=c(min(tableau.m$value), max(tableau.m$value))) +
geom_text(aes(label=value), family="AkkuratLightPro-Regular", color = "black",lineheight=.5,size = 4)
base_size <- 9
p + theme_grey(base_size = base_size) +
labs(x = "", y = "") + scale_x_discrete(expand = c(0, 0)) +
scale_y_discrete(expand = c(0, 0)) +
theme(legend.position = "none", axis.ticks = element_blank(),
axis.text.x = element_text(size = 12, angle = 270, hjust = 0, colour = "grey50", family="AkkuratPro-Regular")
,axis.text.y = element_text(size = 12, angle = 0, hjust = 1, colour = "grey50", family="AkkuratPro-Regular")) +
ggtitle(filename) +
theme(plot.title = element_text(size = 16, angle = 0, colour = "grey25", family="AkkuratPro-Regular"))
ggsave(file=paste0(filename,".png"))
}, dat, matrix_add_cats_files)
和i >= 0
对循环中的任何正数不会为负时,您将继续循环。由于1个案例在循环中,因此它会打印该语句。
此外,即使你纠正了循环,它仍然会执行
i
无论是否有一个给定数字。
您需要将此代码更新为以下
System.out.print("Has No 1");
希望这有帮助
答案 1 :(得分:0)
辅助方法使其变得简单且可重复使用:
private static String hasDigit(int n, int digit) {
for (int i = n; i > 0; i /= 10)
if (i % 10 == digit)
return "Has " + digit;
return "Has No " + digit;
}
测试
System.out.println(hasDigit(13579, 1));
System.out.println(hasDigit(24680, 1));
System.out.println(hasDigit(13579, 2));
System.out.println(hasDigit(24680, 2));
输出
Has 1
Has No 1
Has No 2
Has 2