打印数字 3 或 6 从 1 到 1000.like 3 ,6,13,16…996,

这是我的代码。当number的值小于100时,输出正确,当number的值为1000时,输出错误


import java.util.*;

public class Test {

    public static void main(String args[]) {

        int i,x,y,z,num;

        int number=1;


        for(;number<1000;number++) {

            i=number;

               while (i > 0) {

                z=i%10; //System.out.println( "digit="+z);

                if(((z%3==0)&&(z%9!=0)&&(z!=0))||(z%6==0)&&(z!=0)) //condition for divisiblity by 3 or 6 and not by 9

                {

                    System.out.println( "number="+number);  

                    break;

                }

                i = i / 10;

            }

        }

    }

}


慕森卡
浏览 172回答 3
3回答

千万里不及你

这要短得多,而且更有意义。&nbsp; &nbsp;for(int i = 0; i < 1000; i++){&nbsp; &nbsp;String str = Integer.toString(i);&nbsp; &nbsp; &nbsp; for(int j = 0; j < str.length(); j++){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(str.charAt(j) == '3' || str.charAt(j) == '6')&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("nuber =&nbsp; "+ i);&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp;}

元芳怎么了

你的代码工作得很好,唯一缺少的是你的循环直到 999。此外,在 Java 8 中,您可以简单地执行以下操作:IntStream.range(1,1001).mapToObj(p->Integer.toString(p)).filter(p->p.contains("3")||p.contains("6")).forEach(System.out::println);输出:361316..993996- 编辑 -如果您想要从 3 或 6 开始的所有数字,您可以使用以下之一:IntStream.range(1,1001).mapToObj(p->Integer.toString(p)).filter(p->p.charAt(0)=='3'||p.charAt(0)=='6').forEach(System.out::println);输出:36303132....698699

慕无忌1623718

你似乎把事情复杂化了。相反,我会选择:IntStream.range(1,1000)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.filter(n -> String.valueOf(n).matches(“3|6”))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.forEach(n-> System.out.println(“number “ + n));或命令式方法:for(int i = 1; i < 1000; i++)&nbsp; &nbsp; &nbsp;if(String.valueOf(i).matches(“3|6”))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;System.out.println(“number “+i);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java