In a program I'm writing, I currently have a class that looks like...
public class Plane {
int[][] planes = new int[5][5];
}
An array is created in this class that has 5 rows and 5 columns. Each row of the array is supposed to contain the details of different 'planes', which are just lines. Each column will contain a different value that is related to the line that I'll have to access later, such as the X and Y values of its start point and its end point, its slope, its y-intercept, etc. In the beginning of the program, though, the user will have the option to create as many lines as they want, and they are requested for the details of that plane, which is currently stored in the "planes" array.
This program would probably be a lot neater if, instead of having a huge array, and creating a new row in that array for every line they wanted to create, I want to create a new "plane" object, and each object will contain the start and end point, slope, and y-intercept details of itself.
The code I have in my main class currently prompts the user, asking them if they want to create a new line. If they say yes, they are then prompted to enter the necessary information about it. After entering the information, they're again prompted, asking if they'd like to create another line, and it repeats. How could I restructure my program to create a new class for each line the user would want to make? How would I reference the variables of those classes when I have to assign values to them? How would I keep track of the classes created?
Any help is appreciated!
Related
This question already has answers here:
Sort a file with huge volume of data given memory constraint
(14 answers)
Closed 2 years ago.
I have a text file that has text on each line, for example:
1245 Dog Husky
2356 Cat Tabby
3476 Dog Pug
with a huge amount of kind of arbitrary data repeated per line, about 10,000 lines, for the sake of argument, lets say it tends to infinity.
I have code that reads this data and stores it in an object, pseudo code follows;
Pet P;
lineInput = reader.readLine(); //where reader is reading the above mentionedfile
P.id = lineInput.split('\t')[0]
P.type = lineInput.split('\t')[1] //Assigning the parts of the line to it's relevant data members
P.breed = lineInput.split('\t')[2]
Now here's the problem, considering I need to be able to sort, search and display these values as fast as possible, I don't know what my best option is, I came up with two methods which can be seen below
Method 1: Store all the Objects in an array list based on their starting id number
ArrayList<Pet> idStartsWith1;
if(P.id starts with 1)
idStartsWith1.add(P); // "1245 Dog Husky" will be added here
ArrayList<Pet> idStartsWith2;
if(P.id starts with 2)
idStartsWith2.add(P); // "2356 Cat Tabby" will be added here
ArrayList<Pet> idStartsWith3;
if(P.id starts with 3)
idStartsWith3.add(P); // "3476 Dog Pug" will be added here
I think this would be the faster method, as these arraylists are already in the process memory, but I fear that it would overload the memory, and cause issues. (Remember, the number of lines in the text file tends to infinite)
Method 2:Write all the Objects to a .dat file based on their starting id number
Writer writer1 = new Writer("idStartsWith1.dat"); //writer1 will write to file "idStartsWith1.dat"
if(P.id starts with 1)
writer1.write(P); // "1245 Dog Husky" will be writen to this file
Writer writer2 = new Writer("idStartsWith2.dat"); //writer2 will write to file "idStartsWith2.dat"
if(P.id starts with 2)
writer2.write(P);
Writer writer3 = new Writer("idStartsWith3.dat"); //writer3 will write to file "idStartsWith3.dat"
if(P.id starts with 3)
writer3.write(P);
This will prevent the process memory from being overloaded but I fear that having to open, then read, then close the file each time I need to search and display a Pet, will add significant delays to the runtime.
Which of these two methods would work better? or is there another more efficient method that would not occur to a java novice like me?
Data of many applications are small enough to fit into main memory of a desktop computed. When your file has 1 GB, then you need some 3 GB of main memory and that's no problem for most desktops. On mobile, it's different.
Nothing can be as fast as working with main memory, when done right. ArrayList is not usable for searching, but a Map is.
You can use a database instead and you probably should. It's much slower than having all data in main memory, but still very fast, assuming you do it right (learn about indexes etc.). Most database can import a CSV file directly and are able to answer all your queries - filtering, sorting and joining other tables are what databases exists for.
I am writing a program for calculating pay for overtime hours and non-overtime hours. This is for my Java course, so the requirements are that I must have two classes and three functions. The first class does not have a main and contains three functions. It's basically where the calculation is done.The second class is for I/O, where you input your values through the Scanner and display the result.
I think I am almost done, however, I cannot get my total pay amount to return in my I/O class, it comes out as 0.0. How can I get it to properly return my function getPayAmount() value?
Here is the image of my first class, the three functions: constructor, payCalculation, and getPayAmount()
Here is the image of my second class, where the I/O is done.
Again, I'd like to know how I can return the value from my getPayAmount() function to print at my last sys.out statement.
Thanks so much in advance for your help, I'm so anxious to be done with this!
try creating paycheck calculation after getting the input. move line 11 to 25
PayCheckCalculation myPay= new PayCheckCalculation (hours,rate);
myPay.payCalculation(rate,hours);
When you are creating the object mypay, the parameters are rate and hours have value as 0. Instead you want to instantiante the object with the values you get as input and you should get the right answer. Also you should use this in your class methods to refer to current object.
You did not call the method paycalculation method in your code as well.
In line 11 of your main function, you're creating the mPay object with (0,0) as initial values, you could initiate the object, you get the required information from the console or user, then the variables in the object will have updated values in them.
You could create or initiate the object after line 25 so that, you will have all the required data to calculate the payroll information from the user.
To understand an error, always check the flow of your code, this way you can find most of your errors.
These are the specs for the program I need to complete. Could someone please help me!! I really need to get this program done! Will take any help/advice I can get! Thank you all so much!
You must create two programs named Board and ConFour that have the
following criteria:
1) Proper Introduction
2) Comments that accurately describe the program features
3) Board should have one attribute; a two dimensional array of
character values representing the Connect Four game board. Be sure
to include a constructor (without parameters) that instantiates the
2D-array with 6 rows and 7 columns
4) Board should contain at least four methods. The first method should
be setBoard() which adds an empty character value to every position in the board. The second method, setPosition(), should place the character representing a player (X or O) in the column of their choosing. The third method named checkWinner() should check the board to see if there are four of the same character (X or O) in a row, column or either diagonal. Lastly, printBoard(), should print the contents of the board.
5) ConFour should represent the game play. Have the user(s) enter
START to start the game (they should be able to continuously play after each game)
6) Start each turn by printing the board followed by asking the user to
enter the column they want (be sure to alternate players). If the user enters an incorrect column number, make them re-enter. First player to get four in a row, column or either diagonal is the winner.
Here is a little bit of my thoughts:
To start off, try to make algorithms that check for 4 Xs/Os in a row, which should be 4 for each player. You could also just make 4 algorithms that require you to input the number you are checking for. The directions you need to check are horizontal (check array[i][x+1], where i is the constant in the for loop and x is the number you find to be X or O), vertical (check array[x+1][i] ), right-facing diagonal (check array[i+1][x+1] ), and left-facing diagonal (check array[i-1][x-1].
To print the board, just use 2 for loops that print the values of the array.
For the intro, use a bunch of System.out.println() statements.
The entering of coins is the weird part. You have to create height variables (Or a height function) that stores/checks the height of the coins, then places it on top/next to the other coin. Then check if anyone wins and move on the next player. Keep repeating it until someone wins. Warning: Do not use a while loop. They can't check more than one boolean at a time (but you could put a bunch of if(check) {
boolean itsalltrue = true;
}s, too.
Well, that's all that I can think of (I deliberately did not write the code because I would like you write your own). Enjoy!
Is this for a class? Did you literally just copy and paste the assignment? Try spending some time looking through the notes provided for you, or search more specific questions here. Here's an example of a similar question with code:
Simple 2d array java game
I posted here a few weeks ago regarding a project I have for work. The project began as creating a simple little program that would take an incoming ACH file and read each line. The program would also ask a user for a "reason code" and "bank" which would affect the next step. The program would then reformat all the data in a certain way and save it to an external file. For those that don't know, an ACH is simply a text based file that is in a very concrete format. (Every character and space has a meaning.)
I have completed that task using a few GUI items (Jcombobox, JFileChooser, etc), string array lists, buffered reader/writer, and lots of if/else statements.
The task has now been expanded to a much more complicated and I don't know exactly how to begin, so I thought I would seek the communities advice.
When an ACH file comes in it will be in a format that looks something like this:
101 100000000000000000000000000000
522 00000202020382737327372732737237
6272288381237237123712837912738792178
6272392390123018230912830918203810
627232183712636283761231726382168
822233473498327497384798234724273487398
522 83398402830943240924332849832094
62723921380921380921382183092183
6273949384028309432083094820938409832
82283409384083209482094392830404829304
900000000000000000000000000000000
9999999999999999999999999999999999999
9999999999999999999999999999999999999
(I will refer to each line by " " number, for example "1 number" are the lines that begin with 1)
The end result is that the lines of data are maniuplated and put into "batches". The output file begins with the "1 number"
and then contains a batch with the format of
5
6
8
5
6
8
5
6
8
We continue using the same "5 number" until all sixes that were below it in the original file have been written, then we go to the next "5" and work with the "6" below it.
So, my project now is to create a full GUI. After the user inputs the file the GUI will have some type of drop down box or similar list of all the "6" numbers. For each number there should be another drop down box to choose the reason code (there are 7 reason codes).
Basically the ultimate objective is:
Display all the "6" numbers and give the user the ability to choose a reason code for each.
Allow the user to only select a certain amount of the "6" numbers if they wish.
Is it possible for me to do this using Buffered Reader/ Writer? I currently save the values into Array Lists using the following code:
while((sCurrentLine = br.readLine()) !=null)//<---------This loop will continue while there are still lines to be read.
{
if (sCurrentLine.startsWith("5")){//<------------------If the line starts with "5"..
listFive.add(sCurrentLine);//<-------------------------Add the line to the array list "listFive".
countFive++;//<---------------------------------------------Increase the counter "countFive" by one.
}else if (sCurrentLine.startsWith("6") && countFive==1){//<---------If the line starts with "6" and countFive is at a value of 1..
listSix.add(sCurrentLine);//<---------------------------------------Add the line to the array list "listSix".
}else if (sCurrentLine.startsWith("6") && countFive==2){//<-----------------If the line starts with "6" and countFive is at a value of 2..
listSixBatchTwo.add(sCurrentLine);//<--------------------------------------Add the line to the array list "listSixBatchTwo".
}else if (sCurrentLine.startsWith("6") && countFive==3){//<-----------------------If the line starts with "6" and countFive is at a value of 3..
listSixBatchThree.add(sCurrentLine);//<------------------------------------------Add the line to array list "listSixBatchThree".
}else if (sCurrentLine.startsWith("6") && countFive==4){//<------------------------------If the line starts with "6" and countFive is at a value of 4..
listSixBatchFour.add(sCurrentLine); //<--------------------------------------------------Add the line to array list "listSixBatchFour".
}else if (sCurrentLine.startsWith("8")){//<-----------------------------------------------------If the line starts with "8"..
listEight.add(sCurrentLine);//<----------------------------------------------------------------Add the line to array list "listEight".
}else if (sCurrentLine.startsWith("1")){//<-----------------------------------------------------------If the line starts with "1"..
one = sCurrentLine;//<-------------------------------------------------------------------------------Save the line to String "one".
}else if (sCurrentLine.startsWith("9") && count9 == 1){//<---------------------------------------------------If the line starts with "9" and count9 is at a value of 1..
nine = sCurrentLine;//<-------------------------------------------------------------------------------------Save the line to String "nine".
count9 = 0;//<--------------------------------------------------------------------------------------------------Set count9 to a value of 0.
}else if (sCurrentLine.startsWith("999") && count9 == 0){//<-----------------------------------------------------------If the line starts with "999" and count9 is at a value of 0..
listNine.add(sCurrentLine);//<---------------------------------------------------------------------------------------Add the line to array list "listNine".
}else{
}
}
If anyone can point me where I can get started I would be very grateful. If you need more information please let me know.
Update:
Here is an example of my JOptionPane with decision making.
String[] choices = {"Wells Fargo", "Bank of America", "CitiBank", "Wells Fargo Legacy", "JPMC"};
String input = (String) JOptionPane.showInputDialog(null, "Bank Selection", "Please choose a bank: ", JOptionPane.QUESTION_MESSAGE, null, choices, choices[0]);
if (input.equals("Wells Fargo"))
{
bank = "WELLS FARGO";
}else if (input.equals("Bank of America")){
bank = "BANK OF AMERICA";
}else if (input.equals("CitiBank")){
bank = "CITI BANK";
}else if (input.equals("Wells Fargo Legacy")){
bank = "WELLS FARGO LEGACY";
}else if (input.equals("JPMC")){
bank = "JPMC";
}
}else{
}
Let's assume I wanted to use the Buffered Writer to save all of the "6" numbers into a String array, then put them into a drop down box in the GUI. How could I accomplish this?
Can you use the input from Buffered Writer in a GUI..
Well, a BufferedWriter is not used to get input but rather to output information, but assuming that you meant a BufferedReader, then the answer is yes, definitely. Understand that a GUI and getting data with a BufferedReader are orthogonal concepts -- they both can work just fine independently of the other. The main issues involving reading in data with a Bufferedhaving a GUI
Say a JOptionPane for example.
I'm not sure what you mean here or how this relates.
If yes, then how could I go about doing that? In all the examples I have seen and tutorials about JOptionPane everything is done BEFORE the main method. What if I need if statements included in my JOptionPane input? How can I accomplish this?
I'm not sure what you mean by "everything is done before the main method", but it sounds like you may be getting ahead of yourself. Before worrying about nuts and bolts and specific location of code, think about what classes/objects your program will have, and how they'll interact -- i.e., what methods they will have.
I believe I just had an idea of how I need to proceed first. Can someone please verify? 1. Create static variables representing the lines that will be read. (Such as a static ArrayList.
No, don't think about static anything off the bat, since once you do that, you leave the OOP realm and go into procedural programming. The main data should be held in instance variables within a class or two.
Create the actual GUI, outside the main Method.
I'm not sure what you mean "outside the main method", but the GUI will consist of multiple classes, probably one main one, and an instance of the main class is not infrequently created in the main method, or in a method called by the main method, but queued onto the Swing event thread.
Create the Buffered Reader which will write to the variables mentioned in #1, inside the main method.
Again, I wouldn't do this. The main method should be short, very short, and its reason for existence is only to start your key objects and set them running, and that's it. Nothing critical (other than just what I stated) should be done in them. You're thinking small toy programs, and that's not what you're writing. The reader should be an instance variable inside of its own class. It might be started indirectly by the GUI via a control class which is a class that responds to GUI events. If you need the data prior to creation of the GUI, then you will have your main method create the class that reads in the data, ask it to get the data, and then create your GUI class, passing the data into it.
I've been reading up on it, but every question I've found has asked for slightly different things, such as only wanting a single letter for their array, or in a different language (I'm new and only learning java at the moment), so here I am.
I want to set up an array that uses the user's input for their names.
What I have so far is this, I'm assuming this is the declaration line, where later I use an input line to define a value within the array (which I also am unsure how to do)
String[] array = {"name"};
But I don't know how to for example print.out the object or keep up with which name will be what value. I appreciate your time taken to teach me!
EDIT for further clarification. I'm trying to write up a small app that asks the user for numerous names, addresses, and phone numbers (Type name -> Type name's address -> type name's phone number, ask if they want to add another person, if yes then go back to asking for another name)
I am unsure how to set up a String array or how to use it throughout. However, thanks to your input and coming back after some fresh air, I have a better idea how to word it for google. Thank you guys for your help, even if it was just to gesture a better articulated question.
An array is a sequence of values. You have created an array of Strings that is one String long. To access the value at a specific of an array, use array subscript notation: the name of the array followed by a pair of square brackets ([]) with the index in between them.
String[] anArrayOfStrings = {"string0", "string1", "string2"};
anArrayOfStrings[0]; //the first element
System.out.println(anArrayOfStrings[1]); //print the second element
anArrayOfStrings[2] = "new string value"; //assign the third element to a new value
if (anArrayOfStrings[0].equals("string0") //evaluate the first element and call a method
{
//this block will execute anArrayOfStrings[0] is "string0"
}
anArrayOfStrings[3]; //error, index out of bounds
Simply declaring the array would be
String[] names;
In your code you both declare and assign it in the same line by using an initializer list.
To assign individual elements, use the [] notation. Note that once you initialized you list to be only one String long, it cannot become longer than without be re-assigned. To declare an array of any size, you can use:
String[] arrayWithInitialSize = new String[5]; //holds five strings, each null to begin with