/* */ package cis119.pkg09loops; import java.util.Scanner; /** * * @author AChapin */ public class WhileExamples { /** * @param args the command line arguments */ public static void main(String[] args) { Scanner scan = new Scanner(System.in); // basic while loop // keep halving d until we get down to 0 (note integer division) int d = 23; int t = 1; while (d != 0) { System.out.println("Try #" + t + ": " + d); d = d /2; t++; } // while loop to find average // asks if user wants to continue each time int sum = 0; int count = 0; int x; String ans; System.out.println("Do you have a number for me?"); ans = scan.next(); // check if most recent answer was y while (ans.equals("y")) { System.out.println("What is the first number?"); x = scan.nextInt(); // one more number read in count++; // add newest number to sum sum += x; // get new answer, possibly changing condition System.out.println("Do you have another number for me?"); ans = scan.next(); } // get and print the average System.out.println("average: " + (double)sum/count); // same thing with a sentinel value sum = 0; count = 0; x = 0; int STOP = -989; while (x != STOP){ System.out.println("Enter a number, " + STOP + " to stop."); x = scan.nextInt(); // don't want to add sentinel value into our average if (x != STOP) { count++; sum += x; } } System.out.println("average: " + (double)sum/count); // for user input int choice = 0; int choice2 = 0; // ke3ep track of total price double price = 0; System.out.println("Welcome to LiveStockMart!"); //outer menu loop, ends if they enter 3 while (choice != 3) { // show choices and get user input System.out.println("1. See total"); System.out.println("2. Buy stuff"); System.out.println("3. Check out"); choice = scan.nextInt(); // what to do depends which choice they entered // see total price if (choice == 1) { System.out.println("Current total is: $" + price); // buy stuff } else if (choice == 2) { choice2 = 0; // reset so we can start the loop again fresh //inner loop for buying stuff menu, ends if they enter 3 // (back to outer loop) while (choice2 != 3) { // show choices and get user input System.out.println("1. Buy Chickens"); System.out.println("2. Buy Elephant"); System.out.println("3. Return to Main Menu"); choice2 = scan.nextInt(); // what to do depends which choice they entered // buy some number of chickens if (choice2 == 1) { System.out.println("How many chickens? ($10 per chicken)"); int numChickens = scan.nextInt(); price += numChickens * 10; System.out.println(numChickens + " chickens purchased!"); // buy an elephant } else if (choice2 == 2) { price += 1000; System.out.println("1 elephant purchased ($1000)"); } }// end inner loop, now we're back in the main loop } }// end outer loop } }