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!