2016-04-30 67 views
1

我的代碼當前無法在「請輸入...」的程序開始時啓動。我希望代碼能夠在每次執行選擇1或2時返回到開始語句。 while語句不能滿足這個要求,因爲我在'choice'聲明之前不能使用while語句。據我所知,我假設使用做,而循環,但每次我嘗試實現它 - 它給我一個大括號的錯誤。在循環中應用do

以下是我的代碼片段:

System.out.println("Please type in 1 for a customer to view their portfolio, 2 to trade stocks or 3 to exit the application"); 
    int choice = Integer.parseInt(input.nextLine()); 
    { 
while (!"3".equals(choice)); 
    { 
     if (choice == 1) { 
      System.out.println(mycustomers[menuchoice].toString()); 
      return; 
         } 
     if (choice == 2) { 
      String StockSelect = "Please select a stock"; 
      for (int i = 0; i < mystocks.length; i++) { 
       // [i] is the element we are accessing 
       StockSelect += " " + i + " " + (mystocks[i].getSymbol()); 
      } 

      System.out.println(StockSelect); 

      int stockchoice = Integer.parseInt(input.nextLine()); 

      System.out.println("Select 1 to buy or 2 to sell?"); 
      int choice2 = Integer.parseInt(input.nextLine()); 

      if (choice2 == 1) { 
       System.out.println("How many stocks would you like to buy "); 
       int volumebought = Integer.parseInt(input.nextLine()); 
       for (int i = 0; i < numofstocks; i++) { 
        mycustomers[menuchoice].setBalance(
          mycustomers[menuchoice].getBalance() - (volumebought * mystocks[i].getprice())); 
        mycustomers[menuchoice].setPortfolio(); 
       } 
       System.out.println(mycustomers[menuchoice].toString()); 
       return; 
      } 
      if (choice2 == 2) { 
       System.out.println("How much stocks would you like to sell "); 
       int volumesold = Integer.parseInt(input.nextLine()); 
       for (int i = 0; i < numofstocks; i++) { 
        mycustomers[menuchoice].setBalance(
          mycustomers[menuchoice].getBalance() + (volumesold * mystocks[i].getprice())); 
          mycustomers[menuchoice].setPortfolio(); 
       } 
       System.out.println(mycustomers[menuchoice].toString()); 
       return; 
      } 

     } 
     if (choice == 3) // how to exit application 
     { 
      System.out.println("Thank you for using the application"); 
      System.out.println("The current state of all customers are:"); 
      for (int i = 0; i < mycustomers.length; i++) { 
       System.out.println(mycustomers[i].toString()); 
      } 
      System.out.println("The current state of all stocks are:"); 
      for (int i = 0; i < mystocks.length; i++) { 
       System.out.println(mystocks[i].toString()); 
      } 
      System.exit(0); 
     } 

    } 

}}} 

我將如何落實do-while循環,使其每一次可以追溯到最初的聲明中執行代碼後 - 如果只有當輸入不是3?

+2

這不是一個do while循環 – Natecat

+1

時嘗試(!選擇= 3) –

回答

1

詢問輸入while循環裏面,像這樣:

choice = Integer.parseInt(input.nextLine()); 
+0

我已經要求輸入while循環內,但它仍然強調紅色的「選擇」,表明我仍然需要初始化該變量,然後才能在while循環中使用該語句 –

+0

@KonfuChicken不要刪除頂部的行。另外,你的while循環之後有一個分號,所以它不會做任何事情,並且你的if語句永遠不會被達到。另外,既然你把選擇變成了一個整數,你的條件應該是'choice!= 3' – Natecat

+0

哦,這很有道理!得到它的工作!謝謝 ! –