Here is my code
class Employee{
private String Animal;
private int Quantity;
Employee(String Animal, int Quantity){
this.Animal=Animal;
this.Quantity=Quantity;
public String getAnimal{
return animal;
}
public void setAnimal{
this.Animal=Animal;
}
public String getQuantity{
return Quantity;
}
public void setQuantity{
this.Quantity=Quantity;
}
public static void Input(){
Scanner sc = new Scanner(System.in);
int n = 0;
Employee[] list = new Employee[20];
list[no] = new Employee(" ", 0);
String nameOfAnimal = sc.nextLine();
list[n].setAnimal(nameOfAnimal);
String numberOfAnimal = sc.nextLine();
list[n].setQuantity(numberOfAnimal);
++n;
}
public static void Output(){
...
for(int i=0; i<n; ++i){
System.out.println(" -" + list[i].getAnimal + " - " + list[i].getQuantity);
}
}
}
In the Output method, I dot 3 points because I don't know how to get the array declared in the Input method and print its content within the Output method. It always shows an error that the first element is null when I create the same array in the Output function. Concisely, how can I keep an array that both functions can be used?
As part of the curriculum at my school, we are working on some CodeHS Java.
There is one problem that I'm stuck on:
Taking our Student and Classroom example from earlier, you should fill in the method getMostImprovedStudent, as well as the method getExamRange. The most improved student is the one with the largest exam score range.
To compute the exam score range, you must subtract the minimum exam score from the maximum exam score.
For example, if the exam scores were 90, 75, and 84, the range would be 90 - 75 = 15.
This is the Student class which I added my method getExamRange().
import java.util.*;
public class Student
{
private static final int NUM_EXAMS = 4;
private String firstName;
private String lastName;
private int gradeLevel;
private double gpa;
private int[] exams;
private int numExamsTaken;
public static int[] examRange = new int[Classroom.numStudentsAdded];
private int i = 0;
/**
* This is a constructor. A constructor is a method
* that creates an object -- it creates an instance
* of the class. What that means is it takes the input
* parameters and sets the instance variables (or fields)
* to the proper values.
*
* Check out StudentTester.java for an example of how to use
* this constructor.
*/
public Student(String fName, String lName, int grade)
{
firstName = fName;
lastName = lName;
gradeLevel = grade;
exams = new int[NUM_EXAMS];
numExamsTaken = 0;
}
public int getExamRange()
{
Arrays.sort(exams);
examRange[i] = exams[exams.length-1] - exams[0];
i++;
return exams[exams.length-1] - exams[0];
}
public String getName()
{
return firstName + " " + lastName;
}
public void addExamScore(int score)
{
exams[numExamsTaken] = score;
numExamsTaken++;
}
// This is a setter method to set the GPA for the Student.
public void setGPA(double theGPA)
{
gpa = theGPA;
}
/**
* This is a toString for the Student class. It returns a String
* representation of the object, which includes the fields
* in that object.
*/
public String toString()
{
return firstName + " " + lastName + " is in grade: " + gradeLevel;
}
}
And this is the Classroom class in which I added the method getMostImprovedStudent().
import java.util.*;
public class Classroom
{
Student[] students;
static int numStudentsAdded;
public Classroom(int numStudents)
{
students = new Student[numStudents];
numStudentsAdded = 0;
}
public Student getMostImprovedStudent()
{
Arrays.sort(Student.examRange);
//return Student.examRange[0];
}
public void addStudent(Student s)
{
students[numStudentsAdded] = s;
numStudentsAdded++;
}
public void printStudents()
{
for(int i = 0; i < numStudentsAdded; i++)
{
System.out.println(students[i]);
}
}
}
I can get the exam Range by sorting the exams array then subtracting the smallest from the biggest, but once I do this, how do I find the student with the biggest exam range, and return it?
The way you would do this is looping through students, and have a variable to hold the biggest difference in score, and the most improved student:
public Student getMostImprovedStudent()
{
Student mostImproved = students[0];
int biggest = student[i].getExamRange();
for(int i = 1; i < students.length; i++) {
if(students[i].getExamRange() > biggest) {
mostImproved = students[i];
biggest = students[i].getExamRange();
}
}
return mostImproved;
}
However Java 8+ we can do:
public Student getMostImprovedStudent()
{
return Arrays.stream(students)
.max(Comparator.comparing(Student::getExamRange))
.get();
}
Which is assuming that students is not empty
As I explained in the comment above you can do it this way:
public Student getMostImprovedStudent() {
Student maxRangeStudent = null;
int maxRange = 0;
for (Student student: students) {
int curExamRange = student.getExamRange();
if (curExamRange > maxRange){
maxRangeStudent = student;
maxRange = curExamRange;
}
}
return maxRangeStudent;
}
import java.util.*;
public class Student
{
static CollegeCourse[] theirCourses = new CollegeCourse[5];
public static void main(String[] args)
{
int ID;
Scanner input = new Scanner(System.in);
/////////////////////////////////////////////////// Assigns student ID
System.out.println("Please enter your student ID >>");
ID = input.nextInt();
///////////////////////////////////////////// Wasn't sure how to populate the array
theirCourses[0] = new CollegeCourse("CIS 110", 3, 'A');
theirCourses[1] = new CollegeCourse("MATH 330", 2, 'A');
theirCourses[2] = new CollegeCourse("FR ENG 110", 2, 'A');
theirCourses[3] = new CollegeCourse("PHYSICS 110", 1, 'B');
theirCourses[4] = new CollegeCourse("GAMING 110", 1, 'C');
theirCourses[0].setCID("CIS 110");
theirCourses[1].setCID("MATH 330");
theirCourses[2].setCID("FR ENG 110");
theirCourses[3].setCID("PHYSICS 110");
theirCourses[4].setCID("GAMING 110");
theirCourses[0].setHours(3);
theirCourses[1].setHours(2);
theirCourses[2].setHours(2);
theirCourses[3].setHours(1);
theirCourses[4].setHours(1);
theirCourses[0].setGrade('A');
theirCourses[1].setGrade('A');
theirCourses[2].setGrade('A');
theirCourses[3].setGrade('B');
theirCourses[4].setGrade('C');
////////////////////////////////////////////////////////////////// Displays all preset populated courses
System.out.println("Please enter a number for the course you would to view, 0-4.\n"
+ "Courses are:");
for(int x = 0; x < theirCourses.length; ++ x)
{
System.out.println(theirCourses[x].getCID());
}
}
}
If I don't have the repetitious statements populating the array below where I already assign the array theirCourses a String, int, and char all in one line then when I get to the bottom where I have the print statement: System.out.println(theirCourses[x].getCID()); I keep getting a null output. Any clue as to what may be the cause of that? I will post the client class as well.
public class CollegeCourse
{
private String cID;
private int cHours;
private char grade;
public CollegeCourse(String string, int i, char c)
{
}
public void setCID(String c)
{
cID = c;
}
public String getCID()
{
return cID;
}
public void setHours(int h)
{
cHours = h;
}
public int getHours()
{
return cHours;
}
public void setGrade(char g)
{
grade = g;
}
public char getGrade()
{
return grade;
}
}
Like #JB Nizet mentioned, your constructor is not doing anything. Constructor is taking the parameters, set them as the value.
public CollegeCourse(String string, int i, char c) {
cID = string;
cHours = i;
grade = c;
}
Get rid of all the setCID, setHours and setGrade. That's 15 lines of unnecessary code.
I am creating a program that handles a car dealership. The user has the opportunity to add a car in the store by creating a random 3 digit number.
Now the question is how I can search/delete cars depending on the 3 digit code?
I'm thinking that I need every code that the cars have to save it on an array so I can search and delete afterwards.
I have created a class and certain methods on it, I have also created 5 objects and I'm trying to see if it works on these 5.
Here is the method of the random number:
I use the metritis variable because I can't achieve to place correctly the values on the array so I have to give parameter of 1,2,3,4,5 so I can place them correctly to the array.
package antiprosopeia;
import java.util.Random;
public class Antiprosopeia {
private String company,colour;
private int model,horsePower,speed,price,specialCode,metritis;
private int[] codes = new int[]{0,0,0,0,0};
public Antiprosopeia(String company, String colour, int model, int horsePower, int speed, int price) {
this.company = company;
this.colour = colour;
this.model = model;
this.horsePower = horsePower;
this.speed = speed;
this.price = price;
}
public Antiprosopeia() {
company = ""; colour = ""; model = 0; horsePower = 0; speed = 0; price = 0;
}
public void setRandomNumber(int metritis) {
Random rand = new Random();
int randNum2 = rand.nextInt(900) + 100;
specialCode = randNum2;
codes[metritis] = specialCode;
}
public void printarray() {
for(int i=0; i<codes.length; i++) {
System.out.println(" " + codes[i]);}
}
public void Info() {
System.out.println("Company : " + company + "\nColour : " + colour + "\nModel : " + model + "\nHorse Power : " + horsePower +
"\nSpeed : " + speed + "\nPrice : " + price );
}
public static void main(String[] args) {
Antiprosopeia car1 = new Antiprosopeia("Toyota","red",333,100,2223,8000);
car1.setRandomNumber(0);
Antiprosopeia car2 = new Antiprosopeia("Mercedes","yellow",233,100,2990,9000);
car2.setRandomNumber(1);
Antiprosopeia car3 = new Antiprosopeia("Volkswagen","green",153,100,2780,6000);
car3.setRandomNumber(2);
Antiprosopeia car4 = new Antiprosopeia("Mitsubisi","white",678,140,2600,7000);
car4.setRandomNumber(3);
Antiprosopeia car5 = new Antiprosopeia("Porsche","black",390,1000,2000,30000);
car5.setRandomNumber(4);
}
}
[EDIT] Now when i call the printarray() method it seems that at my array only one value is hold and all the others are zer0s as i defined the array at start of my program
If I were doing this, I would use a HashMap. This way you know that you have a unique 3 digit number, and if you wanted to, you could also store more data. You could do something like:
HashMap<Integer, Car> cars = new HashMap<Integer, Car>();
This example would allow you to add a car object to the map. You don't have to that, but it's an option. If you didn't want to do that, you could do:
HashMap<Integer, String> cars = new HashMap<Integer, String>();
and then do:
cars.put(123, "Description of car");
Using a HashMap would give you more options when storing the data. This would also prevent you from creating an array with 1000 elements, all of which are 0 until you have a value for them. You could easily print out all your numbers by doing:
for(int number : cars.entrySet()){
System.out.println("My car number: " + number);
}
Searching for keys would extremely easy, as you could do:
String description = cars.getKey(123);
If description was null, you would know that there is no key for it.
Your issue is that each Antiprosopeia object has its own codes array. They are not shared.
If you really want each object to have a Random ID, then assign that within the constructor.
public class Antiprosopeia {
private String company,colour;
private int model,horsePower,speed,price,specialCode,metritis;
private int randID;
public Antiprosopeia(String company, String colour, int model, int horsePower, int speed, int price){
this.company = company;
this.colour = colour;
this.model = model;
this.horsePower = horsePower;
this.speed = speed;
this.price = price;
this.randID = new Random().nextInt(900) + 100;
}
public Antiprosopeia(){
this("", "", 0, 0, 0, 0);
}
public int getID() { return this.randID; }
#Override
public String toString() {
return String.format(
"Company : %s\n" +
"Colour : %s\n" +
"Model : %s\n" +
"Horse Power : %d\n" +
"Speed : %d\n" +
"Price : %d\n",
company, colour, model, horsePower, speed, price
);
}
If you want to print all those objects,
public static void main(String[] args) {
List<Antiprosopeia> cars = new ArrayList<Antiprosopeia>();
cars.add(new Antiprosopeia("Toyota","red",333,100,2223,8000));
cars.add(new Antiprosopeia("Mercedes","yellow",233,100,2990,9000));
for (int i = 0; i < cars.size(); i++) {
Antiprosopeia c = cars.get(i);
System.out.println(c.getID());
System.out.println(c);
}
}
package chapter10;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Customer {
private String name;
private String streetAddress;
private String phoneNumber;
private int total;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStreetAddress(){
return streetAddress;
}
public void setStreetAddress(String streetAddress) {
this.streetAddress = streetAddress;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public int getTotal(){
return total;
}
public void setTotal(int total){
this.total = total;
}
public static void assign(){
int a = (int) (Math.random() + 10);
int r = (int) (Math.random() + 10);
int f = (int) (Math.random() + 10);
System.out.println(a + r + f + "x" + "x" + "x");
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
ArrayList <Customer > customerList = new ArrayList <Customer>();
char ans;
do
{
Customer customer = new Customer();
System.out.print("Customer name ");
customer.setName(in.next());
int i = 0;
++i;
System.out.print("Street Address ");
customer.setStreetAddress(in.next());
System.out.print("Phone Number ");
customer.setPhoneNumber(in.next());
customerList.add(customer);
System.out.println("Enter total sales ");
customer.setTotal(in.nextInt());
System.out.println("Would you like to enter in a new customer ( y/n)? ");
String answer = in.next();
ans = answer.charAt(0);
((String) customerList).concat("")
} while(ans == 'y');
for(Customer c: customerList){
System.out.print(c.getName() + "\n" + "Phone number is " +c .getPhoneNumber() +"\n" + "Total sales is "+ c.getTotal() + "\n" + "Address is"+ c.getStreetAddress());
}
for(int i=0; i<customerList.size(); i++){
//System.out.print(customerList.get(i).getName());
}
}
}
I need to assign a number to each value in the arraylist but i am getting an error that says that I have to convert to string (arraylist). How do I add it?
If what I gather from the comments is correct then I believe this is what you want:
Your current assign() is incorrect if you want random values 1-10, it should look like this instead:
public String assign(){
Random rand = new Random();
int a = rand.nextInt(10) + 1;
int r = rand.nextInt(10) + 1;
int f = rand.nextInt(10) + 1;
return a+r+f+"xxx";
}
Customer will look like this:
public class Customer {
private String name;
private String customerNumber;
private String streetAddress;
private String phoneNumber;
private int total;
...
...
...
public String getCustomerNumber() { return this.customerNumber; }
public void setCustomerNumber(String cNumber) { this.customerNumber = cNumber; }
And assigning the numbers should look like this:
for(Customer c : customerList) {
c.setCustomerNumber(assign());
}
Also avoid this line of code, it's a really bad idea:
((String) customerList).concat("")
You should probably rename the customerNumber to customerID.
Hiiii
As i understand you are trying to to add number to each value to arrayList ,And same time you are creating arrayList of customer object, So first understand about arrayList of object,
Customer c1 = new Customer();
Customer c2 = new Customer();
ArrayList<Customer> al = new ArrayList();
al.add(c1);
al.add(c2);
Here this ArrayList object save only address of customer object so how can you change the address of Customer object ; You can not add number in Customer type ArrayList Object,
There is another way typecast your ArrayList to Object type and then no need to typecast again , you can add any type of object in ArrayList
like this,
Customer c1 = new Customer();
Customer c2 = new Customer();
ArrayList<Object> al = new ArrayList();
al.add(c1);
al.add(c2);
In your code there's the following line:
((String) customerList).concat("")
Trying to cast a List to a String is doomed to failure - I'm not sure why do you think it should work.
If you want a String representation of the list, you should implement a toString() method in class Customer and then you can do something like:
System.out.println(Arrays.toString(customerList.toArray()));
Instead of using ArrayList, you can use Map. In which you can have the number as key and value as Customer.
http://examples.javacodegeeks.com/java-basics/java-map-example/ Contains the example of using Map
Answer in Storing a new object as the value of a hashmap? contains info about how to use Object as value in HashMap