0

我真的坚持这个。我必须创建一个手机计划插件菜单。然后我必须编写一个 java 代码段,它将显示这些选项的菜单并循环以允许用户选择所需的选项,直到用户输入 -1。这是我到目前为止所拥有的:

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 循环中放入什么?谢谢!

4

1 回答 1

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);
于 2014-10-11T22:44:46.427 回答