未使用的声明使我的程序正常工作?

时间:2017-09-27 01:28:45

标签: java

所以我写了这段代码,然后我写了#34; int number = input.nextInt(); "在它作为一个实验。该计划正是我想要的,但我不明白为什么这样做。稍后在程序中根本不使用该变量,但如果我将其删除,程序将停止工作。有任何想法吗?我的代码如下:

import java.util.Scanner;
/*
 * Name: Ki
 */
public class Countdown {
    public static void main(String[] args) {
        //Create a Scanner object to accept the input from user
        Scanner input = new Scanner(System.in);

        // Prompt the user to enter starting number, I just set it to 5 because 
        // that's what the program had as standard input.
        System.out.println("Enter the beginning number: ");

        // I don't know how this works. I had this here as an experiment, but
        // the program now doesn't work without it so I guess I'll leave it here.
        int number = input.nextInt();

        // sets max countdown value
        int i=5;

        // Make a loop that makes the program countdown until it reaches 2
        while(i>1) 
        {
            System.out.print(i + " ... \n");
            i--;
        }
        // Makes the program print 1 without dots and print stopped at the end 
        if (i==1) System.out.println(i);
        System.out.print("Stopped");
    }
}

2 个答案:

答案 0 :(得分:1)

 int number = input.nextInt();

    // sets max countdown value


    // Make a loop that makes the program countdown until it reaches 2
    while(number>1) 
    {
        System.out.print(number + " ... \n");
        number--;
    }
    // Makes the program print 1 without dots and print stopped at the end 
    if (number==1) System.out.println(number);
    System.out.print("Stopped");

答案 1 :(得分:0)

在这里创建扫描仪,但它对用户没有任何作用。

Scanner input = new Scanner(System.in);

使用nextInt(),程序将等待用户输入。

int number = input.nextInt();

但之后你总是使用i,设置为5。

我想您想使用输入数字作为起始编号。将后半部分更改为:

    // You can remove: int i=5;

    while(number>1) 
    {
        System.out.print(number + " ... \n");
        number--;
    }
    // Makes the program print 1 without dots and print stopped at the end 
    if (number==1) System.out.println(number);
    System.out.print("Stopped");