无限循环试图停止

时间:2014-11-04 02:31:47

标签: loops infinite

这不应该太难了,但我还是java的新手,所以我想对这个功能有所帮助。我正在使用编程书中的代码。我复制并粘贴了代码,并在第一条消息上不断循环。我无法弄清楚导致这个问题的原因。

import java.util.Scanner;

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

        int n;
        String message;

        System.out.println( "Type in a message, and I'll display it five times." );
        System.out.print( "Message: " );
        message = keyboard.nextLine();

        for ( n = 1 ; n <= 5 ; n++ )
        {
            System.out.println( n + ". " + message );
        }


        System.out.println( "\nNow I'll display it ten times and count by 5s.");
        for ( n = 5 ; n <= 50 ; n += 5 )
        {
            System.out.println( n + ". " + message );
        }

        System.out.println( "\nFinally, three times counting backward." );
        for ( n = 3 ; n > 0 ; n = 1 )
        {
            System.out.println( n + ". " + message );
        }

    }

}

1 个答案:

答案 0 :(得分:0)

作为一个新手,我宁愿在更传统的事情中使用for循环,在每个循环中使用不同的int类型n实例,这样只会有n的一个实例存在于每个for块,实际上是n

的正确范围
String message;

System.out.println( "Type in a message, and I'll display it five times." );
System.out.print( "Message: " );
message = keyboard.nextLine();

for (int n = 1 ; n <= 5 ; n++ )
{
    System.out.println( n + ". " + message );
}


System.out.println( "\nNow I'll display it ten times and count by 5s.");
for (int n = 5 ; n <= 50 ; n += 5 )
{
    System.out.println( n + ". " + message );
}

System.out.println( "\nFinally, three times counting backward." );
for (int n = 3 ; n > 0 ; n -- )
{
    System.out.println( n + ". " + message );
}

但是你的错误实际上是你忘记在最后一个中添加-,它应该是n-=1n--而不是n=1记住{{1}始终是分配