需要帮助在for循环中声明变量(Java)

时间:2013-10-09 18:43:43

标签: java variables loops for-loop declare

我正在尝试执行for循环时正在编写程序并遇到错误。我想在for循环中声明一个变量,然后在该变量获得某个值时断开,但它返回错误“无法解析为变量。”

这是我的代码

int i = -1;
for (; i == -1; i = index)     
{ 
    Scanner scan = new Scanner(System.in);
    System.out.println("Please enter your first and last name");
    String name = scan.nextLine();
    System.out.println("Please enter the cost of your car,"
                     + "\nthe down payment, annual interest rate,"
                     + "\nand the number of years the car is being"
                     + "\nfinanced, in that order.");
    DecimalFormat usd = new DecimalFormat("'$'0.00");
    double cost = scan.nextDouble();
    double rate = scan.nextDouble();
    int years = scan.nextInt();
    System.out.println(name + ","
                   +  "\nyour car costs " + usd.format(cost) + ","
                   +  "\nwith an interest rate of " + usd.format(rate) + ","
                   +  "\nand will be financed annually for " + years + " years."
                   +  "\nIs this correct?");
    String input = scan.nextLine();
    int index = (input.indexOf('y'));
}

我想运行程序的输出段,直到用户输入yes,然后循环中断。

5 个答案:

答案 0 :(得分:2)

变量index的范围是for循环块的本地范围,而不是for循环本身,因此您无法说{您i = index循环中的{1}}。

无论如何,你不需要for。这样做:

index

甚至

for (; i == -1;)

最后......

while (i == -1)

顺便说一下,我不确定你想 i = (input.indexOf('y')); } ;输入input.indexOf('y')将触发此逻辑,而不只是"blatherskyte",因为输入中有"yes"

答案 1 :(得分:1)

而不是使用for循环,你可以这样做(它适合这种情况更好。

boolean exitLoop= true;
do
{
    //your code here
    exitLoop=  input.equalsIgnoreCase("y");
} while(exitLoop);

答案 2 :(得分:0)

对于无限循环,我更喜欢。

boolean isYes = false;
while (!isYes){ 
Scanner scan = new Scanner(System.in);
System.out.println("Please enter your first and last name");
String name = scan.nextLine();
System.out.println("Please enter the cost of your car,"
                     + "\nthe down payment, annual interest rate,"
                     + "\nand the number of years the car is being"
                     + "\nfinanced, in that order.");
DecimalFormat usd = new DecimalFormat("'$'0.00");
double cost = scan.nextDouble();
double rate = scan.nextDouble();
int years = scan.nextInt();
System.out.println(name + ","
                   +  "\nyour car costs " + usd.format(cost) + ","
                   +  "\nwith an interest rate of " + usd.format(rate) + ","
                   +  "\nand will be financed annually for " + years + " years."
                   +  "\nIs this correct?");
String input = scan.nextLine();
isYes = input.equalsIgnoreCase("yes");
}

答案 3 :(得分:0)

你不能这样做。如果变量在循环内声明,则每次运行都会重新创建。为了成为退出循环的条件的一部分,必须在它之外声明它。

或者,您可以使用break keyworkd结束循环:

// Should we exit?
if(input.indexOf('y') != -1)
    break;

答案 4 :(得分:0)

在这里你想使用while循环。通常你可以通过自己大声说出你的逻辑来决定使用哪个循环,而这个变量是(不)(值)这样做。

对于您的问题,在循环外部初始化变量,然后在里面设置值。

String userInput = null;
while(!userInput.equals("exit"){
  System.out.println("Type exit to quit");
  userInput = scan.nextLine();
}