MikeMan MikeMan - 15 days ago 5
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);

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

Answer

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();
keyboard.nextLine();

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.

Comments