1

我目前正在开发一个程序,并在尝试执行 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'));
}

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

4

5 回答 5

2

变量index的作用域是for循环块的局部,而不是for循环本身,所以你不能i = index在你的for循环中说。

index反正你不需要。做这个:

for (; i == -1;)

甚至

while (i == -1)

最后...

    i = (input.indexOf('y'));
}

顺便说一句,我不确定你是否想要input.indexOf('y');的输入"blatherskyte"将触发此逻辑,而不仅仅是"yes",因为y输入中有 a 。

于 2013-10-09T18:47:41.247 回答
1

除了使用 for 循环,您还可以使用 do-while(它更适合这种情况。

boolean exitLoop= true;
do
{
    //your code here
    exitLoop=  input.equalsIgnoreCase("y");
} while(exitLoop);
于 2013-10-09T18:49:47.680 回答
0

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

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

String userInput = null;
while(!userInput.equals("exit"){
  System.out.println("Type exit to quit");
  userInput = scan.nextLine();
} 
于 2013-10-09T19:04:16.213 回答
0

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

或者,您可以使用breakkeyworkd 来结束循环:

// Should we exit?
if(input.indexOf('y') != -1)
    break;
于 2013-10-09T18:50:25.883 回答
0

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

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");
}
于 2013-10-09T18:48:30.343 回答