Hello everyone, This is my first post in here :) Need a help with v. simple exercise. I need to ask user to input 10 objects of type Product (String name, Double price). I manage to done this. What i need to do now is to validate this inputs! I want to get an console error message when user does type nothing and/or type an number instead of name (String). And same for price, when user enters a String instead of number (Double). This is what i got so far (NOT MUCH) :
try { BufferedReader input = new BufferedReader(new InputStreamReader(System.in) ); Product[] product = new Product[10]; System.out.println("Please enter 10 product names and their price"); for (int i = 0; i < product.length; i++) { System.out.println("Product name: "); String name = input.readLine(); while (name.isEmpty()) if (name == "" || name.length() == 0) { System.out.println("Must type a NAME!"); } System.out.println("Prosuct price: "); Double price = Double.parseDouble(input.readLine()); product[i] = new Product(name, price); } /**for (int i = 0; i < 11; i ++) { String name = bf.readLine(); if(name == null || name.length() == 0) { System.out.println("MUST type a name!"); for(int y = 0; y <name.length();y++) { if (!Character.isLetter(name.charAt(i))) System.out.println("Must be a String!"); } } }**/ System.out.println("Sort them by name or price? Enter n for name and p for price! "); String n = "n", p = "p"; ProductNameComparator compByName = new ProductNameComparator(); if (input.readLine() == n) { for(int i = 0; i < product.length; i++ ) { Arrays.sort(product, compByName); } for (int i = 0; i < product.length; i++) { System.out.println(product[i].getName() + ", " + product[i].getPrice()); } }Do i need to use a do/while loop? Is it better to use Scanner in this case??
Thanks a lot with advance!
The first is i wouldnt use '==' primitive comparator for strings rather use the equals() method or else the if statement wont execute i.e:
if ("".equals(name) || name.length() == 0) { other then that i cant help much because i cant test the code, but i'd suggest using a try catch around statements like"sc.nextDouble();" etc :
Scanner sc = new Scanner(System.in);
System.out.println("Type a double. i.e 7.89 or for error any string");
try {
sc.nextDouble();
} catch (Exception e) {
System.out.println("You didnt enter a double");
} therefore an exception will be thrown if a string is entered instead of an double, however you could read all input in as a string by nextLine() and then cast them to their correct objects i.e String->Double, and catch any exception that occurs during the format-NumberFormatException