Hey I have code for a project im trying to finish up and I keep getting array out of bounds exceptions at a certain part and would like to know how to fix it. My project is to create a reservation system using 3 classes Room,Reservation and a client class. I'm having trouble with my bookRoom class after asking for the number of guests for the room.Any help would be greatly appreciated. The exception occurs at line 57 in the reservation class. The line in question is in bold.
`
public class Reservation {
public void roomInitialization(Room[] room,int numberOfRooms,int numberOfSmokingRooms)
{
boolean smoking=true;
String[] guestName={null,null,null,null};
for (int i=0;i<numberOfRooms;i++)
{
if (i>=numberOfSmokingRooms)
smoking=false;
room[i]=new Room(smoking,false,guestName,null,i+1);
}
}
public void displayRoomsInfo(Room[] room,int numberOfRooms)
{
for (int i=0;i<numberOfRooms;i++)
{
System.out.println("Room " + room[i].getroomNumber() + "\t" +
(room[i].getsmoking()?"Smoking room":"Non-Smoking Room"));
if (room[i].getoccupied())
{
System.out.print("Phone: "+room[i].getguestPhone()+"\t");
for(int j=0;j<4;j++)
System.out.print(room[i].getguestName()[j]+"\t");
System.out.println();
}
}
}
public void bookRoom (Room[] room, int numberOfRooms)
{
displayRoomsInfo(room, numberOfRooms);
Scanner scan = new Scanner(System.in);
Scanner scans = new Scanner(System.in);
Scanner scand = new Scanner(System.in);
System.out.print("Enter a Room Number: ");
int roomNumber = scan.nextInt()-1;
if (roomNumber >=0 && roomNumber < 30){
room[roomNumber].setoccupied(true);
System.out.print("Enter a Phone Number: ");
String guestPhone = scans.nextLine();
room[roomNumber].setguestPhone(guestPhone);
System.out.print("Enter number of guests:(Max of 4 per room) ");
int guests = scand.nextInt()-1;
String[] guestName = new String[guests];
for (int i=0;i<guestName.length;i++)
System.out.print("Enter guest names: ");
**guestName[guests] = scand.next();**
room[roomNumber].setguestName(guestName);
}
else
System.out.println("Enter a valid room number");
}
public void checkOut(Room[] room)
{
Scanner scan=new Scanner(System.in);
int roomNumber;
String[] nullguestName={null,null,null,null};
do
{
System.out.print("Enter the room number: ");
roomNumber=scan.nextInt()-1;
if (roomNumber>=0 && roomNumber<30)
break;
else
System.out.println("Enter a valid room number");
}while(true);
if (room[roomNumber].getoccupied())
{
room[roomNumber].setoccupied(false);
room[roomNumber].setguestPhone(null);
room[roomNumber].setguestName(nullguestName);
}
else
System.out.println("room "+(roomNumber+1)+" is already empty");
}
}
`
Code for the other classes
package hotel;
public class Room {
private boolean smoking;
private boolean occupied;
private String[] guestName=new String[4];
private String guestPhone;
private int roomNumber;
public Room (boolean smoking,boolean occupied,String[] guestName, String guestPhone,int roomNumber)
{
this.smoking=smoking;
this.occupied=occupied;
for (int i=0;i<4;i++)
this.guestName[i]=guestName[i];
this.guestPhone=guestPhone;
this.roomNumber=roomNumber;
}
public void setoccupied(boolean occupied) {
this.occupied = occupied;
}
public void setsmoking(boolean smoking) {
this.smoking = smoking;
}
public void setroomNumber(int roomNumber) {
this.roomNumber = roomNumber;
}
public void setguestPhone(String guestPhone) {
this.guestPhone = guestPhone;
}
public void setguestName(String[] guestName)
{
for (int i=0;i<4;i++)
this.guestName[i]=guestName[i];
}
public boolean getsmoking() {
return this.smoking;
}
public boolean getoccupied(){
return this.occupied;
}
public String getguestPhone(){
return this.guestPhone;
}
public int getroomNumber() {
return this.roomNumber;
}
public String[] getguestName()
{
String[] tempguestName=new String[4];
for (int i=0;i<4;i++)
tempguestName[i]=this.guestName[i];
return tempguestName;
}
}
package hotel;
import java.util.Scanner;
public class ReservationDemo {
public static void main(String[]args)
{
final int numberOfRooms=30, numberOfSmokingRooms=5;
Room[] room=new Room[numberOfRooms];
Reservation reservation=new Reservation();
reservation.roomInitialization(room,numberOfRooms,numberOfSmokingRooms);
int userSelection;
Scanner scan=new Scanner(System.in);
do
{
System.out.println("Press: 1-Book room\t2-checkout\t3-display all rooms\t4-exit. ");
userSelection=scan.nextInt();
switch(userSelection)
{
case 1:
reservation.bookRoom(room,numberOfRooms);
break;
case 2:
reservation.checkOut(room);
break;
case 3:
reservation.displayRoomsInfo(room,numberOfRooms);
break;
case 4:
System.exit(0);
default:
break;
}
}while (true);
}
}
There are lots of mistake in your code.
First-- Use the following code instead of your version in Reservation class
System.out.print("Enter number of guests:(Max of 4 per room) ");
int guests = scand.nextInt();
String[] guestName = new String[guests];
for (int i=0;i<guestName.length;i++) {
System.out.print("Enter guest names: ");
guestName[i] = scand.next();
}
Second -- Use the following method in Room class instead of the existing one.
public void setguestName(String[] guestName)
{
for (int i=0;i<guestName.length;i++)
this.guestName[i]=guestName[i];
}
Let me know what you achieve
You are trying to index into the guests array using the variable guests which is the size of the array, you should be using the iteration counter variable i instead:
guestName[guests] = scand.next() should be guestName[i] = scand.next()
Related
How to display the most fruit with the name and lots of fruit? Can you help me guys, I confusion to add method with sorting in this code. Thank you :D
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
System.out.print("Enter the lots of fruit: ");
int numberOfFruit = userInput.nextInt();
String[] fruitName = new String[numberOfFruit];
int[] lotsOfFruit = new int[numberOfFruit];
nameAndLotsOfFruit(userInput, numberOfFruit, fruitName, lotsOfFruit);
}
static void nameAndLotsOfFruit(Scanner userInput, int numberOfFruit, String[] nameFruit, int[] lotsOfFruit) {
for (int i = 0; i < numberOfFruit; i++) {
System.out.print("Enter the name of fruit " + (i + 1) + ": ");
nameFruit[i] = userInput.next();
System.out.print("Enter the lots of fruit " + nameFruit[i] + ": ");
lotsOfFruit[i] = userInput.nextInt();
}
}
static int theMostFruit(int numberOfFruit, String[] nameFruit, int[] lotsOfFruit) {
for (int i = 0; i < numberOfFruit; i++) {
....
}
}
You are holding name and amount informations in 2 different collections thus making it complexer to handle it. There are many ways to do it but I would've done:
Key-Value pair with fruit names as key and amounts as value
Create a custom class to hold the information
I would go for the second option now
public class FruitCounter {
static List<Fruit> listFruit = new ArrayList<>();
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
System.out.print("Enter the lots of fruit: ");
int numberOfFruit = userInput.nextInt();
nameAndLotsOfFruit(userInput, numberOfFruit);
theMostFruit();
}
static void nameAndLotsOfFruit(Scanner userInput, int numberOfFruit) {
for (int i = 0; i < numberOfFruit; i++) {
Fruit fruit = new Fruit();
System.out.print("Enter the name of fruit " + (i + 1) + ": ");
fruit.setName(userInput.next());
System.out.print("Enter the lots of fruit " + fruit.getName() + ": ");
fruit.setAmount(userInput.nextInt());
listFruit.add(fruit);
}
}
static void theMostFruit() {
Fruit mostFruit = listFruit
.stream()
.max(Comparator.comparing(Fruit::getAmount))
.orElse(null);
if (mostFruit != null)
{
System.out.print(MessageFormat.format("{0} has the highest amount with {1} pieces.", mostFruit.getName(), mostFruit.getAmount()));
}
}
static class Fruit
{
private String Name;
private int Amount;
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public int getAmount() {
return Amount;
}
public void setAmount(int amount) {
Amount = amount;
}
}
}
Please check where I use stream inside the method theMostFruit. It does the job for me. Altough if you have 2 fruits with the same amount, it would give you only one. I suggest you to handle that case by yourself as a practice with java streams.
import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Scanner;
public class AutoMobile {
private static String make;
private static String model;
private static String color;
private static int year;
private static int mileage;
private static int index =300;
public AutoMobile(String make, String model, String color, int year,
int mileage, int index) {
super();
this.make = make;
this.model = model;
this.color = color;
this.year = year;
this.mileage = mileage;
this.index = index;
}
public String getMake() {
return make;
}
public void setMake(String make) {
this.make = make;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public int getMileage() {
return mileage;
}
public void setMileage(int mileage) {
this.mileage = mileage;
}
public static int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
}
class Vehicle {
static ArrayList<AutoMobile> vehicleList = new ArrayList<>();
public static final String FILENAME = "F:\\CSU\\CSC320-01 Programming 1\\Week 8\\AutoMobile.txt";
//Prints to location with proper header, but returns package and no vehicles
public static void addVehicle() {
Scanner s = new Scanner(System.in);
System.out.println("------Add Vehicle-------");
System.out.print("Enter Vehicle make: ");
String make = s.nextLine();
System.out.print("Enter Vehicle model: ");
String model = s.nextLine();
System.out.print("Enter Vehicle color: ");
String color = s.nextLine();
System.out.print("Enter Vehicle year: ");
int year = s.nextInt();
System.out.print("Enter Vehicle mileage: ");
int mileage = s.nextInt();
System.out.print("Enter the Vehicle Index Number: ");
int index = s.nextInt();
AutoMobile a = new AutoMobile(make, model, color, year, mileage, index);
vehicleList.add(a);
System.out.println("Vehicle Added Successfully");
System.out.println("------------------------");
}
public static void removeVehicle() {
Scanner s = new Scanner(System.in);
System.out.println("------Remove Vehicle-------");
System.out.print("Enter Vehicle make: ");
String make = s.nextLine();
System.out.print("Enter Vehicle model: ");
String model = s.nextLine();
System.out.print("Enter the Vehicle Index Number: ");
int index = s.nextInt();
ListIterator<AutoMobile> iterator =vehicleList.listIterator();
boolean find = false;
while(iterator.hasNext()){
AutoMobile a1 =iterator.next();
if(a1.getMake().equalsIgnoreCase(make) && a1.getModel().equalsIgnoreCase(model) &&
a1.getIndex().equalsIgnoreCase(index)){ // Line Showing Error
iterator.remove();
find = true;
break;
}
}
if(find){
System.out.println("Vehicle Removed Successfully");
System.out.println("------------------------");
}
else{
System.out.println("No such Vehicle Exist");
System.out.println("------------------------");
}
}
public static void updateVehicle() {
Scanner s = new Scanner(System.in);
System.out.println("------Update Vehicle-------");
System.out.print("Enter the make of Automobile: ");
String make = s.nextLine();
System.out.print("Enter the model of Automobile: ");
String model = s.nextLine();
System.out.print("Enter the Vehicle Index Number: ");
int index = s.nextInt();
ListIterator<AutoMobile> iterator =vehicleList.listIterator();
boolean find = false;
while(iterator.hasNext()){
AutoMobile a1 =iterator.next();
if(a1.getMake().equalsIgnoreCase(make) && a1.getModel().equalsIgnoreCase(model)
&& a1.getIndex().equalsIgnoreCase(index)){ // Line Showing Error
System.out.println("-----Vehicle found-------");
System.out.print("Enter the new make of Automobile: ");
make = s.nextLine();
System.out.print("Enter the new model of Automobile: ");
model = s.nextLine();
System.out.print("Enter the new color of Automobile: ");
String color = s.nextLine();
System.out.print("Enter the new year of Automobile: ");
int year = s.nextInt();
System.out.print("Enter the new mileage of Automobile: ");
int mileage = s.nextInt();
a1.setMake(make);
a1.setModel(model);
a1.setColor(color);
a1.setYear(year);
a1.setMileage(mileage);
a1.setIndex(index);
find = true;
break;
}
}
if(find){
System.out.println("Vehicle Updated Successfully");
System.out.println("------------------------");
}
else{
System.out.println("No such Vehicle Exist");
System.out.println("------------------------");
}
}
public static void printfile() {
BufferedWriter bw = null;
FileWriter fw = null;
try {
fw = new FileWriter(FILENAME);
bw = new BufferedWriter(fw);
String content = "ID Make Model Color Year Mileage\n";
bw.write(content);
Iterator itr=vehicleList.iterator();
while(itr.hasNext()){
bw.write(itr.next().toString()+"\n");
}
System.out.println("Done printing");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bw != null)
bw.close();
if (fw != null)
fw.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public static void main(String[] args) throws FileNotFoundException {
do {
System.out
.println("============================VEHICLE OPTIONS============================");
System.out.println("1. Add Vehicle");
System.out.println("2. Remove Vehicle");
System.out.println("3. Update Vehicle");
System.out.println("4. Print Vehicle List");
System.out.println("5. Exit");
System.out
.println("=======================================================================");
System.out.println();
Scanner s = new Scanner(System.in);
System.out.print("Enter the choice: ");
int i = s.nextInt();
s.nextLine();
switch (i) {
case 1:
addVehicle();
break;
case 2:
removeVehicle();
break;
case 3:
updateVehicle();
break;
case 4:
printfile();
break;
case 5:
System.out.println("Good Bye!!!!!");
break;
default:
System.out.println("You entered the wrong choice!!!!");
System.out.println();
}
if(i==4)
break;
System.out.println();
} while (true);
PrintWriter pw = new PrintWriter("VehicleInventory");
String text ="Index,Make,Model,Color,Year,Mileage\n";
for(AutoMobile a : vehicleList){
text+=a.getIndex()+","+a.getMake()+","+a.getModel()+","+a.getColor()+","+a.getYear()+","+a.getMileage()+"\n";
}
pw.write(text);
pw.flush();
pw.close();
System.out.println("VehicleInventory file created succesfully");
System.out.println();
System.out.println(text);
}
}
Forgive my inexperience, but I am trying to compile a program for school that achieves the following.
private string make
private string model
private string color
private int year
private int mileage.
Your program should have appropriate methods such as:
default constructor
parameterized constructor
add a new vehicle method
list vehicle information (return string array)
remove a vehicle method
update vehicle attributes method.
All methods should include try..catch constructs. Except as noted all methods should return a success or failure message (failure message defined in catch).
Create an additional class to call your automobile class (e.g., Main or AutomobileInventory). Include a try..catch construct and print it to the console any errors.
Call automobile class with parameterized constructor (e.g., "make, model, color, year, mileage").
Then call the method to list the values. Loop through the array and print to the screen.
Call the remove vehicle method to clear the variables.
Print the return value.
Add a new vehicle.
Print the return value.
Call the list method and print the new vehicle information to the screen.
Update the vehicle.
Print the return value.
Call the listing method and print the information to the screen.
Display a message asking if the user wants to print the information to a file (Y or N).
Use a scanner to capture the response. If Y, print the file to a predefined location (e.g., C:\Temp\Autos.txt). Note: you may want to create a method to print the information in the main class.
If N, indicate that a file will not be printed.
I have the program working somewhat as i wanted, until i tried to assign index numbers to the user inputted vehicles for updating or removing at a later date. This does not return in the output, and all that is returning in the .txt file is the header, and my package listed, no vehicles. Any suggestions or help would be great!
index parameter is of primitive int data type
For int use = for comparing.
if (a1.getMake().equalsIgnoreCase(make) && a1.getModel().equalsIgnoreCase(model)
&& a1.getIndex() == index) {}
I am writing a program that takes names, dates and numbers from a user as many times as they enter it and then adds up the numbers that were entered. If you look at the third for loop you will see where I am trying to add. I tried doing total = cust[i].amount + total; but I cannot access amount for some reason.
This is for an assignment.(I know were not supposed to post homework questions on here but I'm stumped.)The only data member Customer is to have is name
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
final int MAX = 9999;
Customer [] cust = new Customer[MAX];
int choice = 0;
int cnt;
double total = 0;
for(cnt=0; cnt < MAX && (choice == 1 || choice ==2 || choice == 0); cnt++){
System.out.println("For a Service customer type 1, for a Purchaser type 2, to terminate the program press 9");
choice = s.nextInt();
switch (choice){
case 1:
cust [cnt] = new Service();
break;
case 2:
cust [cnt] = new Purchaser();
break;
default:
break;
}
}
for(int i=0; i < cnt; i++){
if(cust[i]!= null)
cust[i].showData();
}
for(int i=0; i < cnt; i++ ){
total = cust[i].amount + total;
}
s.close();
}
}
interface Functions {
public void getData();
public void showData();
}
abstract class Customer implements Functions {
protected String name;
}
class Purchaser extends Customer {
protected double payment;
public Purchaser(){
getData();
}
public void getData() {
Scanner s = new Scanner(System.in);
System.out.println("Enter the name of the customer");
name = s.nextLine();
System.out.println("Enter payment amount: ");
payment = s.nextDouble();
}
public void showData() {
System.out.printf("Customer name: %s Payment amount is: %.2f\n",name,payment);
}
}
class Service extends Customer {
protected String date;
protected double amount;
public Service () {
getData();
}
public void getData() {
Scanner s = new Scanner(System.in);
System.out.println("Enter the name of the customer");
name = s.nextLine();
System.out.println("Enter date of Service: ");
date = s.nextLine();
System.out.println("Enter the cost of Service: ");
amount = s.nextDouble();
}
public void showData() {
System.out.printf("Customer name: %s The date is: %s, the Amount owed is: %.2f\n",name, date, amount);
}
There's no field amount in the class Customer.
There are several issues, but you should
// Use one loop...
for(int i=0; i < cnt; i++){
if(cust[i]!= null) { // <-- check for null.
cust[i].showData();
/* or
if (cust instanceof Service) {
total += ((Service)cust[i]).amount; // <-- assuming a public amount
// field in Service. This is not a good
// practice, but your question is difficult to
// answer.
}
*/
total += cust[i].getAmount(); // <-- a method.
}
}
That is add a getAmount to your interface if you want to get the amount (or, to make this code work - change the access modifier and add a public field named amount to Customer and remove the shadowing fields in your subclasses).
Or, you can learn about Collections (which I strongly recommend you do anyway) - and actually use the correct storage method - perhaps ArrayList.
This is one solution that I could come up with, where we add a getAmount method to the interface:
import java.util.Scanner;
public class home {
/**
* #param args
*/
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
final int MAX = 2;
Customer [] cust = new Customer[MAX];
int choice = 0;
int cnt;
double total = 0;
for(cnt=0; cnt < MAX && (choice == 1 || choice ==2 || choice == 0); cnt++){
System.out.println("For a Service customer type 1, for a Purchaser type 2, to terminate the program press 9");
choice = s.nextInt();
switch (choice){
case 1:
cust [cnt] = new Service();
break;
case 2:
cust [cnt] = new Purchaser();
break;
default:
break;
}
}
for(int i=0; i < cnt; i++){
if(cust[i]!= null)
cust[i].showData();
total = cust[i].getAmount() + total;
}
s.close();
}
}
abstract class Customer implements Functions {
protected String name;
}
import java.util.Scanner;
class Service extends Customer {
protected String date;
protected double amount;
public Service () {
getData();
}
public void getData() {
Scanner s = new Scanner(System.in);
System.out.println("Enter the name of the customer");
name = s.nextLine();
System.out.println("Enter date of Service: ");
date = s.nextLine();
System.out.println("Enter the cost of Service: ");
amount = s.nextDouble();
}
public double getAmount(){
return this.amount;
}
public void showData() {
System.out.printf("Customer name: %s The date is: %s, the Amount owed is: %.2f\n",name, date, amount);
}
}
import java.util.Scanner;
class Purchaser extends Customer {
protected double payment;
public Purchaser(){
getData();
}
public double getAmount(){
return this.payment;
}
public void getData() {
Scanner s = new Scanner(System.in);
System.out.println("Enter the name of the customer");
name = s.nextLine();
System.out.println("Enter payment amount: ");
payment = s.nextDouble();
}
public void showData() {
System.out.printf("Customer name: %s Payment amount is: %.2f\n",name,payment);
}
}
interface Functions {
public void getData();
public void showData();
public double getAmount();
}
I am trying to make a simple JAVA program that will help a user select a car of his choice.
public class CarSelector {
static CarSelector start = new CarSelector();
public String BodyType(String a){
String hatchBack, SUV, MUV, compactSedan, sedan, saloon, miniVan, convertible, hybrid, coupe;
if(a.equalsIgnoreCase("a")){
hatchBack = "polo";
System.out.println("We recommend: " +hatchBack);
}
String b = "";
if(a.equalsIgnoreCase("b")){
SUV = "Fortuner";
System.out.println("We recommend: " +SUV);
}
if(a.equalsIgnoreCase("c")){
compactSedan = "Amaze";
System.out.println("We recommend: " +compactSedan);
}
if(a.equalsIgnoreCase("d")){
sedan = "Vento";
System.out.println("We recommend: " +sedan);
}
if(a.equalsIgnoreCase("e")){
saloon = "Corolla";
System.out.println("We recommend: " +saloon);
}
if(a.equalsIgnoreCase("f")){
MUV = "Innova";
System.out.println("We recommend: " +MUV);
}
else{
System.out.println("Incorrect choice.");
System.out.println(a);
//start.BodyType(a);
return null;
}
System.out.println("We recommend: " +a);
return null ;
}
public int PriceRange(){
int price5 = 5;
int price10 = 10;
int price15 = 15;
int price20 = 20;
int price25 = 25;
int price30 = 30;
return 0 ;
}
public String SegmentBest(){
//string type of the best cars within price range
return null;
}
public int OnRoadPrice(){
//return int of on road price
return 0;
}
public String Manufacturer(){
//all manufacturers with their models available
String Toyota, Volkswagen, Honda;
String i1= "Toyota";
String i2= "Volkswagen";
String i3= "Honda";
return null;
}
public int SeatingCapacity(){
//return integer seating capacity
return 0;
}
public String ReviewLink(){
return null;
}
public String LatestReleases(){
return null;
}
public String FuelType(){
return null;
}
public static void main (String[] args){
Scanner input = new Scanner(System.in);
String option;
System.out.println("Welcome to car selector: ");
System.out.println("Choose according to: ");
System.out.println("A:Body Type");
System.out.println("B: Manufacturer");
System.out.println("C: Price Range");
option = input.nextLine();
if( option.equalsIgnoreCase("a")){
System.out.println("A: Hatchback");
System.out.println("B: SUV");
System.out.println("C: MUV");
System.out.println("D: Sedan");
System.out.println("E: Saloon");
System.out.println("F: Compact Sedan");
String optionA = input.nextLine();
start.BodyType(optionA);
}
}
}
The code is simple. A walkthrough: The main class will prompt the user to make a choice of how he wants to choose a car. Given option "A" as a choice will run the first method. Here are my queries
Within the BodyType method, I would like to run the set of IF statements again if the user enters anything other than a,b,c,d,e,f
How can I hand the control back to the main class (run a specific code from MAIN method) and also start a method from another method (from BodyType to PriceRange). I hope I was clear. Thanks, Cheers!
you can play it now...
import java.util.Scanner;
public class CarSelector {
static CarSelector start = new CarSelector();
static String[] bodytypes = new String[]{"hatchBack", "SUV", "MUV", "compactSedan", "sedan",
"saloon", "miniVan", "convertible", "hybrid", "coupe"};
static String[] manufacturers = new String[]{"Toyota", "Volkswagen", "Honda"};
private String getBodyType(int bt) {
if(bt >= bodytypes.length){
System.err.println("Incorrect choice.");
return null;
}else{
System.out.println("We recommend: " + bodytypes[bt]);
return bodytypes[bt];
}
}
public static String getManufacturer(int mf) {
if(mf >= manufacturers.length){
System.err.println("Incorrect choice.");
return null;
}else{
System.out.println("We recommend: " + manufacturers[mf]);
return manufacturers[mf];
}
}
public static void main(String[] args) {
String bodyType = "";
String manufacturer = "";
Scanner input = new Scanner(System.in);
String option;
System.out.println("Welcome to car selector: ");
System.out.println("Choose according to: ");
pringSelectType();
option = input.nextLine();
while(!option.equalsIgnoreCase("o")){
if (option.equalsIgnoreCase("a")) {
for(int a = 0; a < bodytypes.length ; a++){
System.out.println(a+": "+ bodytypes[a]);
}
option = input.nextLine();
bodyType = start.getBodyType(Integer.parseInt(option));
pringSelectType();
option = input.nextLine();
}else if (option.equalsIgnoreCase("b")) {
for(int a = 0; a < manufacturers.length ; a++){
System.out.println(a+": "+ manufacturers[a]);
}
option = input.nextLine();
manufacturer = getManufacturer(Integer.parseInt(option));
pringSelectType();
option = input.nextLine();
}else{
option = input.nextLine();
System.err.println(("input a right choice"));
pringSelectType();
option = input.nextLine();
}
}
System.out.println("");
System.out.println("it's your choice below: ");
System.out.println("bodyType : "+ bodyType);
System.out.println("manufacturer : "+ manufacturer);
}
private static void pringSelectType() {
System.out.println("A:Body Type");
System.out.println("B: Manufacturer");
System.out.println("C: Price Range");
}
}
i delete some unused method,and change some code.
i don't make any note,cause i think it's easy enough..
if u have some problem,comment it,i will see.
PS:when u want to over the select system,input o.it will be done.
I have a question with the display array method. I can't figure how to make it to format this:
Credit Card # 4:
8908 9014 8812 1331
What I need to do is for each array element call the display method and pass the index of the array in a string for the label, I just cant figure out how to do this, I tried this but it is wrong:
System.out.println(display("Credit Card # %d", cred1[i]));
Can anyone please suggest a way to do this?
package homework4;
import java.util.Scanner;
public class Prog4 {
static Scanner scanner = new Scanner(System.in);
public static void main(String[] args)
{ CreditCardNumber[] cred1;
CreditCardNumber cred2 = getInput();
Display("The complete number from your input:", cred2);
cred1 = getInputArray();
DisplayArray(cred1);
TryAnother();
}
public static CreditCardNumber getInput() {
String ID;
String accNum;
CreditCardNumber tempCred;
System.out.printf("Please enter issuer ID:");
ID = scanner.next();
System.out.printf("Please enter account number:");
accNum = scanner.next();
tempCred = new CreditCardNumber(ID, accNum);
return tempCred;
}
public static void Display(String ch, CreditCardNumber cred2)
{
System.out.println(ch);
System.out.println(cred2.toString().replaceAll(".{4}", "$0 "));
}
public static CreditCardNumber[] getInputArray()
{
CreditCardNumber[] tempArray;
String tempID;
int size;
System.out.printf("Please enter size of the aray:");
size = scanner.nextInt();
if(size < 1)
{
size = 1;
}
tempArray = new CreditCardNumber[size];
System.out.printf("Please enter issuer ID:");
tempID = scanner.next();
System.out.print(tempArray.length);
for(int i = 0; i < tempArray.length; i++)
{
tempArray[i] = new CreditCardNumber();
tempArray[i].CreateCred(tempID);
}
return tempArray;
}
public static void DisplayArray(CreditCardNumber[] cred1)
{
for(int i = 0; i< cred1.length; i++)
{
System.out.println(display("Credit Card # %d", cred1[i]));
}
}
public static boolean TryAnother()
{
String s;
System.out.printf("Get more credit card numbers? (n for no):");
s = scanner.next();
if(s.charAt(0) != 'N' && s.charAt(0) != 'n')
{
return true;
}
return false;
}
}
sounds like all you need is a new line character. For example.
System.out.println("Credit Card # " + cred1[i] + "\n" + cred2.toString());
The new line character "\n" will drop the output onto it's own line.
Do this:
System.out.format("Credit Card # %d:\n%s", i, cred1[i].toString());