对于数字的循环和可分性

时间:2013-12-04 10:40:11

标签: java loops

我已经学习了大约一个星期的Java,过去几天一直在弄乱for循环。我使用if语句来测试几个属性上数字的可分性。以下是我到目前为止所做的事情。

int g = 18;

if ((g % 2 )== 0 && (g % 3)== 0)
{
    System.out.println("g is divisible by 2 and 3");
}
else
{
    System.out.println("g is not divisible by 2 and 3");
}

if ((g % 7 )== 0 || (g % 9) == 0)
{
    System.out.println("g is divisible by 7 or 9");
}
else
{
    System.out.println("g is not divisible by 7 or 9");
}

if (((g % 2 )== 0) && ((g % 3) == 0) && ((g % 5) != 0))
{
    System.out.println("g is divisible by 2 and 3 but 5");
}
else
{
    System.out.println("g is not divisible by 2 and 3 but 5");
}

我正在尝试使用for循环来修改上面的每个程序,以便在每个程序的单次运行中测试1到100之间的所有数字。以下是我的for声明。

for(g=1;g<=100;++g)

麻烦的是,我的程序甚至没有运行。我完全错了吗?正确方向的一点将不胜感激。非常感谢。

2 个答案:

答案 0 :(得分:0)

这应该运行:

public class Demo{

    public static void main(String[] args){
        for( int g = 1; g < 101; g++){
             if ((g % 2 )== 0 && (g % 3)== 0)
                System.out.println("g is divisible by 2 and 3");
             else
                System.out.println("g is not divisible by 2 and 3");    
             if ((g % 7 )== 0 || (g % 9) == 0)
                System.out.println("g is divisible by 7 or 9");
             else
                System.out.println("g is not divisible by 7 or 9");    
             if (((g % 2 )== 0) && ((g % 3) == 0) && ((g % 5) != 0))
                System.out.println("g is divisible by 2 and 3 but 5");
             else
                System.out.println("g is not divisible by 2 and 3 but 5");
        }
    }
}

答案 1 :(得分:0)

试试这个:

public class Sample {

    public static void main(String[] args) {

        for (int g = 1; g <= 100; g++) {
            if ((g % 2) == 0 && (g % 3) == 0) {
                System.out.println(g + " is divisible by 2 and 3");
            } else {
                System.out.println(g + " is not divisible by 2 and 3");
            }

            if ((g % 7) == 0 || (g % 9) == 0) {
                System.out.println(g + " is divisible by 7 or 9");
            } else {
                System.out.println(g + " is not divisible by 7 or 9");
            }

            if (((g % 2) == 0) && ((g % 3) == 0)) {
                if ((g % 5) == 0) {
                    System.out.println(g + " is divisible by 2 and 3 and 5");
                } else {
                    System.out.println(g + " is divisible by 2 and 3 but 5");
                }
            } else if ((g % 5) == 0) {
                System.out.println(g + " is not divisible by 2 and 3 but 5");
            } else {
                System.out.println(g + " is not divisible by 2 and 3 and 5");
            }
        }
    }
}