-2

我现在正试图在学校熟悉 for 循环并立即学习语法。我有几个问题。如果我要在循环中初始化变量,我如何要求用户在它们进入 for 循环之前输入变量值?这是到目前为止我为它编写的代码。

在这段代码中,我的扫描仪也不适合我。我一直在研究它,所以我认为它可能需要再看一遍。

import java.util.Scanner;


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

        System.out.print("Enter your first of two numbers:");
        num1 = input.nextInt();
        System.out.print("Enter the second number:");
        num2 = input.nextInt();

        for(int num1 ; counter <= num2; counter ++)
        System.out.println("There are " + counter + " numbers between " + 
        num1 + " and " + num2);
    }
}

提前感谢您的帮助

4

2 回答 2

0

您可以将用户的输入分配给临时变量,然后在循环内将用户的输入初始化为这些临时变量。

import java.util.Scanner;


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

    System.out.print("Enter your first of two numbers:");
    int temp1 = input.nextInt();
    System.out.print("Enter the second number:");
    int num2 = input.nextInt();

    for(int num1 = temp1; counter <= num2; counter ++)
    System.out.println("There are " + counter + " numbers between " + 
    num1 + " and " + num2);
}

}

于 2018-02-25T20:27:31.603 回答
0

我认为这是最简单的解决方案:

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

        System.out.print("Enter your first of two numbers:");
        num1 = input.nextInt();
        System.out.print("Enter the second number:");
        num2 = input.nextInt();

        for(int x = num1 ; counter <= num2; counter ++)
        System.out.println("There are " + counter + " numbers between " + 
        num1 + " and " + num2);
    }
}

在 for 循环的第一个表达式中,您需要声明控制循环的变量并为其分配一个值 - 在您的情况下为 num1 。在第二个表达式中,您需要设置循环不断迭代的条件 - 我不太确定您所说的counter. 问题是这个变量没有被声明。您需要先声明它,然后才能使用它。
你想让你的程序做什么?

于 2018-02-25T20:27:38.147 回答