2013-10-09 106 views
1

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

这里是我的代码

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')); 
} 

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

回答

2

变量index的范围是本地for循环块,但不是for循环本身,所以你不能在你的for环说i = index

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

for (; i == -1;) 

甚至

while (i == -1) 

,并在年底...

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

顺便说一句,我不知道你想input.indexOf('y');输入"blatherskyte"将触发该逻辑,而不仅仅是"yes",因为输入中有y

+0

添加到上面的回答也处理大写字母Y,如果还什么“耶”的用户类型或类似的东西,那也应该处理 –

+0

@KaushikSivakumar是,该机制从环打破应该改变为“blatherskyte”,“yay”和“Y”的原因。 – rgettman

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"); 
} 
1

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

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

你不能做到这一点。如果变量在循环的内部声明, 。然后重新创建每次运行为了条件的一部分退出循环,必须在它之外或者宣布

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

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

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

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

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