Java Programming Using three preset cars (any type of car and any MPG per said c
ID: 3925743 • Letter: J
Question
Java Programming
Using three preset cars (any type of car and any MPG per said car)
Write a program that will display a menu for the user to select option 0-3
1. Display Auto with the highest MPG
2. Display Auto with the lowest MPG
3. Display Information for all Autos
0. Exit
Auto information will be stored in a user-defined class and instantiated in the main program. You will populate the data (using gets/sets methods). The user will make a selection which will call a method to do the display. After that the menu will be displayed again. Repeat this until the user selects Exit.
REQUIREMENTS:
1. user-defined class (Auto_Info)
2. define methods for each menu item
3. use loops, ifs, fields, switch where ever necessary
Explanation / Answer
package cardemo;
import java.util.Scanner;
class Auto_Info
{
String type;
int MPG;
public Auto_Info(String t, int m)
{
type=t;
MPG=m;
}
public int getMPG()
{
return MPG;
}
public String getType()
{
return type;
}
}
public class CarDemo {
public static void main(String[] args) {
Auto_Info autos[]=new Auto_Info[3];
autos[0]=new Auto_Info("Toyota", 50);
autos[1]=new Auto_Info("Hyundai", 38);
autos[2]=new Auto_Info("Lexus", 31);
while(true)
{
System.out.println("1. Display Auto with the highest MPG");
System.out.println("2. Display Auto with the lowest MPG");
System.out.println("3. Display Information for all Autos");
System.out.println("0. Exit");
System.out.println("Enter your option: ");
Scanner input=new Scanner(System.in);
int option=input.nextInt();
switch(option)
{
case 1: int h=highest(autos); break;
case 2: int l=lowest(autos); break;
case 3: display(autos); break;
case 0: System.exit(0);
}
}
}
static int highest(Auto_Info autos[])
{
int high=autos[0].getMPG();
int h=0;
for(int i=1;i<autos.length;i++)
{
if(autos[i].getMPG()>high)
{
h=i;
high=autos[i].getMPG();
}
}
return h;
}
static void display(Auto_Info autos[])
{
System.out.println("Sno Type MPG");
for(int i=0;i<autos.length;i++)
{
System.out.println((i+1)+" "+autos[i].getType()+" "+autos[i].getMPG());
}
}
static int lowest(Auto_Info autos[])
{
int low=autos[0].getMPG();
int l=0;
for(int i=1;i<autos.length;i++)
{
if(autos[i].getMPG()<low)
{
l=i;
low=autos[i].getMPG();
}
}
return l;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.