I've made a bit of a mess on a project of mine. I have to create an array of objects. I have made an array but it only has 1 field 'myMonths' referring to the length of time of the project.
In my main method:
case 1:
int n = 1; //int n = number of projects
Scanner sc = new Scanner(System.in);
//myMonths = new int[amount];
System.out.println("** Only projects with a duration between 2 and 12 months can be included **");
System.out.println("What was the duration of your projects in months?");
for(int i=0; i<1; i++){
int a = sc.nextInt();
//display error message
if((a < 2) || (a > 12)){
System.out.println(" Please enter an amount between 2 and 12 months. ");
}
//add to the array
else{
myMonths[index++] = a;
}
}
calc.setMyMonths(myMonths); //creating the object
break;
In my class on separate file:
public class MenuTestClass{
private int myMonths[];
private double average; //store average value of numbers
private boolean averageCanBeCalculated;
private int max; // store max number from array. to be calculated
public MenuTestClass(){
myMonths = new int[5];
}
public MenuTestClass(int[] myMonths){
this.myMonths = myMonths;
}
public void setMyMonths(int[] values){ //declare setter method
myMonths = values;
}
I should have added in two more fields, both strings. Is there a way I can add more fields/attributes to this array and have them viewable at the same time under 1 index? For example at [0] projectName, projectManager, myMonths ie(string, string, integer).
Any advice would be great, I am getting really confused with OOP. Thanks in advance!
Yes, create a class containing your three properties:
class MyContainer {
public MyContainer(int durationMonths, String projectName, String projectManager) {
this.durationMonths = durationMonths;
this.projectName = projectName;
this.projetManager = projectManager;
}
public int durationMonths;
public String projectName;
public String projectManager;
}
Then create an array of this class with:
MyContainer[] myArray = new MyContainer[numberOfProjects];
Add items to the array like this:
myArray[0] = new MyContainer(3, "super project", "awesome manager");
Related
When I try to use scanner on another class I can't update the array.
private int numClients;
private int[] clients;
These are variables from my class Rooms.
public Hotel(String name, int numRooms, int numClients){
this.name = name;
this.numRooms = numRooms;
this.numClients= numClients;
this.clients = new int[numClients];
}
Of course I added setters and getters:
public String getName() {
return name;
}
public void setNaziv(String name) {
this.name = name;
}
public int getNumRooms() {
return numRooms;
}
public void setNumRooms(int numRooms) {
this.numRooms = numRooms;
}
public int getNumClients() {
return numClients;
}
public void setNumClients(int numClients) {
this.numClients = numClients;
}
When I tried to add it to test it in another class, name and numRooms change. numClients change too but array doesn't update.
Hotel h1 = new Hotel(" ", 0, 0);
String name= sc.nextLine();
h1.setName(name);
int numRooms= sc.nextInt();
h1.setNumRooms(numRooms);
int numClients= sc.nextInt();
h1.numClients(numClients);
h1.show();
This is the show method:
public void show(){
System.out.println("Name: " + this.name);
System.out.println("Rooms: " + this.numRooms);
System.out.println("Number of clients: " + this.numClients);
for(int i = 0; i < clients.length; i++) {
System.out.println(clients[i]);
}
}
Maybe there will be some typing errors I translated the var names to English for question purposes.
Once you have created the array, it's size is fixed. You can test this with a few rows:
int size = 10; // Start with size 10
int[] array = new int[size]; // Array is 10 elements long
System.out.println(size); // Prints 10
System.out.println(array.length); // Also prints 10
size = 1000; // Change size ??
System.out.println(size); // Prints 1000
System.out.println(array.length); // Still prints 10
Output:
10
10
1000
10
You also don't appear to actually set any elements in the array in your code. That would be something like
h1.getClients()[0] = 3;
Edit
When this line in your constructor is exectuted:
this.clients = new int[numClients];
The array is created with the size that numClients has right at that moment. After that, there is no relation between numClients and clients anymore.
You would need to create a new array, copy contents (if you want to preserve it) and reassign clients with the new array in order to change the size.
You can do this with Arrays.copyOf() :
int newLength = 20;
array = Arrays.copyOf(array, newLength);
System.out.println(array.length); // Prints 20!!
The constructor will run once for a single object. So, if you want to add more values in the clients array then a method is a must.
The main Class:
class Main {
public static void main(String[] args) {
Hotel hotel = new Hotel("romeo",5,10);
hotel.addClients(6);
hotel.addClients(10);
hotel.addClients(5);
hotel.show();
}
}
The Hotel Class:
class Hotel{
private int numRooms,numClients;
private String name;
private int clients[] = new int[10];
public Hotel(String name, int numRooms, int numClients){
this.name = name;
this.numRooms = numRooms;
this.numClients= numClients;
this.clients[0] = numClients;
}
The method to add Clients in the clients array:
public void addClients(int numClients){
for(int i = 0; i < clients.length; i++){
if(clients[i] == 0){
clients[i] = numClients;
break;
}
}
}
Show method output:
Name: romeo
Rooms: 5
Number of clients: 10
10
6
10
5
The Total number of clients can be found by summation of the clients array.
To make the array dynamic, the linked list data structure can be applied.
What I did to fix this without updating and making new methods is defining values with scanner and putting it into constructor.
public void test(){
Scanner sc = new Scanner(System.in);
System.out.print("Type in the name of Hotel: ");
String name= sc.nextLine();
System.out.print("Type in number of rooms: ");
int numRooms = sc.nextInt();
System.out.print("Type in the number of clients");
int numClients= sc.nextInt();
Hotel h1 = new Hotel(name, numRooms, numClients);
h1.show();
}
I'm trying to make a program with three class files, two Objects files and one Main that accesses both and runs operations. The first object file creates objects with one parameter, and then assigns attributes to itself based on said parameter, for example.
public class People {
private int height, weight;
private String specificPerson;
public People(String person){
this.specificPerson = person;
this.height = person.length * 12;
this.weight = person.length * 40;
}
public int getHeight(){return height;}
public int getWeight() {return weight;}
}
These objects are then stored within the array of another object which has a capacity and an array:
public class peopleIndexer {
private int pcapacity, size;
private String[] peopleArray;
public peopleIndexer(int capacity){
this.pcapacity = capacity;
this.peopleArray = new String [capacity];
}
public int getCapacity(){
return pcapacity;
}
public int[] getInfo(String person){
int[] getInfo = new int[2];
int found = Arrays.binarySearch(peopleArray,person);
getInfo[0] = ?.getHeight();
getInfo[1] = ?.getWeight();//I dont know the object name yet so I put "?" for I am not sure
System.out.println("Person" + person + "is " + getInfo[0] + "tall and " + getInfo[1] + " pounds.");
}
}
What I need to know is how to allow the user to make multiple people in the list with input that I can then allow them to retrieve later, for example:
String user_input;
People user_input = new People("user_input");
So that if the users input were to be jack, ryan, and nick, I would have three objects placed in the peopleIndexer as such:
People jack = new People(jack);
People ryan = new People(ryan);
People nick = new People(nick);
Your People constructor takes only one argument and creates a People object..You do not have setters for some of your private variables in the peopleIndexer class, so best to have your main method as part of the peopleIndexer class.
Your "length" attribute in the People constructor is not initialized or declared anywhere, so let's assume it's not there. You must change your "private String[] peopleArray;" to be "private People[] peopleArray;" in order to have people in the array.
public static void main(String args[]){
Scanner input = new Scanner(System.in);
int capacity;
int peopleCount = 0; //used to keep track of people we have in our array
String person = "";
// get the capacity from the user
System.out.println("Enter the number of people you want to capture: ");
capacity = Integer.parseInt(input.nextLine());
//create peopleIndexer object using the given capacity
peopleIndexer pIndexer = new peopleIndexer(capacity);
while(peopleCount < capacity){
//prompt the user for the "People" name, this is the only attibute we need according to your constructor.
System.out.println("Enter person "+(peopleCount + 1)+" name: ");
person = input.nextLine();
//add a new person into the array
peopleArray[peopleCount] = new People(person);
//increase the number of people captured
peopleCount += 1;
}
}
I'm currently trying to working through a problem with ArrayList.
This is supposed to take the input of the user and customers sales and display the top customer. Yet, I'm having and issue with an inner while.
Using VSCODE. The inner while is throwing an error within the inner if sales.get(j) > largest) stating the > is undefined.
Please, any help would be greatly appreciated.
import java.util.ArrayList;
import java.util.Scanner;
public class TopCusomters {
public static void main(String[] args)
{
ArrayList sales = new ArrayList();
ArrayList customers = new ArrayList();
int numOfItems = 0;
double price = 0;
Scanner in = new Scanner(System.in);
boolean entryComplete = false;
do {
System.println("Customers Names");
customers.add(in.next());
System.println("Sales of the Customer (0 to end):");
price = in.nextDouble();
sales.add(price);
numOfItems++;
}while(price != 0 && mumOfItems < 100);
System.out.println("Please provide values of N");
int topN = in.nextInt();
ArrayList topCustomers = nameOfBestCustomers(sales, customers, topN);
System.out.println(" Top Customers list" + "is" + topCustomers.toString());
}
public static ArrayList nameOfBestCustomers (ArrayList sales,ArrayList customers, int topN)
{
ArrayList bestCustomers = new ArrayList();
sortCustomers(sales,customers);
int i = 0;
while (i)
{
bestCustomers.add(customers.get(i));
i++;
}
return bestCustomers;
}
public static void sortCustomers(ArrayList sales, ArrayList customers)
{
int i = 0;
double temp = 0;
String tempName = "";
while (i)
{
double largest = sales.get(i);
int largestIndex = i;
int j = i;
while (j)
{
if(sales.get(j) > largest)
{
largest = sales.get(j);
largestIndex = j;
}
i++;
}
temp = sales.get(i);
sales.set(i,sales.get(largestIndex));
sales.set(largestIndex,temp);
tempName = customers.get(i);
customers.set(i,customers.get(largestIndex));
customers.set(largestIndex, tempName);
i++;
}
}
}
You are not specifying object types that lists are holding for below declarations ,
ArrayList sales = new ArrayList();
ArrayList customers = new ArrayList();
So when you retrieve objects from list and try to apply operators, Java doesn't know which type its working on. ( Java assumes java.lang.Object and operator > doesn't make sense on Object )
For long term solution , declarations should be changed as below or you can try that after explicit cast too,
List<Double> sales = new ArrayList<>();
List<String> customers = new ArrayList<>();
where Double is java.lang.Double
ArrayList without type will default to ArrayList<Object>, that means that sales.get(j)'s return value is Object. You probably want ArrayList<Double>.
You have multiple syntax errors, for example:
Conditional expression like while (<expr>) { ... } need to evaluate to boolean. while(i) is not a valid expression, see
The while and do-while Statements docs.
do { ... } is not a valid Java construct, most likely you tried to use a do-while loop do { ... } while (<expr>); loop.
You are using rawtype ArrayList. Most likely it should be List<Double>. You need generics to compare sales elements with double largest using auto-boxing, see Lesson: Generics (Updated) docs.
I am trying to build a program that reads in info from a .txt file, which contains 20 individuals. Each person has four fields, the team they belong to, their batting average, and home run totals. I need to add each individual to their team(4 players to each team), total up the team home run totals, and rank the 5 teams in order.
I am able to read the text in properly to a single array, consisting of each individual, but I cannot figure out how to also use this data to create a 2D Array. Using the 2D array I would, put the players on the correct teams, and add their home run totals. I want to sort the home run totals from greatest to smallest for each team, and each individual. I am have done my best to find answers, and to learn on other posts and sites, but I am just stumped with the concept of creating 2D arrays and how to sort them.
Updated explanation:
This is what the info should look like for the single array:
[Team][Name][avg][Home Runs]
Then I JUST want to sort the [Home Runs] column, from greatest to smallest, but don't know how to just access that portion of the array.
The 2D array should look like this:
[Team] [Total Team Home Runs]
Once again, sorting from greatest to smallest.
Example of the .txt file looks like this:
Team: Name: Avg:HR:
MILRyan Braun .31015
STLMatt Adams .28718
PITSterling Marte .26420
CINJoey Votto .30224
CUBAnthony Rizzo .27422
PITAndrew McCutchen .29522
MILAdam Lind .28013
The following class reads in the .txt file and puts it in array.
public class ReadTxt {
static String[] teamm = new String[20];
static String[] name = new String[20];
static int[] avg = new int[20];
static double[] homeRuns = new double[20];
static String teams;
static int i;
public void Players(String[] teamm, String[] name, int[] avg, double[] homeRuns){
String[] team = new String[20];
File txtFile = new File("C:\\Users\\Users Name\\Desktop\\homerun.txt");
try{
Scanner txtScan = new Scanner(txtFile);
while(txtScan.hasNext()){
for(i = 0; i < 20; i++){
teams = txtScan.nextLine();
team[i] = teams;
}
}
}
catch(FileNotFoundException e){
System.out.println("File not found" + txtFile);
}
for (i = 0; i < team.length; i++){
System.out.println(team[i]);
}
}
}
The next class is my attempt at sorting:
public class Sort {
static String[] teamm = new String[20];
static String[] name = new String[20];
static int[] avg = new int[20];
static double[] homeRuns = new double[20];
private int index = 0;
private int US = 0;
static double[] homeRunArray;
public void Players(String[] teamm, String[] name, int[] avg, double[] homeRuns){
homeRunArray[index] = ReadTxt.homeRuns[index];
index++;;
US++;
}
public void selectionSort(){
double temp;
int min;
for(int i = 0; i < US-2; i++){
min = i;
for(int j=i+1; j<= US-1; j++){
if(min !=i){
temp = homeRunArray[i];
homeRunArray[i] = homeRunArray[min];
homeRunArray[min] = temp;
}
}
}
}
public void printArray(double[] homeRuns){
for(int i = 0; i < 20; i++){
System.out.print(homeRunArray[i]);
}
System.out.print("\n");
}
}
I don't get your question, but I think you are kind of stuck in your 2D-Array problem...
I would recommend you to create a class and implement Comparable (or use a Comparator). Something like the code below, or even better, make a real Player class. This is much easier to understand.
public class Sorter {
public static void main(String[] args) {
try {
Scanner scanner = new Scanner(new File("team"));
List<SortableLine> lines = new ArrayList<SortableLine>();
while(scanner.hasNext()) {
lines.add(new SortableLine(scanner.nextLine()));
}
Collections.sort(lines);
for(SortableLine line : lines) {
System.out.println(line.line);
}
} catch(FileNotFoundException e) {
System.err.println("File not found");
}
}
private static class SortableLine implements Comparable<SortableLine> {
private String sortCol;
private String line;
private SortableLine(String line) {
this.line = line;
this.sortCol = line.substring(24, 26);
}
public int compareTo(SortableLine other) {
return sortCol.compareTo(other.sortCol);
}
}
}
I have created two classes, one called "Bucket", and the other called "Player".
In "Bucket", I have a constructor method that creates a virtual bucket (i.e. small array) that contains three values - 1, 1, and 1. As well, I created a method to get the bucket array.
In the "Player" class, I have created a method that uses a larger array (I have called this larger array "ArrayOfBuckets"), which uses a loop to store a new bucket at each index value, up until a certain point (when i>NumberSticks). However, when I try to set
ArrayofBuckets[i] = bucketInstance.getBucket();
I get an error from Eclipse, saying that "Type mismatch: cannot convert from Bucket to int". I have spent an hour trying to solve this, to no avail. Any help would be really nice. Thanks a lot, and here is all the code that is used:
The Player Class:
import java.util.Scanner;
public class Player {
Scanner scan = new Scanner(System.in);
public String name;
private int pType;
private int[] ArrayOfBuckets;
public Player(String tempName)
{
this.name = tempName; //this. is unneccessary
}
public void ArrayOfBuckets(int NumberSticks) //this is a constructor method and creates the arrays that contains a
{
ArrayOfBuckets = new int[NumberSticks];
int i = 0;
while(i<NumberSticks)
{
Bucket bucketInstance = new Bucket();
ArrayOfBuckets[i] = bucketInstance.getBucket();//new Bucket(); //ADD THIS
i++;
}
}
and the Bucket Class:
import java.util.Random;
public class Bucket {
// private int[][] largeArray = null; //WTF DO I DO HERE
private int AIChoiceStick;
private int[] bucket;
private Random random = new Random();
private int CurrentScore[] = new int[51]; //at max, if 100 sticks are initially chosen, then each player takes at max 50 sticks,
private int h = 0; //^so why not have one more in case
public Bucket()
{
bucket = new int[3];
bucket[0] = 1;
bucket[1] = 1;
bucket[2] = 1;
public int[] getBucket()
{
return bucket;
}
You're speaking about a two-dimensional array.
private int[][] ArrayOfBuckets;
Your ArrayOfBuckets (should be just buckets according to naming conventions) is an array of arrays, so it gets two sets of square brackets.
Then the initialization:
ArrayOfBuckets = new int[NumberSticks][3];
By the way, if you want to have room for 50 elements in an array, then initialize it new int[50] so it will have indexes 0 through 49.