Search code examples
javaarraysloopsmenusentinel

Using a sentinel While loop in Java to go add cell phone plan options


I'm really stuck on this one. I have to create a menu of cell phone plan add ons. I then have to write a java code segment that will display a menu of these options and loop to allow the user to choose the desired options until the user enters a -1. This is what I have so far:

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) {




  }

 }

} 

How exactly can I make this happen and what do I need to put inside the while loop? Thanks!


Solution

  • You could do something like this.

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

    or if you have to use sentinel:

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

    This is one way to get the total Price:

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