是什么导致我的无限循环?

时间:2015-10-07 21:12:26

标签: java loops

我似乎无法弄清楚我的代码在创建无限循环时做错了什么。如果有人能帮我解释一下,我真的很感激。

import java.util.Scanner;

class LoopMath1 {
    public static void main(String[] args) {
        Scanner inputScanner;
        inputScanner = new Scanner(System.in);

        //gets a number from a user and parses the string as an int
        System.out.println("Please give me a positive number");
        String userNum;
        userNum = inputScanner.nextLine();
        System.out.println("Your number is " + userNum + ".");
        int number = Integer.parseInt(userNum);

        printX(number);  //function call

        //prints 2 to the x power
        System.out.print("2^" + number + "=");
        int j = 1;
        int twoToThe = 2;
        while (j < number) {
            twoToThe *= 2;
            j++;
        }
        System.out.print(twoToThe);

        //determines if the user number is prime
        int i = 0;
        for (i = 1; 1 < number; i++) {
            int nPrime = number;
            if (nPrime == 0) {
                System.out.println(number + " is not prime.");
                break;
            } else {
                System.out.println(number + " is prime.");
            }

        }
    }

    //this is a function to print a certain amount of Xs, depending          on the user input
    public static void printX(int nTimes) {
        final int WIDTH = nTimes;
        while (nTimes < WIDTH) {
            System.out.print("x");
            nTimes += 1;

        }
    }
} 

2 个答案:

答案 0 :(得分:3)

for (i=1; 1 < number; i++)有拼写错误。 1应与i

中的for (i=1; i < number; i++)相同

答案 1 :(得分:2)

替换

    for (i=1; 1 < number; i++) {

通过

    for (i=1; i < number; i++) {

在for循环的第一部分初始化的递增器必须在第二部分进行测试,最好在第三部分进行测试。