printing out data of array element in java - java

If I have an array of a class type (cars) and each car has been given a make and model
using set methods, how can I then print out the make and model of a particular element?
I need to print this out in a separate class
public class Car {
private String make;
private String model;
public void setMake (String str1) {
make = str1;
}
public void setModel (String str2) {
model = str2;
}

You need to add a toString() method to your class
public class Car {
private String make;
private String model;
public void setMake (String str1) {
make = str1;
}
public void setModel (String str2) {
model = str2;
}
#Override
public String toString() {
return "Make :"+ make + " Model :" + model;
}
}
Just printing a car
You can then use this as follows
public static void main(String[] args){
Car car=new Car();
car.setMake("Audi");
car.setModel("ModelName");
System.out.println(car);
}
Printing all of an array
Equally if this exists in an array of cars (I'm using the constructor I introduce in the notes for brevity)
public static void main(String[] args){
Car[] cars=new Car[3];
cars[0]=new Car("Audi","ModelName");
cars[1]=new Car("BMW","ModelName");
cars[2]=new Car("Honda","ModelName");
for(int i=0;i<cars.length;i++){
System.out.println(cars[i]);
}
}
Printing after user selects an index
public static void main(String[] args){
Car[] cars=new Car[3];
cars[0]=new Car("Audi","ModelName");
cars[1]=new Car("BMW","ModelName");
cars[2]=new Car("Honda","ModelName");
Scanner scan=new Scanner(System.in);
System.out.println("Select index to print, should be between 0 and " + (cars.length-1));
//checks that user actually inputs an integer,
//checking its in range is left as an excercise
while (scan.hasNextInt()==false){
scan.next(); //consume bad input
System.out.println("Select index to print, should be between 0 and " + (cars.length-1));
}
int index=scan.nextInt();
System.out.println(cars[index]);
}
Notes
It seems like the make and model are essential to the workings of the car class, consider changing your constructor to take them as arguments
public Car(String make, String model){
this.make=make;
this.model=model;
}
All this assumes you already have the element you wish to print

class Car{
String make ;
String model;
#Override
public String toString() {
return "make :"+ this.make + " model :" + this.model;
}
}
List<Car> list= new ArrayList<Car>();
Car c1=new Car();
Car c2=new Car();
Car c3=new Car();
Car c4=new Car();
list.add(c1);
list.add(c2);
list.add(c3);
list.add(c4);
for(Car car : list)
{
System.out.println(car);
}

public class Car {
private String make;
private String model;
public Car(String make, String model) {
this.make = make;
this.model = model;
}
public void setMake (String str1) {
make = str1;
}
public void setModel (String str2) {
model = str2;
}
public String getMake() {
return make;
}
public String getModel() {
return model;
}
}
public class PrintCars {
public static void main(String []args) {
Car cars[] = new Car[10];
// Assume you populate the array with Car objects here by code
cars[0] = new Car("make1", "model1");
for (Car carObj : cars) {
System.out.println(carObj.getmake());
System.out.println(carObj.getmodel());
}
}
}

Try this
private static String toString(sample[] carTypes)
{
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < carTypes.length; i++)
{
if (carTypes[i] != null)
{
stringBuilder.append(" Name : ");
stringBuilder.append(carTypes[i].name);
stringBuilder.append(",");
stringBuilder.append(" Model : ");
stringBuilder.append(carTypes[i].model);
stringBuilder.append(",");
}
}
return stringBuilder.toString().substring(0, stringBuilder.toString().length() - 1);
}
output :
Name : BMW, Model : Mark 3, Name : AUDI, Model : A-6, Name : BENZ, Model : BZ

Related

Sorting and Binary Search (Java)

I was asked to sort a car array by model type and then use Arrays.binarySearch to search for a Car with that Model field. The problem is when the search is conducted it doesn't find anything (even though the model is in there).
Below is my code and output:
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
public class CarApplication
{
public static void main (String[] args)
{
Scanner keyboard = new Scanner(System.in);
Car car1 = new Car("Toyota", "Corolla" , 1996);
Car car2 = new Car("Nissan", "Murano" , 2004);
Car car3 = new Car("Mazda" , "Miata", 1999);
Car car4 = new Car("Ford", "Mustang" , 2013);
Car car5 = new Car("Chevy", "Volt" , 2020);
Car car6 = new Car("Tesla", "Model X" , 2016);
Car [] myCars = {car1, car2, car3, car4, car5, car6};
Arrays.sort(myCars, new CompareByModel());
System.out.println("Sorting by Model only (Comparator)");
for (Car car:myCars)
System.out.println(car);
System.out.println("Enter the name of the car model you wish to purchase: ");
String model = keyboard.nextLine();
//binary search
Car key = new Car("", model, 0); // set the name field so we can look for a match in array
int location = Arrays.binarySearch(myCars, 0, myCars.length, key, new CompareByModel());
//print message
if (location < 0)
System.out.println("Sorry, please check back next week.");
else
{
System.out.println("We have a " + model + " in location" + myCars[location]);
}
}
}
//Comparator
class CompareByModel implements Comparator<Car>
{
public int compare(Car c1, Car c2) {
int makeResult = c1.getCarMake().compareTo(c2.getCarMake());
int modelResult = c1.getCarModel().compareTo(c2.getCarModel());
return (modelResult == 0) ? makeResult: modelResult;
}
}
Output:
Enter the name of the car model you wish to purchase:
Volt
Sorry, please check back next week.
When you sort, you sort by the make and model, which is cool. But when you try and search, you set the make to "", so the result of comparing the entities won't work correctly.
You could modify the sort Comparator so as to ignore makes with "" when comparing them (so only using models) or supply the make as part of your search or create a seperate "search" Comparator, for example
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
Scanner keyboard = new Scanner(System.in);
Car car1 = new Car("Toyota", "Corolla", 1996);
Car car2 = new Car("Nissan", "Murano", 2004);
Car car3 = new Car("Mazda", "Miata", 1999);
Car car4 = new Car("Ford", "Mustang", 2013);
Car car5 = new Car("Chevy", "Volt", 2020);
Car car6 = new Car("Tesla", "Model X", 2016);
Car[] myCars = {car1, car2, car3, car4, car5, car6};
Arrays.sort(myCars, new SortComparator());
System.out.println(Arrays.toString(myCars));
String model = "Murano";
int result = Arrays.binarySearch(myCars, 0, myCars.length, new Car("", model, 0), new ModelComparator());
System.out.println(result);
int location = Arrays.binarySearch(myCars, 0, myCars.length, new Car("", model, 0), new SortComparator());
System.out.println(location);
}
public class Car {
private String make;
private String model;
private int year;
public Car(String make, String model, int year) {
this.make = make;
this.model = model;
this.year = year;
}
public String getMake() {
return make;
}
public String getModel() {
return model;
}
public int getYear() {
return year;
}
#Override
public String toString() {
return getMake() + " " + getModel() + " # " + getYear();
}
}
public static class SortComparator implements Comparator<Car> {
public int compare(Car c1, Car c2) {
int makeResult = c1.getMake().compareTo(c2.getMake());
int modelResult = c1.getModel().compareTo(c2.getModel());
return (modelResult == 0) ? makeResult : modelResult;
}
}
public static class ModelComparator implements Comparator<Car> {
public int compare(Car c1, Car c2) {
return c1.getModel().compareTo(c2.getModel());
}
}
}

how to get input for an array of class in java?

I am new in java and I trying to get information
for five students and save them into an array of classes. how can I do this?
I want to use class person for five students whit different informations
import java.io.IOException;
import java.util.*;
public class exam
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
// I want to get and save information in this array
person[] f = new student[5];
}
}
class person defined for get name and family name.
import java.util.*;
public abstract class person {
Scanner scr = new Scanner(System.in);
private String name , fname;
public void SetName() {
System.out.println("enter name and familyNAme :");
name = scr.next();
}
public String getname() {
return name;
}
public void setfname () {
System.out.println("enter familyname:");
fname = scr.next();
}
public String getfname() {
return fname;
}
}
class student that inherits from the class person for get studentID and student Scores .
import java.util.*;
class student extends person {
float[] p = new float[5];
int id , sum ;
float min;
public void inputs() {
System.out.println("enter the id :");
id = scr.nextInt();
}
public void sumation() {
System.out.println("enter points of student:");
sum= 0;
for(int i = 0 ; i<5 ; i++){
p[i]=scr.nextFloat();
sum+=p[i];
}
}
public void miangin() {
min = (float)sum/4;
}
}
So first things first, when creating Java objects, refrain from getting input inside the object so that if you decide to change the way you get input (e.g. transition from command line to GUI) you don't need to modify the Java object.
Second, getters and setters should only get or set. This would save some confusion when debugging since we don't have to check these methods/functions.
So here's the person object:
public abstract class Person {
protected String name, fname;
public Person (String name, String fname) {
this.name = name;
this.fname = fname;
}
public void setName (String name) {
this.name = name;
}
public String getName () {
return name;
}
public void setFname (String fname) {
this.fname = fname;
}
public String getFname () {
return fname;
}
}
And here's the student object (tip: you can make as much constructors as you want to make object creation easier for you):
public class Student extends Person {
private float[] p;
private int id;
public Student (String name, String fname) {
this (name, fname, -1, null);
}
public Student (String name, String fname, int id, float[] p) {
super (name, fname);
this.id = id;
this.p = p;
}
public void setP (float[] p) {
this.p = p;
}
public float[] getP () {
return p;
}
public void setId (int id) {
this.id = id;
}
public int getId () {
return id;
}
public float summation () {
float sum = 0;
for (int i = 0; i < p.length; i++)
sum += p[i];
return sum;
}
public float miangin () {
return summation () / 4.0f;
}
#Override
public String toString () {
return new StringBuilder ()
.append ("Name: ").append (name)
.append (" Family name: ").append (fname)
.append (" Id: ").append (id)
.append (" min: ").append (miangin ())
.toString ();
}
}
And lastly, wherever your main method is, that is where you should get input from. Take note that when you make an array, each index is initialized to null so you still need to instantiate each array index before using. I made a sample below but you can modify it depending on what you need.
import java.util.*;
public class Exam {
Scanner sc;
Person[] people;
Exam () {
sc = new Scanner (System.in);
people = new Person[5];
}
public void getInput () {
for (int i = 0; i < people.length; i++) {
System.out.print ("Enter name: ");
String name = sc.nextLine ();
System.out.print ("Enter family name: ");
String fname = sc.nextLine ();
System.out.print ("Enter id: ");
int id = sc.nextInt (); sc.nextLine ();
System.out.println ("Enter points: ");
float[] points = new float[5];
for (int j = 0; j < points.length; j++) {
System.out.printf ("[%d] ", j + 1);
points[j] = sc.nextFloat (); sc.nextLine ();
}
people[i] = new Student (name, fname, id, points);
}
}
public void printInput () {
for (Person p: people)
System.out.println (p);
}
public void run () {
getInput ();
printInput ();
}
public static void main (String[] args) {
new Exam ().run ();
}
}
Just one last tip, if you ever need dynamic arrays in Java, check out ArrayList.
You can add a class attribute, and then add class information for each student, or you can add a class class, define an array of students in the class class, and add an add student attribute, and you can add students to that class.
First of all, please write class names with capital letter (Student, Exam <...>).
Exam class:
import java.util.Scanner;
public class Exam {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Student[] students = new Student[]{
new Student(),
new Student(),
new Student(),
new Student(),
new Student()
};
for (int i = 0; i < 5; i++) {
students[i].setFirstName();
students[i].setLastName();
students[i].setId();
}
}
}
Person class:
import java.util.Scanner;
public class Person {
String firstName, lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName() {
System.out.println("Type firstName: ");
this.firstName = new Scanner(System.in).next();
}
public String getLastName() {
return lastName;
}
public void setLastName() {
System.out.println("Type lastName: ");
this.lastName = new Scanner(System.in).next();
}
}
Student class:
import java.util.Scanner;
public class Student extends Person{
int id;
public int getId() {
return id;
}
public void setId() {
//Converting String line into Integer by Integer.parseInt(String s)
System.out.println("Type id: ");
this.id = Integer.parseInt(new Scanner(System.in).next());
}
}

Objects as arguments

I try to:
Create a Car object in the Main.
Send the object as an argument to the carOwners class.
Print the entire carOwners data from main.
Name and Address will be printed, but not the Car.
What is wrong with my code?
public class TestProgram {
public static void main(String [] args){
Car Saab = createCar();
carOwners guy = createCarOwners (Saab);
printAll(guy);
}
public static Car createCar (){
//user input a, b, c, d
Car temporary = new Car (a, b, c, d);
return temporary;
}
public static carOwners createCarOwners (Car x){
//user input a, b
Car c = x;
carOwners temporary = new carOwners (a, b, c);
return temporary;
}
public static void printAll (carOwners x){
x.printCarData();
x.printNameAddress();
}
}
public class Car {
private String model;
private String Year;
private String licensePlate;
private String color;
public Car (String x, int y, String z, String q){
model = x;
Year = y;
licensePlate = z;
color = q;
}
}
public class carOwners {
private String name;
private String address;
private Car TheCar;
public carOwners (String n, String a, Car b){
name = n;
address = a;
TheCar = b;
}
public void printNameAddress(){
System.out.println();
System.out.println(name);
System.out.println(address);
}
public void printCarData(){
System.out.println(TheCar);
}
}
override toString(), so you can custom the output format of Car
public String toString(){
return "Model :" + this.model + ",Year :" + year;
}
Your Problem is here:
public void printCarData(){
System.out.println(TheCar);
}
You want to print an Object. That doens't work because Java uses the toString-Method for that. If you want to do it like that you have to override the toString()-Method of your car class like that:
public String toString()
{
return "CarModel: " + this.model + ", Production Year: " + year;
}

Adding objects to ArrayList from another class

I'm very new to programming and currently trying to write a car showroom application. I've got a vehicle class, showroom class and I'm trying to use a showroom driver for the input.
I'm having problems adding vehicle objects to my arraylist. Could someone point me in the correct direction.
My code:
public class Vehicle {
private String manufacturer;
private String model;
private String custName;
private String vin;
private String dateMan;
private String dateSold;
private Boolean sold;
private char tax;
private double cost;
public Vehicle(String a, String b, String c, String d) {
manufacturer = a;
model = b;
vin = c;
dateMan = d;
}
public String toString() {
String s = "Manufacturer: " + manufacturer + " Model: "
+ model + " vin: " + vin + "Date Manufactured:" + dateMan
+ "Cost: " + cost;
return s;
}
public void buyVehicle(String a, String b) { //buy method for the vehicle
a = dateSold;
b = custName;
sold = true;
}
public String getManufacturer() {
return manufacturer;
}
public String getModel() {
return model;
}
public String getCustName() {
return custName;
}
public String getVin() {
return vin;
}
public String getDateMan() {
return dateMan;
}
public String getDateSold() {
return dateSold;
}
public Boolean getSold() {
return sold;
}
public char getTax() {
return tax;
}
public double getCost() {
return cost;
}
}
.
import java.util.ArrayList;
public class Showroom {
private ArrayList<Showroom> theVehicles;
public Showroom() {
theVehicles = new ArrayList<Showroom>();
}
public boolean addVehicle(Showroom newVehicle) {
theVehicles.add(newVehicle);
return true;
}
}
.
import java.util.*;
public class ShowroomDriver {
public static void main(String[] args) {
Vehicle v1 = new Vehicle("renault", "clio", "12", "290890");
Showroom.addVehicle(v1);
}
}
Basically, I'm confused to how I add vehicle objects to the arraylist within the showroom class. If anyone could point me in the right direction I would really appreciate it.
Thanks in advance.
You have to instantiate the class Showroom to use its properties and methods
The collection theVehicles is of Vehicle not Showroom.
package cars;
import java.util.ArrayList;
import java.util.List;
public class Showroom {
private final List<Vehicle> theVehicles = new ArrayList<>();
public boolean addVehicle( Vehicle newVehicle ) {
theVehicles.add( newVehicle );
return true;
}
public static void main( String[] args ) {
final Showroom showroom = new Showroom();
final Vehicle v1 = new Vehicle( "renault", "clio", "12", "290890" );
showroom.addVehicle( v1 );
}
}
in Vehicle class, a mistake around '=' operator, I suppose you want to memorize the sold value and the customer name:
public void buyVehicle( String a, String b ) { // buy method for the vehicle
dateSold = a;
custName = b;
sold = true;
}
I Think this
private ArrayList <Showroom> theVehicles;
Shoulde be this
private ArrayList <Vehicle> theVehicles;
theVehicles = new ArrayList <Vehicle> ();
And this
public boolean addVehicle( Showroom newVehicle )
Should be
public boolean addVehicle( Vehicle newVehicle )
Don't you want an ArrayList of Vehicles and not ShowRooms?
Your problem is that you declared an ArrayList of ShowRoom objects, but what you want is an ArrayList of Vehicle objects.
private ArrayList<Vehicle> theVehicles;
public boolean addVehicle(Vehicle v) {
theVehicles.add(v);
return true;
}

java calling methods and objects

my dear Friends I am new to this java ..so plz help me thank u in advance.. Now i am workin on an examples to understand the concepts of java's objects, classes method in detail.
With all the knowledge i have i tried this example. . but i am unable to accomplish the task.. . Can any one plz give me suggestions of corrected coding..
I also wanted to know Which s the best site for learning JAVA (like MSDN for .NET )
Thank u in advance
Question:To Create Vehicle having following attributes: Vehicle No., Model, Manufacturer and Color. Create truck which has the following additional attributes: loading capacity( 100 tons…).Add a behavior to change the color and loading capacity. Display the updated truck details.
Codings:
import java.io.*;
class Vehicle
{
String VehicleNo;
String Model;
String Manufacturer;
String Color;
public void setNo(String VehicleNo)
{
this.VehicleNo=VehicleNo;
}
public String getNo()
{
return VehicleNo;
}
public void setModel(String Model)
{
this.Model=Model;
}
public String getModel()
{
return Model;
}
public void setManufacturer(String Manufacturer)
{
this.Manufacturer=Manufacturer;
}
public String getManufacturer()
{
return Manufacturer;
}
public void setColor(String Color)
{
this.Color=Color;
}
public String getColor(String s)
{
return s;
}
}
class Truck extends Vehicle
{
double LoadingCapacity;
public void setLoad(double LoadingCapacity)
{
this.LoadingCapacity=LoadingCapacity;
}
public double getLoad(double ld)
{
return ld;
}
}
public class VehicleInfo {
/**
* #param args
* #throws IOException
*/
public static void mainEntry2() throws IOException
{
//Truck D=new Truck();
//BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Color: ");
String col=br.readLine();
D.setColor(col);
System.out.print("Enter Loading Capacity: Maximum 100tons");
int load=Integer.parseInt(br.readLine());
D.setLoad(load);
}
public static void main(String[] args) throws IOException
{
int loop_option=0;
public Truck D=new Truck();
public BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Vehicle No: ");
String no=br.readLine();
D.setNo(no);
System.out.print("Model: ");
String model=br.readLine();
D.setModel(model);
System.out.print("Manufacturer: ");
String man=br.readLine();
D.setManufacturer(man);
mainEntry2();
do
{
System.out.println("");
System.out.println("----Vehicle Information----");
System.out.println();
System.out.println("Vehicle No: "+D.getNo());
System.out.println("Model: "+D.getModel());
System.out.println("Manufacturer: "+D.getManufacturer());
System.out.println("Color: "+D.getColor(col));
System.out.println("Loading Capacity: "+D.getLoad(load));
System.out.println("");
System.out.println(" if U want to update color and loading capacity press 1 and to exit press 2 ..");
loop_option=Integer.parseInt(br.readLine());
if(loop_option==1)
{
mainEntry2();
}
}while(loop_option==1);
}
}
Here are some general remarks. Hope they help:
getters should only return value, they do not have parameters (otherwise they are not getters).
if you're encapsulating fields, make them private
use descriptive variable names (eg. truck instead of D)
use descriptive method names (mainEntry2() tells absolutely nothing)
if you're parsing integer from user input, handle parsing exceptions (like NumberFormatException)
For instance, your program may be re-written like here:
import java.io.*;
class Vehicle {
private String vehicleNo;
private String model;
private String manufacturer;
private String color;
public void setNo(String vehicleNo) {
this.vehicleNo = vehicleNo;
}
public String getNo() {
return vehicleNo;
}
public void setModel(String model) {
this.model = model;
}
public String getModel() {
return model;
}
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
public String getManufacturer() {
return manufacturer;
}
public void setColor(String color)
{
this.color = color;
}
public String getColor() {
return color;
}
}
class Truck extends Vehicle
{
private double loadingCapacity;
public void setLoad(double loadingCapacity) {
this.loadingCapacity = loadingCapacity;
}
public double getLoad() {
return this.loadingCapacity;
}
}
public class VehicleInfo {
private static void updateColorAndCapacity(BufferedReader br, Truck truck)
throws IOException
{
System.out.print("Color: ");
String col = br.readLine();
truck.setColor(col);
while (true)
{
System.out.print("Enter Loading Capacity (maximum 100tons):");
String value = br.readLine();
value = value.trim();
try {
int load = Integer.parseInt(value);
truck.setLoad(load);
return;
} catch (NumberFormatException e) {
/// do it once again
continue;
}
}
}
public static void main(String[] args)
throws IOException {
Truck truck = new Truck();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Vehicle No: ");
String no = br.readLine();
truck.setNo(no);
System.out.print("Model: ");
String model = br.readLine();
truck.setModel(model);
System.out.print("Manufacturer: ");
String man = br.readLine();
truck.setManufacturer(man);
updateColorAndCapacity(br, truck);
int loop_option = 0;
do {
System.out.println();
System.out.println("----Vehicle Information----");
System.out.println();
System.out.println("Vehicle No: " + truck.getNo());
System.out.println("Model: " + truck.getModel());
System.out.println("Manufacturer: " + truck.getManufacturer());
System.out.println("Color: " + truck.getColor());
System.out.println("Loading Capacity: " + truck.getLoad());
System.out.println();
System.out.println(" if U want to update color and loading capacity press 1 and to exit press 2 ..");
loop_option = Integer.parseInt(br.readLine());
if (loop_option == 1) {
updateColorAndCapacity(br, truck);
}
} while (loop_option == 1);
}
}
You should start here for learning Java: http://download.oracle.com/javase/tutorial/

Categories