MikeMan MikeMan - 1 year ago 88
Java Question

keyboard being skipped in while loop

I am making code that just creates a basket to put things in it. It is a homework assignment i have pretty much done by showing inheritance in classes and extending variables to the child classes. The simplest thing is catching me up. My while loop will only request the info from the keyboard for the fruit type on the first loop of the while, thereafter the loop skips that and moves on to how many. What am i doing wrong; keep in mind im a novice, this code may not be set up to professional level and thats ok.

while((makeBasket != 'n') && (count <= 10)){

System.out.print("What fruit would you like? ");
fruitRequest[count] = keyboard.nextLine();

fruitColor = getColor(fruitRequest[count]);

System.out.print("How many " + fruitRequest[count] + " would you like? ");
fruitCount = keyboard.nextInt();

Fruit fruitBasket = new Fruit(fruitRequest[count], fruitColor, fruitCount);

for(int i = 0; i< 3; i++){
case 0:
basketRecipt[i][count] = fruitCount;
case 1:
basketRecipt[i][count] = fruitCount * fruitBasket.getPrice(fruitRequest[count], fruitColor, fruitCount);
case 2:
basketRecipt[i][count] = fruitCount * fruitBasket.getWeight(fruitRequest[count], fruitColor, fruitCount);
count +=1;

Answer Source

My gut instinct here is that you need to put in a keyboard.nextLine(); after the fruitCount assignment:

stem.out.print("How many " + fruitRequest[count] + " would you like? ");
fruitCount = keyboard.nextInt();

nextInt() only advances along the current line, so when the while loop runs again it does keyboard.nextLine() and gets an empty string of some blankspace after the int you enter.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download