Try catch i pętla while

0
import java.util.*;

public class Receipt {
	public static void main(String[] args) {
		
		Scanner userInput = new Scanner(System.in);
		int quantity;

			try {
				quantity = Integer.parseInt(userInput.nextLine());
			} catch (NumberFormatException nfe) {
				System.out.print("You gave me a wrong number sweetie... Do it again:");
				quantity = userInput.nextInt();
			}
		}

	}
	
}

Przejrzałem już kilka stron, które omawiają dany problem, ale jakoś dalej nie mogę zaimplementować rozwiązania w swoim programie. Może mi ktoś pomoc i wytłumaczyć jak użyć pętli while w bloku try catch tak, żeby to działało na zasadzie pobieraj liczbę i sprawdzaj do momentu aż użytkownik poda poprawnego inta?

1

Umieść blok try...catch w pętli while, a pod

quantity = Integer.parseInt(userInput.nextLine());

umieść break;

 Jeśli nie wyrzuci wyjątku to wyjdzie z pętli.
0
import java.util.*;

public class Receipt {
	public static void main(String[] args) {
		
		Scanner userInput = new Scanner(System.in);
		int quantity;
		String answer;
		float total = 0;

		
		System.out.print("Tell me sweetheart, how many products did you buy this day..?");
	
		 while(true) {
			try {
				quantity = Integer.parseInt(userInput.nextLine());
				break;
			} catch (NumberFormatException nfe) {
				System.out.print("You gave me a wrong number sweetie... Do it again:");
			}
		}
		 
		 do {
			if(quantity > 1) {
				System.out.println("So you bought " + quantity + " items, didn't you?");
			} else {
				System.out.println("So you bought only one item, didn't you?");
			}
			
			answer = userInput.nextLine();
			
			if(answer.equals("no")) System.exit(0);
			
		 } while ((answer.compareTo("yes") != 0) && (answer.compareTo("yea") != 0));
		 
		Item[] item = new Item[quantity];
		
		for(int i = 0; i < quantity; i++) {
			item[i] = new Item();
			
			System.out.print("Write a name of an item you bought: ");
			item[i].setName(userInput.nextLine());
			
			System.out.print("price: ");
			item[i].setPrice(userInput.nextFloat());
			total += item[i].getPrice();
		}
		
		System.out.println("So the receipt should look like this: " + "\n");
		
		for(int i = 0; i < quantity; i++) {
			System.out.println(item[i].getName() + " " + item[i].getPrice());
		}
		System.out.println("total: " + total);

	}
}

public class Item {
	
	float price;
	String name;
	
	Item() {
		name = "product";
		price = 0;
	}
	
	void setPrice(float price) {
		this.price = price;
	}
	
	void setName(String name) {
		this.name = name;
	}
	
	float getPrice() {
		return price;
	}
	
	String getName() {
		return name;
	}
}

Tell me sweetheart, how many products did you buy this day..?5
So you bought 5 items, didn't you?
yes
Write a name of an item you bought: l
price: 3
Write a name of an item you bought: price: <- w tym miejscu, w drugim wykonaniu pętli nie czeka aż uzupełnie item[1].name. Dlaczego za pierwszym razem działa poprawnie, a w każdym kolejnym podejściu sie sypie?

1

".nextInt() gets the next int, but doesn't read the new line character. This means that when you ask it to read the "next line", you read til the end of the new line character from the first time.

You can insert another .nextLine() after you get the int to fix this. Or (I prefer this way), read the int in as a string, and parse it to an int."

Źródło: stackoverflow.com

Dodaj jedno .nextLine() na końcu:

for(int i = 0; i < quantity; i++) {
            item[i] = new Item();
 
            System.out.print("Write a name of an item you bought: ");
            item[i].setName(userInput.nextLine());
 
            System.out.print("price: ");
            item[i].setPrice(userInput.nextFloat());
            total += item[i].getPrice();
            userInput.nextLine(); // dodane nextLine()
        }
 

I będzie śmigać. Jak użytkownik poda coś innego niż float w miejscu ceny to program też się wysypie.

1 użytkowników online, w tym zalogowanych: 0, gości: 1