mardi 24 janvier 2017

Sentinel number in if statement

For data structures and algorithms in java class I've been assigned to create a program that takes user input for an item's name and price and then averages the price. I have successfully done that, however, I am having a great deal of trouble on a certain specification for the program: a sentinel number (-1) that terminates the project. Here is my code, I will explain what the issue is after.

 while(true){
       System.out.print("Enter item " + (count + 1) + " name: "); // enter name
       names[count] = in.next(); // next string becomes count index
       System.out.print("Enter item " + (count + 1) + " price: "); // enter price
       prices[count] = in.nextDouble(); // stores price entered as array index
       if(prices[count] == -1) break; // if next price == -1 // the code i want to change.
       if(names[count].equalsIgnoreCase("peas")) flag = true;
       average += prices[count];
       count++;
   }

So, my issue is: I want to terminate the program when I enter -1 for the item name, not have to enter a "dummy" item name and then have to enter the sentinel number (-1).

Sorry for the long explanation, just trying to be thorough. Thanks for taking the time to read this and help a programmer hopeful out.

Aucun commentaire:

Enregistrer un commentaire