2014-10-11 54 views
0

我真的被困在這一個。我必須創建一個手機計劃附加菜單。然後我必須編寫一個java代碼段,它將顯示這些選項的菜單並循環以允許用戶選擇所需的選項,直到用戶輸入-1。這是我到目前爲止:使用哨兵在Java中的循環去添加手機計劃選項

import java.util.Scanner; 


public class CellPhone { 

public static void main(String[] args) { 
    //new array 
    String [] plans = new String[4]; 

    plans[0] = "a. 200 or less text messages a month: $5.00"; 
    plans[1] = "b. Additional line: $9.99"; 
    plans[2] = "c. International calling: $3.99"; 
    plans[3] = "d. Early nights and weekends: $16.99"; 

    System.out.println("Here are your plan options: "); 

    //outputs the contents of the array 
    for(int i = 0; i < 4; i++) { 
     System.out.println(plans[i]); 
    } 

    // Sentinel loop for adding options 
    final String SENTINEL = "-1"; 
    String choices = plans[0]; 
    Scanner scanner = new Scanner(System.in); 
    System.out.println("What would you like to add to your plan (options are a,b,c, or d. Enter -1 when you are finished): "); 
    String yourChoice = scanner.nextLine(); 
    while (yourChoice != SENTINEL) { 




    } 

} 

} 

我到底該如何做到這一點,以及我需要在while循環中放什麼?謝謝!

回答

0

你可以做這樣的事情。

while(true) { 
    System.out.println("What would you like to add to your plan (options are a,b,c, or d. Enter -1 when you are finished): "); 
    String yourChoice = scanner.nextLine(); 
    if(yourChoice.equals(SENTINEL)) 
     return; 
} 

,或者如果你必須使用定點:

do { 
     System.out.println("What would you like to add to your plan (options are a,b,c, or d. Enter -1 when you are finished): "); 
     yourChoice = scanner.nextLine(); 
    } while (!yourChoice.equals(SENTINEL)); 

這是一個方式來獲得總價:

double price = 0.0; 
do { 
    System.out.println("What would you like to add to your plan (options are a,b,c, or d. Enter -1 when you are finished): "); 
    yourChoice = scanner.nextLine(); 
    switch (yourChoice) { 
     case "a": 
      price += Double.parseDouble(plans[0].substring(plans[0].length()-4, plans[0].length())); 
      break; 
     case "b": 
      price += Double.parseDouble(plans[1].substring(plans[1].length()-4, plans[1].length())); 
      break; 
     case "c": 
      price += Double.parseDouble(plans[2].substring(plans[2].length()-4, plans[2].length())); 
      break; 
     case "d": 
      price += Double.parseDouble(plans[3].substring(plans[3].length()-5, plans[3].length())); 
      break; 
    } 
} while (!yourChoice.equals(SENTINEL)); 

System.out.println("Total price: " + price); 
+0

使得很多的感覺,我是多麼真糊塗說不等於一個字符串。非常感謝! – 2014-10-12 18:24:50

+0

我還有一個問題,我怎樣才能加總所有選項的總價?我知道價格是包含在字符串數組中,所以我怎麼能設置一些東西,當while while循環經過時,它會增加價格? – 2014-10-12 18:58:05