How to grab value from array list? - java

A briefing of the program: This program keeps track of people who have airline membership cards and how many points they collect each week. (week1, 2, 3, 4) The information is stored in the array, which then when needed, can be outputted by pressing the "listButton".
I know how to grab a value from the array and simply output it, but unsure how to do so with a loop. See problem area under "totalPointsButton"
public class AirlineCardsView extends FrameView {
class airline {
String lastName, firstName;
int week1, week2, week3, week4;
airline (int _week1, int _week2, int _week3, int _week4, String _lastName, String _firstName) {
week1 = _week1;
week2 = _week2;
week3 = _week3;
week4 = _week4;
lastName = _lastName;
firstName = _firstName;
}
}
/** Define the ArrayList */
ArrayList <airline> members = new ArrayList <airline>();
public AirlineCardsView(SingleFrameApplication app) {
//GUI stuff
}// </editor-fold>
private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {
String lastName, firstName;
int week1, week2, week3, week4;
week1 = Integer.parseInt(weekOneField.getText());
week2 = Integer.parseInt(weekTwoField.getText());
week3 = Integer.parseInt(weekThreeField.getText());
week4 = Integer.parseInt(weekFourField.getText());
lastName = lastNameField.getText();
firstName = firstNameField.getText();
airline c = new airline(week1, week2, week3, week4, firstName, lastName);
members.add(c);
}
private void listButtonActionPerformed(java.awt.event.ActionEvent evt) {
String temp = "";
for (int x=0; x<=members.size()-1; x++) {
temp = temp + members.get(x).firstName + " "
+ members.get(x).lastName + ": "
+ members.get(x).week1 + " "
+ members.get(x).week2 + " "
+ members.get(x).week3 + " "
+ members.get(x).week4 + "\n";
}
memberListTArea.setText(temp);
}
Here I'm unsure how to initialize the values week1, week2, week3, week4 (for int totalPoints) with the same values stored in the array for the corresponding member.
private void totalPointsButtonActionPerformed(java.awt.event.ActionEvent evt) {
int week1, week2, week3, week4;
String lastName, firstName;
String points = "";
for (int j = 0; j < members.size()-1; j++) {
//this line checks the inputted name to see if it matches any stored in array.
if (members.get(j).lastName.equals(lastNameField.getText())) {
int totalPoints = week1 + week2 + week3 + week4; //then adds total points
}
}
}

I hope I understood the question correctly....
firstly, this line has problem:
for (int j = 0; j < members.size()-1; j++) {
you should remove the -1 or use <=. otherwise you won't reach the last element.
the if (members.get(j).lastName.equals(lastNameField.getText())) may throw NPE. (members.get(j).lastName could be null) also the variables defined in this method (week1-4, and the lastname, firstname) don't make much sense.
you declare the int totalPoints in if block, which means, it won't be seen outside the if block. It is not big deal, if all your logic is in if block.
you could try:
Airline al = null;
int totalPoints;
for (int j = 0; j < members.size(); j++) {
al = members.get(j);
if (al.lastName.equals(lastNameField.getText())) {
totalPoints = al.week1 + al.week2 + al.week3 + al.week4;
}
}
even better:
int totalPoints;
for (Airline al:members) {
if (al.lastName.equals(lastNameField.getText())) {
totalPoints = al.week1 + al.week2 + al.week3 + al.week4;
}
}
to make the codes look better, you could consider add getter/setters in your Airline class. also add a method, int getTotalPoints() return the sum of 4 weeks. Then you don't have to sum it outside the class.

You should add get and set methods to your airline class. So when you store an object of airline in the arraylist you can get their values by using "members.get(j).week1, members.get(j).week2, etc"
For example create your airline class like this.
public class airline {
String lastName;
String firstName;
int week1;
int week2;
int week3;
int week4;
public airline (int week1, int week2, int week3, int week4, String lastName, String firstName) {
week1 = this.week1;
week2 = this.week2;
week3 = this.week3;
week4 = this.week4;
lastName = this.lastName;
firstName = this.firstName;
}
public int getWeek1(){
return week1;
}
public void setWeek1(int newWeek1){
week1 = newWeek1;
}
public int getWeek2(){
return week2;
}
public void setWeek2(int newWeek2){
week2 = newWeek2;
}
public int getWeek3(){
return week3;
}
public void setWeek3(int newWeek3){
week3 = newWeek3;
}
public int getWeek4(){
return week4;
}
public void setWeek4(int newWeek4){
week4 = newWeek4;
}
public String getFirstName(){
return firstName;
}
public void setFirstName(String newFirstName){
firstName = newFirstName;
}
public String getLastName(){
return lastName;
}
public void setLastName(String newLastName){
lastName = newLastName;
}
public String toString(){
return getWeek1() + " " + getWeek2() + " " + getWeek3() + " " + getWeek4() + getFirstName() + " " + getLastName();
}
}

Related

Java not outputting or requesting keyboard input

I am having trouble getting my java code to properly output the required results. Not to mention that my System.out.Println isn't prompting for input. All my code is good with no errors. However it just doesn't seem to output anything or request an input.
//Author Adam Duffy
package test1;
import java.util.Scanner;
public class Employee {
public static void main(String [ ] args){}
public String DEF_EMP_NUM = "NO_EMP_NUM";
public double DEF_RATE_PER_HOUR = 20.0;
public double DEF_OVER_TIME_RATE = 40.0;
public double DEF_RATE_HOURS_PER_WEEK = 1.5;
private String empNum;
private double ratePerHour;
private double baseHrsPerWeek;
private double overTimeRate;
// no arg constructor setting width and length to default of 1
public Employee() {
empNum = DEF_EMP_NUM;
ratePerHour = DEF_RATE_PER_HOUR;
baseHrsPerWeek = DEF_RATE_HOURS_PER_WEEK;
overTimeRate = DEF_OVER_TIME_RATE;
}
// all arg constructor
public Employee(String empNum, float ratePerHour, float baseHrsPerWeek, int overTimeRate) {
this.empNum = empNum;
this.ratePerHour = ratePerHour;
this.baseHrsPerWeek = baseHrsPerWeek;
this.overTimeRate = overTimeRate;
}
//setters
public void setempNum(String empNum) {
this.empNum = empNum;
}
public String getempNum() {
return this.empNum;
}
//methods
public double getratePerHour() {
return ratePerHour;
}
public void setratePerHour(float ratePerHour) {
this.ratePerHour = ratePerHour;
}
public double getoverTimeRate() {
return overTimeRate;
}
public int setoverTimeRate(int overTimeRate) {
this.overTimeRate = overTimeRate;
return overTimeRate;
}
public double getbaseHrsPerWeek() {
return baseHrsPerWeek;
}
public void setbaseHrsPerWeek(float baseHrsPerWeek) {
this.baseHrsPerWeek = baseHrsPerWeek;
}
#Override
public String toString() {
return super.toString()
+ "\n["
+ "\nbaseHrsPerWeek = " + baseHrsPerWeek
+ "\noverTimeRate = " + overTimeRate
+ "\nratePerHour = " + ratePerHour
+ "\nempNum = " + empNum
+ "\n]";
}
public double calcWeeksPay(int hours) {
return this.ratePerHour * this.baseHrsPerWeek;
/*#param hours
#return
*/
}
{
Scanner scan = new Scanner(System.in);
int myNum[] = new int[5];
int i;
int sum = 0;
for (i = 0; i < myNum.length; i++) {
System.out.print("Enter the number " + (i + 1) + " : ");
myNum[i] = scan.nextInt();
}
for (i = 0; i < myNum.length; i++) {
System.out.print("The number " + (i + 1) + " : ");
System.out.print(myNum[i] + "\n+");
for (int e = 1; e <= i; e++) {
sum = sum + e;
}
System.out.println(sum);
}
}
}
I just can't seem to get it to work. I'm sure I'm missing something obvious. If I could get some advice, I would be very appreciative.
Updated peice of code , which will accept and print the number on console.
public class Employee {
public static void main(String [ ] args){
Scanner scan = new Scanner(System.in);
int myNum[] = new int[5];
int i;
int sum = 0;
for (i = 0; i < myNum.length; i++) {
System.out.print("Enter the number " + (i + 1) + " : ");
myNum[i] = scan.nextInt();
}
for (i = 0; i < myNum.length; i++) {
System.out.print("The number " + (i + 1) + " : ");
System.out.print(myNum[i] + "\n+");
for (int e = 1; e <= i; e++) {
sum = sum + e;
}
System.out.println(sum);
}
}
public String DEF_EMP_NUM = "NO_EMP_NUM";
public double DEF_RATE_PER_HOUR = 20.0;
public double DEF_OVER_TIME_RATE = 40.0;
public double DEF_RATE_HOURS_PER_WEEK = 1.5;
private String empNum;
private double ratePerHour;
private double baseHrsPerWeek;
private double overTimeRate;
// no arg constructor setting width and length to default of 1
public Employee() {
empNum = DEF_EMP_NUM;
ratePerHour = DEF_RATE_PER_HOUR;
baseHrsPerWeek = DEF_RATE_HOURS_PER_WEEK;
overTimeRate = DEF_OVER_TIME_RATE;
}
// all arg constructor
public Employee(String empNum, float ratePerHour, float baseHrsPerWeek, int overTimeRate) {
this.empNum = empNum;
this.ratePerHour = ratePerHour;
this.baseHrsPerWeek = baseHrsPerWeek;
this.overTimeRate = overTimeRate;
}
//setters
public void setempNum(String empNum) {
this.empNum = empNum;
}
public String getempNum() {
return this.empNum;
}
//methods
public double getratePerHour() {
return ratePerHour;
}
public void setratePerHour(float ratePerHour) {
this.ratePerHour = ratePerHour;
}
public double getoverTimeRate() {
return overTimeRate;
}
public int setoverTimeRate(int overTimeRate) {
this.overTimeRate = overTimeRate;
return overTimeRate;
}
public double getbaseHrsPerWeek() {
return baseHrsPerWeek;
}
public void setbaseHrsPerWeek(float baseHrsPerWeek) {
this.baseHrsPerWeek = baseHrsPerWeek;
}
#Override
public String toString() {
return super.toString()
+ "\n["
+ "\nbaseHrsPerWeek = " + baseHrsPerWeek
+ "\noverTimeRate = " + overTimeRate
+ "\nratePerHour = " + ratePerHour
+ "\nempNum = " + empNum
+ "\n]";
}
public double calcWeeksPay(int hours) {
return this.ratePerHour * this.baseHrsPerWeek;
/*#param hours
#return
*/
}
}
Problem was that you were not having anything in the psvm method and below piece of code
Scanner scan = new Scanner(System.in);
int myNum[] = new int[5];
int i;
int sum = 0;
for (i = 0; i < myNum.length; i++) {
System.out.print("Enter the number " + (i + 1) + " : ");
myNum[i] = scan.nextInt();
}
for (i = 0; i < myNum.length; i++) {
System.out.print("The number " + (i + 1) + " : ");
System.out.print(myNum[i] + "\n+");
for (int e = 1; e <= i; e++) {
sum = sum + e;
}
System.out.println(sum);
}
Which takes the input and print it on console was not having any calling code. it was just a inside the block of code. i just moved it inside the main method and it worked.

toString an arraylist containing object

I have an array list of type car.
I have an overriding toString method which prints my car in the desired format.
I'm using the arraylist.get(index) method to print the cars.
I only have one for now it works, but I want it do print for all of the cars in the array list.
This is my code:
public class Garage {
private static int carsCapacity = 30;
ArrayList<Cars> myGarage;
public Garage() {
Scanner scanAmountOfCars = new Scanner(System.in);
System.out.println("Please limit the number of car the garage can contain.");
System.out.println("If greater than 50, limit will be 30.");
int validAmount = scanAmountOfCars.nextInt();
if (validAmount <= 50) {
carsCapacity = validAmount;
myGarage = new ArrayList<Cars>();
}
System.out.println(carsCapacity);
}
public void addCar() {
Cars car = new Cars(Cars.getID(), Cars.askCarID(), Cars.getPosition(), Attendant.askForAtt(), System.currentTimeMillis());
myGarage.add(car);
//System.out.println(car);
}
public static int getCarsCapacity() {
return carsCapacity;
}
#Override
public String toString() {
return "Garage [Car:" + myGarage.get(0).getPlateNum() + " ID:" + myGarage.get(0).getCarID() + " Position:" + Cars.getPosition() +
" Assigned to:" + Cars.getAssignedTo().getId() + "(" + Cars.getAssignedTo().getName()
+ ")" + " Parked at:" + Cars.convert(myGarage.get(0).getCurrTime()) + "]";
}
}
I also put the Cars class in case you need it:
public class Cars {
private String carID;
private String plateNum;
private static String position;
private static Attendant assignedTo;
private long currTime;
static String[] tempArray2 = new String[Garage.getCarsCapacity()];
public Cars(String carID, String plateNum, String position, Attendant assignedTo, long currTime) {
this.carID = carID;
this.plateNum = plateNum;
Cars.position = position;
Cars.assignedTo = assignedTo;
this.currTime = currTime;
}
private static void createCarsID() {
for (int x = 0; x < Garage.getCarsCapacity(); x++) {
tempArray2[x] = ("CR" + (x + 1));
}
}
public static String getID() {
createCarsID();
String tempID = null;
String tempPos = null;
for (int x = 0; x < tempArray2.length; x++) {
if (tempArray2[x] != null) {
tempID = tempArray2[x];
tempPos = tempArray2[x];
getPos(tempPos);
tempArray2[x] = null;
break;
}
}
return tempID;
}
public static void getPos(String IdToPos) {
String strPos = IdToPos.substring(2);
int pos = Integer.parseInt(strPos);
position = "GR" + pos;
}
public String getPlateNum() {
return plateNum;
}
public String getCarID() {
return carID;
}
public static String getPosition() {
return position;
}
public long getCurrTime() {
return currTime;
}
public static Attendant getAssignedTo() {
return assignedTo;
}
public static String askCarID() {
boolean valid = false;
System.out.println("Please enter your car's plate number.");
Scanner scanCarID = new Scanner(System.in);
String scannedCarID = scanCarID.nextLine();
while (!valid) {
if (scannedCarID.matches("^[A-Za-z][A-Za-z] [0-9][0-9][0-9]$")) {
valid = true;
System.out.println(scannedCarID);
} else {
System.out.println("Please enter a valid plate number. Ex: AF 378");
askCarID();
}
}
return scannedCarID.toUpperCase();
}
public static String convert(long miliSeconds) {
int hrs = (int) TimeUnit.MILLISECONDS.toHours(miliSeconds) % 24;
int min = (int) TimeUnit.MILLISECONDS.toMinutes(miliSeconds) % 60;
int sec = (int) TimeUnit.MILLISECONDS.toSeconds(miliSeconds) % 60;
return String.format("%02d:%02d:%02d", hrs, min, sec);
}
}
Your Garage should have the implementation of toString() which uses ArrayList#toString() implementation:
public String toString() {
return "Garage: " + myGarage.toString();
}
Also remember to implement toString() in Cars.java.
public String toString() {
return "[" + this.carID + " " +
this.plateNum + " " +
Cars.position + " " +
Cars.assignedTo.toString + " " +
String.valueOf(this.currTime) + "]"
}

Program will not print the statement

I have a program where i select an option to add ship, which prompts me to give an id e.g b 2. it then prompts me to enter a capacity. However, I am using a search method to prevent any repeat id's that I may enter a second time round. The program compiles, but my statement "Ship id is already in use" won't print out. Any ideas please?
Here is my code.
public int search(String id)
{
for(int index = 0; index < ships.length && ships[index] != null; ++index)
{
shipId = id;
if (ships[index].getId().equals(id))
{
return index;
}
}
//ship id not found so you can add ship
return -1;
}
public void addShip( )
{
System.out.println("Enter ship id >> ");
String id = kb.nextLine();
if(id.equals(search(id)))
{
System.out.println("Ship id already in use");
return;
}
else
{
//for(int i = 0; i < ships.length; ++i)
{
System.out.println("Enter ship capacity");
int capacity = kb.nextInt();
ships[shipCounter++] = new Ship(id, capacity);
}
}
}
Here is my ship class:
public class Ship
{
private String id;
private int capacity;
private int currentCrew; // index into the Crew array
// points to the next free space
// in the Crew array
private String status;
private Crew [ ] crew;
public Ship(String id, int capacity)
{
this.id = id;
this.capacity = capacity;
this.currentCrew = 0;
crew = new Crew[capacity];
}
public Ship(String id, int capacity, String status)
{
this.id = id;
this.capacity = capacity;
this.status = "available";
this.currentCrew = 0;
crew = new Crew[capacity];
}
public void setId(String newId)
{
id = newId;
}
public void setCapacity(int newCapacity)
{
capacity = newCapacity;
}
public void setStatus(String newStatus)
{
if(status.equals("available"))
{
newStatus = "on station";
status = newStatus;
}
else if(status.equals("on station"))
{
newStatus = "maintenance";
status = newStatus;
}
else if(status.equals("station") || status.equals("maintenance"))
{
newStatus = "available";
status = newStatus;
}
else
{
System.out.println("Invalid status");
}
}
public String getId()
{
return id;
}
public String getStatus()
{
return status;
}
public int getCapacity()
{
return capacity;
}
public int getCurrentCrew()
{
return currentCrew;
}
public void addCrew()
{
//if(currentCrew < capacity)
{
//System.out.println("Enter crew id >> ");
//String id = kb.nextLine();
}
}
public String toString()
{
String sdesc =
'\n'
+ "Ship"
+ '\n'
+ "["
+ '\n'
+ " "
+ "Id: " + id
+ " capacity: " + capacity
+ " current crew: " + currentCrew
+ " status: " + status
+ '\n'
+ "]";
return sdesc;
}
}
Did you noticed this line
if(id.equals(search(id)))
id is String type, but search return type is int.
if you see in String class equals method,
if (anObject instanceof String) {
}
return false;
so its simply give false always
so the simple solution is convert that int to String.
something like
if(id.equals(search(id+"")))
If you'd like to see if you already have a ship with the id, you should check that the index exists, which is what your search method returns.
if(search(id) > 0)
{
System.out.println("Ship id already in use");
return;
}

Search Array Error

I am having an issue using netbeans with this program. The program is used to search via an array from an imported text file and the text file has several columns and rows, pertaining to several characteristics of cars (i.e. License Plate Numbers). You need to create dialog boxes to search what your looking for, for each option. The problem is at the end of the code snippet starting with one.setPlate. All of the one.set(x) is being flagged, what could be the reason?
package vehiclesearch;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
import javax.swing.JOptionPane;
public class VehicleSearch {
private static String[] sliced;
public static void main
(String[] args) throws FileNotFoundException {String NameOfFile =
JOptionPane.showInputDialog("Where is the File Path to Import Located at?");
File textFile = new File((NameOfFile));
Scanner in = new Scanner (textFile);
//Imports the appropriate text file named "vehicles.txt"//
ArrayList <String> carsArrayList = new ArrayList <>();
while(in.hasNextLine()){
String line = in.nextLine();
carsArrayList.add(line);
}
in.close();
ArrayList<VehicleSearch> vehicleObs = new ArrayList<>();
for (int i= 0; i <carsArrayList.size(); i++){
String temp = carsArrayList.get(i);
VehicleSearch VehicleClass = new VehicleSearch ();
String[] sliced = temp.split("\\s+");
vehicleClass.setPlate(sliced[0]);
int a = Integer.parseInt(sliced[1]);
vehicleClass.setYear(a);
vehicleClass.setMfg(sliced[2]);
vehicleClass.setStyle(sliced[3]);
vehicleClass.setColor(sliced[4]);
vehicleObs.add(vehicleClass);
boolean stepTwo = true;
while(stepTwo) {
String search;
search = JOptionPane.showInputDialog("Please choose one of the following search options" + "1 Plate" + "\n" +"2 Year" + "3 Manufacturer" + "\n" + "4 Body Style"+ "\n"+ "5 Color");
int searchOption = Integer.parseInt(search);
String searchVal;
searchVal = JOptionPane.showInputDialog("Enter a value to search for" + "\n" + "All values must be exact in wording, please be careful when using Caps or check for Caps Lock");
searchDialogs(vehicleObs, searchOption, searchVal);
String c;
c = JOptionPane.showInputDialog("Type S to search | E to exit");
String b = "S";
if(c.equalsIgnoreCase(b)){
stepTwo = true;
}
else{
stepTwo= false;
}
}
}
}
public static String plateCheck(ArrayList list, String search){
ArrayList<String> as = new ArrayList<>();
for (int i = 0; i< list.size(); i++){
String temp = list.get(i).toString();
if(temp.contains(search)){
as.add(list.get(i).toString());
}
}
return alFormat(as);
}
public static String yearCheck(ArrayList list, String search){
ArrayList<String> as = new ArrayList<>();
for (int i = 0; i< list.size(); i++){
String temp = list.get(i).toString();
as.add(list.get(i).toString());
}
return alFormat(as);
}
public static String mfgCheck(ArrayList list, String search){
ArrayList<String> as = new ArrayList<>();
for (int i = 0; i< list.size(); i++){
String temp = list.get(i).toString();
as.add(list.get(i).toString());
}
return alFormat(as);
}
public static String StyleCheck(ArrayList list, String search){
ArrayList<String> as = new ArrayList<>();
for (int i = 0; i< list.size(); i++){
String temp = list.get(i).toString();
as.add(list.get(i).toString());
}
return alFormat(as);
}
public static String colorCheck(ArrayList list, String search){
ArrayList<String> as = new ArrayList<>();
for (int i = 0; i< list.size(); i++){
String temp = list.get(i).toString();
as.add(list.get(i).toString());
}
return alFormat(as);
}
public static void searchDialogs(ArrayList vehicleObs, int searchOption, String
searchVal){
if(searchOption == 1){
JOptionPane.showMessageDialog(null, "Your following search yielded the following
results" + "\n" + plateCheck(vehicleObs, searchVal));
}//Outputs data (Plate Numbers) from the text file imported
else if(searchOption == 2){
JOptionPane.showMessageDialog(null, "Your following search yielded the following
results" + "\n" + yearCheck(vehicleObs, searchVal));
}//Outputs data (Year) from the text file imported
else if(searchOption == 3){
JOptionPane.showMessageDialog(null, "Your following search yielded the following
results" + "\n" + mfgCheck(vehicleObs, searchVal));
}//Outputs data (Manufacturer) from the text file imported
else if(searchOption == 4){
JOptionPane.showMessageDialog(null, "Your following search yielded the following
results" + "\n" + styleCheck(vehicleObs, searchVal));
}//Outputs data (Style) from the text file imported
else if(searchOption == 5){
JOptionPane.showMessageDialog(null, "Your following search yielded the following
results" + "\n" + colorCheck(vehicleObs, searchVal));
}//Outputs data (Color) from the text file imported
else{
JOptionPane.showMessageDialog(null, "Sorry no results have been found");
}//will only output this message only if nothing is found,//
}
public static String alFormat(ArrayList too){
String tmpString;
String full = "";
for( Object aValue | too){
tmpString = aValue + "\n";
full = full + tmpString;
}
return null;
}
}
//Vehicle Class//
public class VehicleClass {
protected String plate;//car plate
protected int year;//car model year
protected String mfg;//manufacturer
protected String style;// car style
protected String color;//color of car
public VehicleClass(){
plate = null;
year = 0000;
style = null;
color = null;
}
public VehicleClass (String e , int r, String g, String y, String c){
plate = e;
year = r;
mfg = g;
style = y;
color = c;
}
public VehicleClass copyVehicle(VehicleClass k){
VehicleClass k1 = new VehicleClass();
k1.setPlate(k.getPlate ());
k1.setYear(k.getYear());
k1.setMfg(k.getMfg());
k1.setStyle(k.getStyle());
k1.setColor(k.getColor());
return k1;
}
public void setPlate(String e){
plate= e;
}
public void setYear(int r){
year = r;
}
public void setMfg(String g){
mfg = g;
}
public void setStyle(String y){
style = y;
}
public void setColor(String c){
color = c;
}
public String getPlate(){
return plate;
}
public int getYear(){
return year;
}
public String getMfg(){
return mfg;
}
public String getStyle(){
return style;
}
public String getColor(){
return color;
}
#Override //need this?
public String toString(){
return (plate + "\t" + year + "\t" + mfg +"\t"+ style + "\t" + color);
}
}
//Text File to import//
A3245D 2009 Ford sedan white
B3396 2011 GMC pickuup blue
S214X 2010 Toyota sedan white
TR3396 2009 BMW sedan black
XR295 2011 Honda pickuup red
Z2349A 2012 Toyota suv silver
IMAQT 2009 Honda suv blue
I did some corrections in there. Now it is working. I checked with plate. Can you check it. I think code can be improved further.
VehicleSearch.java
public class VehicleSearch {
private static String[] sliced;
public static void main(String[] args) throws FileNotFoundException {
String NameOfFile = JOptionPane.showInputDialog("Where is the File Path to Import Located at?");
File textFile = new File((NameOfFile));
Scanner in = new Scanner (textFile);
//Imports the appropriate text file named "vehicles.txt"//
ArrayList <String> carsArrayList = new ArrayList <String>();
while(in.hasNextLine()){
String line = in.nextLine();
carsArrayList.add(line);
}
in.close();
ArrayList<VehicleClass> vehicleObs = new ArrayList<VehicleClass>();
for (int i= 0; i <carsArrayList.size(); i++){
String temp = carsArrayList.get(i);
VehicleClass one = new VehicleClass ();
String[] sliced = temp.split("\\s+");
one.setPlate(sliced[0]);
int a = Integer.parseInt(sliced[1]);
one.setYear(a);
one.setMfg(sliced[2]);
one.setStyle(sliced[3]);
one.setColor(sliced[4]);
vehicleObs.add(one);
boolean stepTwo = true;
while(stepTwo) {
String search;
search = JOptionPane.showInputDialog("Please choose one of the following search options" + "1 Plate" + "\n" +"2 Year" + "3 Manufacturer" + "\n" + "4 Body Style"+ "\n"+ "5 Color");
int searchOption = Integer.parseInt(search);
String searchVal;
searchVal = JOptionPane.showInputDialog("Enter a value to search for" + "\n" + "All values must be exact in wording, please be careful when using Caps or check for Caps Lock");
searchDialogs(vehicleObs, searchOption, searchVal);
String c;
c = JOptionPane.showInputDialog("Type S to search | E to exit");
String b = "S";
if(c.equalsIgnoreCase(b)){
stepTwo = true;
}
else{
stepTwo= false;
}
}
}
}
public static String plateCheck(ArrayList list, String search){
ArrayList<String> as = new ArrayList<String>();
for (int i = 0; i< list.size(); i++){
String temp = list.get(i).toString();
if(temp.contains(search)){
as.add(list.get(i).toString());
}
}
return alFormat(as);
}
public static String yearCheck(ArrayList list, String search){
ArrayList<String> as = new ArrayList<String>();
for (int i = 0; i< list.size(); i++){
String temp = list.get(i).toString();
as.add(list.get(i).toString());
}
return alFormat(as);
}
public static String mfgCheck(ArrayList list, String search){
ArrayList<String> as = new ArrayList<String>();
for (int i = 0; i< list.size(); i++){
String temp = list.get(i).toString();
as.add(list.get(i).toString());
}
return alFormat(as);
}
public static String styleCheck(ArrayList list, String search){
ArrayList<String> as = new ArrayList<String>();
for (int i = 0; i< list.size(); i++){
String temp = list.get(i).toString();
as.add(list.get(i).toString());
}
return alFormat(as);
}
public static String colorCheck(ArrayList list, String search){
ArrayList<String> as = new ArrayList<String>();
for (int i = 0; i< list.size(); i++){
String temp = list.get(i).toString();
as.add(list.get(i).toString());
}
return alFormat(as);
}
public static void searchDialogs(ArrayList vehicleObs, int searchOption, String
searchVal){
if(searchOption == 1){
JOptionPane.showMessageDialog(null, "Your following search yielded the following results" + "\n" + plateCheck(vehicleObs, searchVal));
}//Outputs data (Plate Numbers) from the text file imported
else if(searchOption == 2){
JOptionPane.showMessageDialog(null, "Your following search yielded the following results" + "\n" + yearCheck(vehicleObs, searchVal));
}//Outputs data (Year) from the text file imported
else if(searchOption == 3){
JOptionPane.showMessageDialog(null, "Your following search yielded the following results" + "\n" + mfgCheck(vehicleObs, searchVal));
}//Outputs data (Manufacturer) from the text file imported
else if(searchOption == 4){
JOptionPane.showMessageDialog(null, "Your following search yielded the following results" + "\n" + styleCheck(vehicleObs, searchVal));
}//Outputs data (Style) from the text file imported
else if(searchOption == 5){
JOptionPane.showMessageDialog(null, "Your following search yielded the following results" + "\n" + colorCheck(vehicleObs, searchVal));
}//Outputs data (Color) from the text file imported
else{
JOptionPane.showMessageDialog(null, "Sorry no results have been found");
}//will only output this message only if nothing is found,//
}
public static String alFormat(ArrayList too){
String tmpString;
String full = "";
for( Object aValue : too){
tmpString = aValue + "\n";
full = full + tmpString;
}
return full;
}
}
VehicleClass.java
public class VehicleClass {
protected String plate;//car plate
protected int year;//car model year
protected String mfg;//manufacturer
protected String style;// car style
protected String color;//color of car
public VehicleClass(){
plate = null;
year = 0000;
style = null;
color = null;
}
public VehicleClass (String e , int r, String g, String y, String c){
plate = e;
year = r;
mfg = g;
style = y;
color = c;
}
public VehicleClass copyVehicle(VehicleClass k){
VehicleClass k1 = new VehicleClass();
k1.setPlate(k.getPlate ());
k1.setYear(k.getYear());
k1.setMfg(k.getMfg());
k1.setStyle(k.getStyle());
k1.setColor(k.getColor());
return k1;
}
public void setPlate(String e){
plate= e;
}
public void setYear(int r){
year = r;
}
public void setMfg(String g){
mfg = g;
}
public void setStyle(String y){
style = y;
}
public void setColor(String c){
color = c;
}
public String getPlate(){
return plate;
}
public int getYear(){
return year;
}
public String getMfg(){
return mfg;
}
public String getStyle(){
return style;
}
public String getColor(){
return color;
}
#Override //need this?
public String toString(){
return (plate + "\t" + year + "\t" + mfg +"\t"+ style + "\t" + color);
}
}
vehicle info file
AB-2323 1900 Japan Sport Black
AB-2323 1990 German Business White
AB-2323 2000 USA Army Blue

Making an array out of a custom class?

import java.io.*;
public class workPoS {
/**
* #param args
*/
public static void main(String[] args) {
dataList[] some_list = new dataList[10];
for (int x = 0; x < some_list.length; x++) {
some_list[x].firstName = "John";
some_list[x].middleName = "Jacob";
some_list[x].lastName = "Jingle-Heimer-Schmidt";
some_list[x].age = 101;
}
for (int x = 0; x < some_list.length; x++) {
System.out.println(some_list[x].firstName + " "
+ some_list[x].middleName + " " + some_list[x].lastName
+ " Age: " + some_list[x].age);
}
}
public class dataList {
String firstName, middleName, lastName;
int age;
public dataList() {
firstName = "";
middleName = "";
lastName = "";
age = 0;
}
}
}
ERROR: Exception in thread "main" java.lang.NullPointerException
at workPoS.main(workPoS.java:12)
This is line 12:
some_list[x].firstName = "John";
It seems that I am able to access some_list[x], but as soon as I specify a constructor, some_list[x].firstName, the result is a null value.
Am I simply referencing the constructor value incorrectly?
If so, what is the correct way to do so?
Thanks guys!
Look here:
dataList[] some_list = new dataList[10];
for (int x = 0; x < some_list.length; x++) {
some_list[x].firstName = "John";
You've created the array - but all the elements will be null references. You talk about "referencing the constructor value incorrectly" - you're not calling the constructor at all. You should have:
for (int x = 0; x < some_list.length; x++) {
some_list[x] = new dataList();
some_list[x].firstName = "John";
See the Java Tutorial for Arrays for more information.
(You should also fix your names to follow Java naming conventions, and make your fields private, but that's a different matter...)
If you are using both the classes in the same .java file, the try this code
import java.io.*;
public class workPoS {
public workPoS() {
super();
}
/**
* #param args
*/
public static void main(String[] args) {
workPoS wp = new workPoS();
dataList[] some_list = new dataList[10];
for (int x = 0; x < some_list.length; x++) {
some_list[x] = wp.new dataList();
some_list[x].firstName = "John";
some_list[x].middleName = "Jacob";
some_list[x].lastName = "Jingle-Heimer-Schmidt";
some_list[x].age = 101;
}
for (int x = 0; x < some_list.length; x++) {
System.out.println(some_list[x].firstName + " "
+ some_list[x].middleName + " " + some_list[x].lastName
+ " Age: " + some_list[x].age);
}
}
public class dataList {
String firstName, middleName, lastName;
int age;
public dataList() {
firstName = "";
middleName = "";
lastName = "";
age = 0;
}
}
}

Categories