Reputation: 469
I can't figure out why my program won't continue past the while loop once I enter the string "end" as one of the items. I tried putting println statements after the while loop and they didn't print after I typed "end". I also tried putting a print statement at the end of the while loop and it did not print once I typed "end", so it isn't running the while loop after I type "end", but it also isn't running anything after it. Any ideas? Here's the code:
package a1;
import java.util.Scanner;
public class A1Adept {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
process(s);
}
public static void process(Scanner s) {
int[] numbers = new int[10];
double[] cost = new double[10];
String itemName = "";
int categoryNumb;
int quantities;
double costs;
System.out.println("Please enter the names of the items, their category, their quantity, and their cost.");
while(!itemName.equals("end")){
itemName = s.next();
categoryNumb = s.nextInt();
quantities = s.nextInt();
costs = s.nextDouble();
numbers[categoryNumb] += quantities;
cost[categoryNumb] += (costs*quantities);
}
System.out.println("win");
int qMax = 0;
int qMin = 0;
int cLarge = 0;
int cLeast = 0;
int max = 0;
int min = 100;
double large = 0;
double least = 100;
for (int i = 0; i < 10; i++){
if (numbers[i] >= max)
{
max = numbers[i];
qMax = i;
}
if (numbers[i] <= min){
min = numbers[i];
qMin = i;
}
if (cost[i] >= large){
large = cost[i];
cLarge = i;
}
if (cost[i] <= least){
least = cost[i];
cLeast = i;
}
}
System.out.println("Category with the most items:"+qMax);
System.out.println("Category with the least items:"+qMin);
System.out.println("Category with the largest cost:"+cLarge);
System.out.println("Category with the least cost:"+cLeast);
}
}
Upvotes: 0
Views: 167
Reputation: 11662
It will stop if you write "end" followed by an int, another int and a double.
This is because you are first checking for "end", then asking for the 4 inputs.
The while(condition) is evaluated at the beginning of every loop.
So your program goes like this :
If you want to exit as soon as the user types "end" change it to :
while (true) { // Creates an "endless" loop, will we exit from it later itemName = s.next(); if (itemName.equals("end")) break; // If the user typed "end" exit the loop // Go on with the rest of the loop
Upvotes: 3