2013-10-09 105 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(); 
}