Xaxxis Xaxxis - 1 year ago 76
Java Question

How to print array data without displaying any if else statement

I have a following sample code from my lecture note. in my code if you try to print one directly, you get an output that does not match what I want. How to print a car list that I just select it. Without displaying any other lines. But if the input is less than 1 and over 3 then it displays the wrong message

package scanner1;
import java.util.Scanner;
public class Scanner1 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);

int carSelect;
int [] noNumb = {1,2,3};
String [] carList = {"Lexus","Bugati","McLaren"};

System.out.println("================ Car List ================");
for (int i = 0; i < noNumb.length; i++) {
System.out.println(noNumb [i]+". "+carList[i]);
}
System.out.println(" ");
System.out.print("Choose your car : ");
carSelect = scan.nextInt ();
loop:
for (int i=0; i<noNumb.length; i++){
if(carSelect == noNumb [i]){
System.out.println("Great you choose " +carList[i]);
break;
}else if (carSelect <= noNumb[i]){
System.out.println("Your input is less than 1 ");
break;
} else {
System.out.println("Wrong input ");

}
}
} }


Output:

================ Car List ================
1. Lexus
2. Bugati
3. McLaren

Choose your car : 3
Wrong input
Wrong input
Great you choose McLaren
BUILD SUCCESSFUL (total time: 1 second)

Answer Source

From your question, I think this is what you are looking for:

if (carSelect < 1){
     System.out.println("Your input is less than 1 ");  
} else if (carSelect > 3) {
     System.out.println("Wrong input ");
} else {   
   //valid input, let us check the car selected
   System.out.println("Great you choose " +carList[carSelect]);
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download