Integer and ArrayList issues - java

This program is meant to prompt a user for address information. Identify the address that would come first by zip code, and then print that address.
I'm having a couple of issues. When I try to assign an int value to the apartment variable, I get an error. Same thing with the zip code portion. Once the minimum value is found, then I want to get the index of the minimum value so that I can print the same index value of each arraylist.
Can someone point me in the right direction or give me a good reference for this? I think I'm just confusing a few things.
package newchapter7;
import java.util.*;
/**
*
* #author Crazy
*/
public class Address {
ArrayList<Integer> houses = new ArrayList<>();
ArrayList<String> streets = new ArrayList<>();
ArrayList<Integer> apts = new ArrayList<>();
ArrayList<String> cities = new ArrayList<>();
ArrayList<String> states = new ArrayList<>();
ArrayList<Integer> zips = new ArrayList<>();
int minValue;
/**
* Adds a house number to the address
* #param house house number
*/
public void addHouse(int house)
{
houses.add(house);
}
public ArrayList<Integer> getHouse()
{
return houses;
}
/**
* Adds a street name to the address
* #param street street name
*/
public void addStreet(String street)
{
streets.add(street);
}
public ArrayList<String> getStreet()
{
return streets;
}
/**
* constructor to add an apartment number that equals 0
*/
public void addApt()
{
}
/**
* Adds an apartment number to the address
* #param aptNbr apartment number
*/
public void addApt(int aptNbr)
{
apts.add(aptNbr);
}
public ArrayList<Integer> getAptNbrs()
{
return apts;
}
/**
* Adds a city to the address
* #param city city
*/
public void addCity(String city)
{
cities.add(city);
}
public ArrayList<String> getCity()
{
return cities;
}
/**
* Adds a state to the address
* #param state state
*/
public void addState(String state)
{
states.add(state);
}
public ArrayList<String> getState()
{
return states;
}
/**
* Adds a zip code to the address
* #param zip zip code
*/
public void addZip(int zip)
{
zips.add(zip);
}
public ArrayList<Integer> getZip()
{
return zips;
}
public int arrValue()
{
minValue = zips.indexOf(Collections.min(zips));
return minValue;
}
}
Main
package newchapter7;
import java.util.*;
public class NewChapter7 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Address addy = new Address();
for (int i = 0; i < 3; i++)
{
System.out.print("Please enter a house number: ");
int house1 = in.nextInt();
addy.houses.add(house1);
System.out.print("Please enter the street name: ");
String street1 = in.next();
addy.streets.add(street1);
System.out.print("Please enter an apartment number if applicable: ");
int apartment;
apartment = in.nextInt();
addy.apts.add(apartment);
if (apartment != 0)
{
addy.apts.add(apartment);
}
else
{
addy.apts.add(0);
}
System.out.print("Please enter the city name: ");
String city2 = in.nextLine();
addy.cities.add(city2);
System.out.print("Please enter the state name: ");
String states2 = in.nextLine();
addy.states.add(states2);
System.out.print("Please enter the zip code: ");
int zipC = in.nextInt();
addy.zips.add(zipC);
}
}
}
This is a homework assignment. I think I've confused the material quite a bit and even if this works, I would like to learn a more efficient way to accomplish the same task.
Error
Please enter a house number: 772
Please enter the street name: Apple Drive
Exception in thread "main" java.util.InputMismatchException
Please enter an apartment number if applicable:
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at newchapter7.NewChapter7.main(NewChapter7.java:32)
Java Result: 1
BUILD SUCCESSFUL (total time: 21 seconds)
Assignment:
Implement a class Address. An address has a house number, a street, an optional apartment number, a city, a state, and a postal code. Supply two constructors: one with an apartment number and one without. Supply a print method that prints the address with the street on one line and the city, state, and postal code on the next line. Supply a method public boolean comesBefore (Address other) that tests whether this address comes before another when the addresses are compared by postal code.

Your Address class is mixed up and actually seems backwards to me. I think that you'd be much better off if it represented the state of a single address. If so, then it should not hold ArrayLists, but rather individual fields for a single house with getter and setter methods for each field, a constructor that accepts the field parameters, and perhaps a default constructor that accepts no parameters if desired.
Then if you need to work with many Addresses, you can create a single ArrayList<Address> for this.
Note that as an aside, I wouldn't use int for apartment number or zip code. While these look like numbers and comprise the digits of numbers, they don't behave as numbers. Use String instead.

change
String street1 = in.next();
addy.streets.add(street1);
line to
in.nextLine();
String street1 = in.nextLine();
addy.streets.add(street1);
and other next() to nextLine() also.
Ok the suggestion above is not working this is the full working code, but you have a possible logical error in this. Since it is homework you should be able to solve that. However...
for (int i = 0; i < 3; i++)
{
System.out.print("Please enter a house number: ");
int house1 = in.nextInt();
addy.houses.add(house1);
System.out.print("Please enter the street name: ");
in.nextLine();
String street1 = in.nextLine();
addy.streets.add(street1);
System.out.print("Please enter an apartment number if applicable: ");
int apartment;
apartment = in.nextInt();
addy.apts.add(apartment);
if (apartment != 0)
{
addy.apts.add(apartment);
}
else
{
addy.apts.add(0);
}
System.out.print("Please enter the city name: ");
in.nextLine();
String city2 = in.nextLine();
addy.cities.add(city2);
System.out.print("Please enter the state name: ");
String states2 = in.nextLine();
addy.states.add(states2);
System.out.print("Please enter the zip code: ");
int zipC = in.nextInt();
addy.zips.add(zipC);
}

Related

How to I do an array with a JOptionPane

The question asks "The number of fuel tanks can only be (2,4,8,10, 15,20)" this is aNbrTanks in the code below. I been trying to use an array to have these inputs. But then I get the error of Object cant be converted to int or int[] to int. I need to ask for input by JOptionPane and then ask again if it doesn't meet the standards.
package project2;
import javax.swing.JOptionPane;
/**
*
* #author Administrator
*/
public class VehicleApp {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
//name
String firstName = JOptionPane.showInputDialog("Please enter your first name");
while(firstName.equals("")){
firstName =JOptionPane.showInputDialog("Please enter a valid first name");
}
String lastName = JOptionPane.showInputDialog("Please enter your last name");
while(lastName.equals("")){
lastName =JOptionPane.showInputDialog("Please enter a valid first name");
}
String aName = firstName + " " + lastName;
//phone
String aphone = JOptionPane.showInputDialog("Please enter your number");
while(aphone.length()!=10){
aphone = JOptionPane.showInputDialog("Please enter a valid phone number");
}
String aPhone = ("" + aphone).replaceAll("(...)(...)(....)", "$1-$2-$3");
//vechicle number
int aNbrVehicles = Integer.parseInt(JOptionPane.showInputDialog("Enter the number of Vehicles"));
while(aNbrVehicles < 1 || aNbrVehicles > 10 ){
aNbrVehicles = Integer.parseInt(JOptionPane.showInputDialog("valid number of Vehicles"));
}
//fuel tank
int aNbrTanks = Integer.parseInt(JOptionPane.showInputDialog("Enter the number of Tanks"));
VehicleFactory JarApp = new VehicleFactory(aName, aPhone, aNbrVehicles, aNbrTanks);
JarApp.calcManufacturingCost();
JarApp.calcFuelTankCost();
JarApp.calcSubtotal();
JarApp.calcTax();
JarApp.calcTotal();
JOptionPane.showMessageDialog(null, JarApp.getSummary());
}
}
I just need ideas or help figuring out how to get an array or a statement that be used as int aNbrTanks like the question asks.
You could request values in a loop, as you suggest anyway.
My example shows the loop you can use. There are more efficient ways to test for the allowed values.
int aNbrTanks = 0;
while (true) {
try {
aNbrTanks = Integer.parseInt(JOptionPane.showInputDialog("Enter the number of Tanks"));the number of Vehicles"));
} catch (NumberFormatException e) {
e.printStackTrace(e);
}
if (aNbrTanks==2) {
break;
}
}
Coming back to your title question, you can use JOptionPane with an Object[], not int[]. It will then convert your list of choices into a JComboBox. Here is an example:
public static void main(String[] args) {
Object[] choices = new Object[]{2,3,5,8};
System.out.println(Arrays.toString(choices));
Object choice = JOptionPane.showInputDialog(null, "Enter the number of Tanks", "Tanks", JOptionPane.PLAIN_MESSAGE, null, choices, 2);
System.out.println(choice);
}

Using empty arrays to create methods

Thanks to some online assistance from the wonderful stackoverflow users, here is the edits to the enroll and drop student methods to add to the Student array set up. Now it's just on to get the other methods to work as well. Any insight for those would be helpful, especially for speed and efficiency at those points.
import java.util.Scanner;
public class School {
private Student[] theStudents;
public School() {
this.theStudents = new Student[] { null };// needs to start out as empty
}
/*
* next two methods would allow a user to add or drop a student into the
* student array for the school Also with Enroll student, should be able to
* assign a class to the student, i.e. Calculas, history, etc
*/
public void enrollStudent(Student newStudent) {
Student newStudents[] = new Student[theStudents.length+1];
for (int i = 0; i < theStudents.length; i++)
{
newStudents[i] = theStudents[i];
}
newStudents[theStudents.length] = newStudent;
theStudents = newStudents;
}
public void dropStudent(Student dropStudent) {
Student newStudents[] = new Student[theStudents.length-1];
for (int i = 0; i > theStudents.length; i--)
{
newStudents[i] = theStudents[i];
}
newStudents[theStudents.length] = dropStudent;
}
// add Test Score for a student
public double addTestScore(String newStudent, double testScore) {
testScores[posi] = testScore;
}
/*
* count the number of students in a given class, not the school
*/
public int countClassSize(String course) {
}
// get average average score of a given class
public double averageAverageScore(String course) {
}
/*
* add a programming language to only CS students at the school Will need to
* use the instanceof for proper type casting
*/
public String addProgrammingLanguage(String studentName, String programLanguage) {
}
/*
* Count the number of students in the school that know a certain
* programming language, again will need to typecast properly
*/
public int numberThatKnowLanguage(String programLanguage) {
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
String dropStudent, course;
System.out.println("Welcome to the School. Please select " + "Option 1 to enroll a regular student, \n "
+ "Option 2 to enroll a CompSci student, \n" + "Option 3 to drop a student, \n"
+ "Option 4 to add test score or programming language, or \n" + "Option 5 to perform class analytics.");
int Operation = input.nextInt();
/*
* Simple UI to add and drop students, will need to set the operation to
* call the add and drop students to fit them to the Student body array
* will need to make these two options loop until the user is satisfied
* with the size of the student body
*/
if (Operation == 1) {
System.out.println("Enter the # of regular students that you want to add to the school.");
int addStudents = input.nextInt();
/*
* Possibly create some type of input array to
* make it easier to enter the students' names
*/
System.out.println("Please enter the name and course of the student you are enrolling:");
Student newRegularStudent = (String) input.next();
course = input.next();
}
else if (Operation == 2) {
System.out.println("Enter the # of CompSci students that you want to add to the school.");
int addStudents = input.nextInt();
/*
* Possibly create some type of input array to make it easier to
* enter the students' names
*/
System.out.println("Please enter the name and course of the student you are enrolling:");
Student newCompSciStudent = (String) input.next();
course = input.next();
}
else if (Operation == 3) {
System.out.println("Enter the # of students that you want to drop from the school.");
int dropStudents = input.nextInt();
/*
* Possibly create some type of input array to make
* it easier to enter the students' names
*/
System.out.println("Please enter the name of the student you wish to drop from the school:");
dropStudent = (String) input.next();
/*
* After the first two operations, will need to build to the UI to
* call the other five methods, will need to make it into a
* while/for loop so user can continue to add information as needed.
*/
}
else if (Operation == 4) {
System.out.println("Enter the # for what you want to add to a student's records."
+ "Enter 1 to enter a test score\n " + "Enter 2 to enter a programming language, enter 2.");
int optionNum1 = input.nextInt();
/*
* Possibly create some type of input array
* to make it easier to enter the students' names
*/
if (optionNum1 == 1) {
} else if (optionNum1 == 2) {
}
}
else if (Operation == 5) {
System.out.println("This is the analytics section of this program.\n");
System.out.println("Enter the # for which of the following analytics options that you want performed: "
+ "Enter 1 to count the # of students for a particular class,\n "
+ "Enter 2 to calculate the average average score for all students take a particular course, or\n "
+ "Enter 3 to count the # of CompSciStudents.");
int optionNum2 = input.nextInt();
if (optionNum2 == 1) {
System.out.println("Enter the course name that you want to know the # of students for.");
course = input.next();
Student classSize;
classSize.countClassSize(course);
}
else if (optionNum2 == 2) {
System.out.println("Enter the course name that you want \n"
+ "to calculate the average average test value for.");
course = input.next();
Student testAvg;
testAvg.averageAverageScore(course);
}
else if (optionNum2 == 3) {
System.out.println("Count the # of CompSciStudents who know a \n"
+ "particular programming language by entering that language name now.");
String programLanguage = input.next();
CompSciStudent csStudent;
csStudent.knowsLanguage(programLanguage);
}
}
input.close();
}
}
I don't know if this is the best way, but if I were you, I would just create a new array one size larger or smaller and fill it will the values from the old array each time you add or remove a value. For example:
public void enrollStudent(Student newStudent) {
Students newStudents[] = new Student[theStudents.length+1];
for (int i = 0; i < theStudents.length; i++)
{
newStudents[i] = theStudents[i];
}
newStudents[theStudents.length] = newStudent;
theStudents = newStudents;
}
Not very efficient but hey, it doesn't sound like you're doing anything that needs to be super efficient.

Two methods executing at the same time? Why?

package contractmanager;
import java.util.*;
/**
*
* #author Tom McCloud
*/
public class ContractManager {
static Scanner keyb = new Scanner(System.in);
// global scanner
public static void main(String[] args) {
int option;
//variable declaration
String clientName;
String packageSize;
String dataBundle;
String reference;
int period;
boolean intlCalls;
//display menu to user
System.out.println("Welcome: \n");
System.out.println("1. Enter new contract ");
System.out.println("2. Display contract summary");
System.out.println("3. Display summary of contract for selected month");
System.out.println("4. Find and display contract");
System.out.println("0. Exit");
//take option off user
option = keyb.nextInt();
//WIP - only working on option 1 at the minute
switch(option) {
case 1:
clientName = clientName();
packageSize = packageSize();
dataBundle = dataBundle();
reference = reference();
break;
}
exit();
}
public static void exit()
{
System.out.println("Thank you for using the contract manager. Goodbye!");
}
public static String clientName()
{
String name = " ";
System.out.println("Please input your full name: ");
name = keyb.nextLine();
return name;
}
public static String packageSize()
{
String size;
System.out.println("Please input your package size: ");
System.out.println(" 1. Small \n 2. Medium \n 3. Large");
size = keyb.next();
return size;
}
public static String dataBundle()
{
String data;
System.out.println("Please input data bundle size: ");
System.out.println("1. Low \n 2. Medium \n 3. High \n 4. Unlimited");
data = keyb.next();
return data;
}
public static String reference()
{
String ref;
boolean isRefValid = false;
do {
System.out.println("Please input your reference code: ");
ref = keyb.next();
if(ref.length() > 6)
{
System.out.println("Reference number too long, re-enter!");
}
for(int i = 0; i < 2; i++)
{
if(Character.isDigit(ref.charAt(i)))
{
System.out.println("First two characters must be letters!");
}
}
} while(isRefValid = false);
return ref;
}
}
So, this is some code I have. If I press enter code hereone, it executes these, now technically shouldn't this be in order of one another once each method reaches completion and returns?
For example, on execution after pressing "1" I get the following output:
Please input your full name:
Please input your package size:
1. Small
2. Medium
3. Large
Whereas this should come one by one, after the full name has been inputted it should move onto the package size step. If I input it goes to the third step rather than repeating for the second step's input.
I think it's because in your clientName function you have just printed "Please input your full name: " without waiting for input. For example you have to do something like below here scan.nextLine() will wait until user have press enter:
Scanner scan = new Scanner();
System.out.println("Please input your full name:");
String name= scan.next();
System.out.println(name);
scan.nextLine();
Updated: Try by updating clientName function as below
public static String clientName() {
String name = " ";
System.out.println("Please input your full name: ");
name = keyb.next();
keyb.nextLine();
return name;
}

Arrays between classes?

Main Class;
package finalapp;
import java.util.Scanner;
/**
*
* #author bassammetwally
*/
public class FinalApp {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner input = new Scanner(System.in);
Team tem = new Team();
Tournament tour = new Tournament();
System.out.print("Whats the tournament name?\n");
tour.setTourName(input.next());
System.out.print("Please enter the tournamen date\n");
tour.setTourDate(input.next());
System.out.print("Please enter the location\n");
tour.setLocation(input.next());
System.out.print("Please enter number of Software Stations\n");
tour.setAvaliableHardwareIns(input.nextInt());
System.out.print("Please enter number of Hardware Stations\n");
tour.setAvaliableHardwareIns(input.nextInt());
System.out.print("Please enter number of field testing");
tour.setAvaliableFieldTesting(input.nextInt());
System.out.print("Please enter max number of teams\n");
tour.setMaxNumberOfTeams(input.nextInt());
tour.tourStatSet(1);
while (true)
{
int choice;
choice = input.nextInt();
if (choice == 1)
{
System.out.printf("Enter Team %s Names\n",tour.getMaxNumberOfTeams());
for (int i = 0; i >= tour.getMaxNumberOfTeams();i++)
{
System.out.print("Please Enter Team Name");
tour.addingTeam(input.next());
tem.teamStats(1);
tem.teamJudgeStat(1);
Have a PREPARING team turn the robot on
(set the robot status to READY) to prepare for inspections
}
}
else if ( choice == 2)
{
System.out.print("Sending prepareing teams");
//for (int a = 0; a >= tour.getTeamsChecked(); a++)
{
}
}
}
}
Question:
I'm making a robot contest simulation, and I'm trying to get the main class to:
Add teams, which I already did
Change status of each team in the array
But my main idea was to go through the ArrayList and change the variables in the other classes, but I couldn't figure out how to do it.
Is there any easier way to do this?
From what it sounds like you should be able to use simple getters and setters to do what you want.
Simply have a method that sets the value you want into an array, and another that gets the array or a specific index in the array. This way you can set and share the array between classes.

Why does this array go out of bounds inconsistently?

This is a Student class I have which creates a student that has a name, grade, and ID number. The Student is used as the key in a TreeMap, while the student's grade is used as the value. I wrote compareTo as I am implementing Comparable, but this error pops up upon entering in the first student:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at Student.<init>(Student.java:25)
at Main.main(Main.java:50)
Java Result: 1
I think it is coming from the splitting of the student's name into a String[], but I've tested those lines that call the first and last names, as well as the line that splits the name and they all seem to work as intended, except for when they are called in compareTo.
Any help would be much appreciated.
public class Student implements Comparable<Student>{
private String name, grade, first, last;
private String[] stuName;
private int id;
/**
* Constructs a new Student with a name, ID Number, and a grade.
* #param n name
* #param i ID Number
* #param g grade
*/
public Student(String n, int i, String g){
name = n;
id = i;
grade = g;
stuName = n.split(" ");
first = stuName[0];
last = stuName[1];
}
/**
* Compares Students. First by last name, then by first if the last names
* are the same. If the first names are also the same, the students are
* compared by their ID Numbers.
* #return the value upon comparing the proper property of the Student
*/
#Override
public int compareTo(Student other){
if (last.equals(other.getLast())){
if (first.equals(other.getFirst())){
return id - other.getID();
}else
return first.compareTo(other.getFirst());
}
return last.compareTo(other.getLast());
}
/**
* Changes the student's current grade.
* #param g new grade
*/
public void changeGrade(String g){
grade = g;
}
/**
* Returns student's name.
* #return name
*/
public String getName(){
return name;
}
/**
* Returns student's first name.
* #return first name
*/
public String getFirst(){
return first;
}
/**
* Returns student's last name.
* #return last name
*/
public String getLast(){
return last;
}
/**
* Returns the student's grade.
* #return grade
*/
public String getGrade(){
return grade;
}
/**
* Returns the student's ID Number
* #return id number
*/
public int getID(){
return id;
}
Tester:
public class Main {
public static void main(String[] args) throws InterruptedException{
Map<Student, String> students = new TreeMap();
Scanner in = new Scanner(System.in);
System.out.println("How many students do you want to add?");
int numStudents = in.nextInt();
String name, grade;
int id;
for (int i = 1; i < numStudents; i++){
System.out.println("Name of student " + i + "?");
name = in.nextLine();
in.nextLine();
System.out.println("Grade of " + i + "?");
grade = in.nextLine();
System.out.println("ID Number of " + i + "?");
id = in.nextInt();
Student s = new Student(name, id, grade);
students.put(s, s.getGrade());
}
System.out.println("How many students do want to remove");
int remStudents = in.nextInt();
for (int i = 0; i < remStudents; i++){
System.out.println("ID?");
int remID = in.nextInt();
for (Student s : students.keySet()){
if (s.getID() == remID){
students.remove(s);
}
}
}
System.out.println("How many grades do you want to change?");
int changeGrades = in.nextInt();
for (int i = 0; i < changeGrades; i++){
System.out.println("ID?");
int foo = in.nextInt();
System.out.println("New grade?");
String newGrade = in.nextLine();
for (Student s : students.keySet()){
if (s.getID() == foo){
s.changeGrade(newGrade);
}
}
}
String printout = "";
for (Student s : students.keySet()){
printout += s.getLast() + ", " + s.getFirst() + " (" + s.getID() + "): " + s.getGrade() + "\n";
}
System.out.println(printout);
}
}
Probably because you have two different loops, with different indices:
in your one loop, you start from 1, and thus you are 1 student short:
for (int i = 1; i < numStudents; i++){
in the delete loop you have a 0-based index:
for (int i = 0; i < remStudents; i++){
I suspect that, you think you add 2 studends, but really you have just one (at index 0), and thus your indexout-of-bounds exception.
EDIT, OP has added a 'full' stack for the exception, and the above answer is not related to the OP's problem.....
Answer 2: Based on your revised stack/exception edit, the only possible answer is that there are no spaces in the student's name..... your assertion that there is always a space is simply not true ....
you may want to add a count qualifiewr to the split so that you will get an empty string on any invalid input:
stuName = n.split(" ", 2);

Categories