Java - Add user input to 3 arrays? (Parallel Arrays) - java

So I have 3 Parallel Arrays. I need a method that will allow for the user to add to these arrays. As well as another method to be able to identify a certain item and remove it. As well as another method to identify an item and edit/change the contents of that item in the array.
These are my 3 arrays...
I need to add the brand name of the computer to:
String[] computerBrand
I need to add the processor speeds to:
double[] computerSpeed
and I need to add the computers price to:
double[] computerPrice
The first array (string) holds the brand name of computer. (Dell)
the second array (double) holds the processor speed of the computer. (2.5)
the third array (double) holds the price of the computer. (1500)
How do I take user input and put them in the array?
(I CANNOT USE ARRAYLISTS)

For taking input look at the Scanner class.
Scanner
For adding the values to your arrays just do this:
computerBrand[i] = <value_brand>;
computerSpeed[i] = <value_speed>;
computerPrice[i] = <value_price>;
i++;
where these 3 values are the one read by the Scanner,
and i is some index/counter integer variable.
But first make sure you initialize your arrays e.g.:
computerBrand = new String[100];
computerSpeed = new double[100];
computerPrice = new double[100];

// Create the arrays
// (anyway It's better to use double for price and speed)
String[] computerBrand = new String[5];
String[] computerSpeed = new String[5];
String[] computerPrice = new String[5];
//
// Now you have 3 arrays which contains computer info
// A Computer with index 0 will contains his name in computerBrand[0], speed in computerSpeed[0] and price in computerPrice[0]
// Put info into the arrays, here is random in the real code you get the info from the user.. you can understand it's the same way you use for standard arrays (it's anyway arrays)
for (int i = 0; i < 5; ++i)
{
computerBrand[i] = "Computer " + i;
computerSpeed[i] = String.valueOf(Math.floor(Math.random()*10));
computerPrice[i] = String.valueOf(Math.floor(Math.random()*500));
}
// print info
//
for (int i = 0; i < 5; ++i)
{
// As you can see, i have used the same index in every array
System.out.println(
"Brand: " + computerBrand[i] +
" Speed: " + computerSpeed[i] +
" Price: " + computerPrice[i] + "E"
);
}
By reading the code you can understand a simple thing: every array will share the same index.
For your real code, you just need to get name, price and speed of the pc and put everything in the arrays using the same index. If you use it in separate code you can store the last index and use it (more info depends on how it should work.).

Related

How to delete and add an element from an array based of the user input in JAVA?

String[] courseNames=new String[numbOfCourses];
Double[] courseCredits=new Double[numbOfCourses];
String[] gradeLetters= new String[numbOfCourses];
I asked the user to enter some course names,credits and letters and I put them in each array like:
courseNames[j]= keyboard.next();
courseCredits[j]=keyboard.nextDouble();
gradeLetters[j]=keyboard.next();
I expect the output to be like
Before:
course numb course name course credit course Grade
1 C 3.0 A
2 B 3.0 B
3 D 3.0 A
user input: 2
After:
course numb course name course credit course Grade
1 C 3.0 A
2 D 3.0 A
Firstly, I strongly encourage you to use some kind of List since it will be much easier to achieve your desired effect.
To "delete" an item from the array you could create a method similar to this:
void deleteCourseAtIndex(int index) {
courseNames[index]= null;
courseCredits[index]= null;
gradeLetters[index]= null;
}
And then when you are doing your printf()'s to display the content of the arrays:
for (int i = 0; i < courseNames.length; i++) {
if (courseNames[i] != null)
//printf() with whatever formatting you have
}
To add a new course, you would have to have enough indices in your arrays to store a new course. This is why I would advise you to use a List. Nonetheless:
//This method adds course info to the arrays and returns a boolean whether it was successfully added
//Precondition: all arrays are the same length
boolean addCourse(String[] cNames, double[] cCredits, String[] gLetters) {
boolean added = false;
for (int i = 0; i < courseNames.length; i++) {
if (courseNames[i] == null) {
courseNames[i]= cNames;
courseCredits[i]= cCredits;
gradeLetters[i]= gLetters;
added = true;
}
}
return added;
}
With a List, you don't have to deal with the issue of running out of space because they don't have a fixed size when you initialize them. To do this with Lists, try something like this:
ArrayList<String> courseNames= new ArrayList<String>();
ArrayList<Double> courseCredits = new ArrayList<Double>();
ArrayList<String> gradeLetters = new ArrayList<String>();
Note that I used Double instead of double because double is a primitive and ArrayLists can't use primitives. Use the wrapper classes Integer, Double etc. when using Lists.
Now when you accept keyboard input:
courseNames.add(keyboard.next());
courseCredits.add(keyboard.nextDouble());
gradeLetters.add(keyboard.next());
And you don't even need to loop through each index!
Even better, you could make a completely new class called Course (as Andreas suggested) and make an ArrayList.

Java - Trouble reading data from a list of 2D arrays

I have created a list of 2D arrays containing randomly generated number values for different locations.
public static int Prices[][] = new int[Cities.length][ItemNames.length];
public static List<int[][]> CityPrices = new ArrayList<int[][]>();
public static void NewDay()
{
for(int i = 0; i<Cities.length; ++i)
{
Prices[i] = PriceGenerator.ReturnPricesForCity(i);
//This method returns an array of random integers
}
CityPrices.add(Prices);
}
But then later when I want to retrieve the price history for a specific item for the amount of days passed, it returns the same value for each day
int Prices[] = new int[GlobalVariables.CityPrices.size()];
String sTest = "";
for(int i = 0; i < Prices.length; ++i)
{
Prices[i] = GlobalVariables.CityPrices.get(i)[spinCity.getSelectedItemPosition()][spinItem.getSelectedItemPosition()];
sTest = sTest + Prices[i] + ",";
}
In this case, the values returned by sTest was : 6055,6055,6055,6055,6055, for five consecutive days.
If I would for instance add a day, the values would change to a range of a new number, which in this case was : 7294,7294,7294,7294,7294,7294,
Please show me what I am doing wrong, as I have been trying to figure this one out the past 4 days with no luck.
Every element in your CityPrices list is the same: in each case, you are adding the Prices two-dimensional array. Your loop modifies Prices[i], but it doesn't change Prices, which is still a reference to the same two-dimensional array right the way through.
I think you're imagining it will pass the contents of the array in its current state, but it doesn't: it passes a reference to the array to the .add() method, so any subsequent changes to the array will be reflected in the contents of CityPrices.
If at the end of your loop you try
CityPrices.get(0) == CityPrices.get(1)
you'll see it returns true.
In the assignment: Prices[i] = GlobalVariables.CityPrices.get(i)[spinCity.getSelectedItemPosition()][spinItem.getSelectedItemPosition()]; you are basically referencing an int[][] at the same index for both dimensions.
On top of that, the spinCity.getSelectedItemPosition() invocation might be returning the same index at every iteration of your loop, hence your identical values.
It's hard to assume anything further as you haven't posted the code for spinCity.

How can I store a bunch of double in a single double?

I edited my post.
:: New logic problem, everytime I input only 1 integer the += only prints 0.
System.out.print("\nEnter the property code: ");
sPropertyCode = input.next();
bError = false; //set to false
dTotalCommission += dCommissionRate;
dTotalSales += dSellPrice;
if (sPropertyCode.equalsIgnoreCase("R"))//if r or R dRate will store 7,...perform calculation for dCommissionRate
{
dRate = 7;
dCommissionRate = dSellPrice * (dRate/100);
System.out.print("Total commission on this property is $" +dCommissionRate);
} //this works and prints the calculated amount of rate but when it is going to the last line....
if (sYesOrNo.equalsIgnoreCase("n"))
{
System.out.println(sApplicationReport);//prints the Summary Report
System.out.println ("----------------------------------------------------------");
System.out.println ("Total property sales: $" + dTotalSales);//all the stored values for dSellPrice will be added and printed
System.out.println("Total Commissions: $"+ dTotalCommission);//This part only prints 0.00 instead of the calcuated dCommissionRate
break;
}
dTotalPrice += dSellPrice
means : dTotalPrice = dTotalPrice + dSellPrice
But if you want to store 10000 and 20000 in a single variable , you can use an arrayList :
Example :
ArrayList<Double> myValues = new ArrayList<Double>();
myValues.add(10000 );
myValues.add(200O00 );
// etc.
If you want to show them :
for(int i = 0 ; i < myValues.size(); i++){
Double mySingleValue = myValues.get(i);
System.out.println(mySingleValue.toString());
}
Hm. It's kind of hard to follow your thinking, but here is my best shot.
Your code here (dTotalPrice += dSellPrice) Will add the value of dSellPrice to dTotalPrice.
aside from a semicolon you aren't missing anything.
Instead of trying to store multiple doubles in a single double variable, why not try and store your multiple doubles in an array? Therefore you could store your multiple number values in this array and then pick out the ones you want.
You'd just reassign the variable. No problem.
Try it!
double dada = 10.7;
/* run jump play */
dada = 3.141592653589;
However, what makes more sense is to use an array.
declare a double array -
double[] myNumbers = {28.3, 21.2};

Reading from CSV who has char and int

I got a task. The input of the Java Decathlon program is a CSV-like text file. The task is to output an XML file with all athletes in ascending order of their places, containing all the input data plus total score and the place in the competition (in case of equal scores, athletes must share the places, e.g. 3-4 and 3-4 instead of 3 and 4)
This is my cvs file:
Jana Kari;12.61;5.00;9.22;1.50;60.39;16.43;21.60;2.60;35.81;5.25.72
Eva Narun;13.04;4.53;7.79;1.55;64.72;18.74;24.20;2.40;28.20;6.50.76
Maja Hope;13.75;4.84;10.12;1.50;68.44;19.18;30.85;2.80;33.88;6.22.75
Kirke Kanda;13.43;4.35;8.64;1.50;66.06;19.05;24.89;2.20;33.48;6.51.01
I got these constants for each decathlon event
double[] A = new double[]{25.4347,0.14354,51.39,0.8465,1.53775,5.74352,12.91,0.2797,10.14,0.03768};
double[] B = new double[]{18,220,1.5,75,82,28.5,4,100,7,480};
double[] C = new double[]{1.81,1.4,1.05,1.42,1.81,1.92,1.1,1.35,1.08,1.85};
Formula for points is
Points = INT(A(B — P)^C) for track events (faster time produces a better score)
Points = INT(A(P — B)^C) for field events (greater distance or height produces a better score)
"P" is persons records (from cvs). I dont really understand how to read properly from file that it would allow me to do calculations with numbers only. Should i use two dimensional array for cvs file ? Its very confusing and im stuck.
EDIT
Well i believe for outputing later to xml file one dimensional array is better. The point of my task is code simplicity, but CVS file may be expanded to N lines so i never know how much rows it will have. I want to use number array in this code:
double[] A = new double[]{25.4347,0.14354,51.39,0.8465,1.53775,5.74352,12.91,0.2797,10.14,0.03768};
double[] B = new double[]{18,220,1.5,75,82,28.5,4,100,7,480};
double[] C = new double[]{1.81,1.4,1.05,1.42,1.81,1.92,1.1,1.35,1.08,1.85};
double PTS;
double finalscore;
for (int i = 0; i < P.length;i++ )
{
finalscore=0;
if (i == 0)
{
PTS = A[i]* Math.pow((P[i]-B[i]),C[i]);
}
else if (i == 4)
{
PTS = A[i]* Math.pow((P[i]-B[i]),C[i]);
}
else if (i == 5 || i == 9)
{
PTS = A[i]* Math.pow((P[i]-B[i]),C[i]);
}
else
{
PTS = A[i]* Math.pow((P[i]-B[i]),C[i]);
}
finalscore = finalscore + PTS;
}
System.out.println(finalscore);
}
}
Where P[] would be array first lane of number without name.
P.S it seems code above gives me result NaN when i use
double[] P = new double[]{12.61,5.00,9.22,1.50,60.39,16.43,21.60,2.60,35.81,5.272};
Yes, you have the right idea - you can use a two dimensional array. I would also recommend you create a class called Person, as this is Java programming and Java is object-oriented, but if you have not studied creating multiple classes yet, you can skip that bit and just do it with two arrays, one one-dimensional array for the names and one two-dimensional array for the numbers.
For the one-dimensional array approach
public class Person {
String name;
double[] scores;
int minutes;
int seconds;
int hundredths;
public Person(String line) {
String[] splitted = line.split(";");
name = splitted[0];
// now fill in the other fields
for(int i = 1; i < splitted.length - 1; i++) {
scores[i - 1] = Double.parseDouble(splitted[i]);
}
String times = splitted[splitted.length - 1].split("\\.");
minutes = Integer.parseInt(time[0]);
// etc. - fill in the rest
}
}
(Actually, this might be wrong, because I assumed most of the numbers are scores, but I guess they are really seconds and hundredths of a second. It doesn't really matter, unless you could have a time over one minute for those events.)
Then you need to have an array of Person objects in your other class - let's make it quite big so that it will be big enough hopefully:
Person[] array = new Person[10000];
Now have a loop, and whenever you read a line from the file you just call the constructor.
array[j] = new Person(line);
Nice approach, isn't it?

List.add() Class Expected

I'm taking a Java class in College. My instructor is actually a teacher for languages derived from C, so she can't figure out what's going on with this piece of code. I read on this page http://docs.oracle.com/javase/6/docs/api/java/util/List.html that I could use the syntax "list[].add(int index, element)" to add specific objects or calculations into specific indexes, which reduced the amount of coding needed. The program I'm looking to create is a random stat generator for D&D, for practice. The method giving the error is below:
//StatGenrator is used with ActionListener
private String StatGenerator ()
{
int finalStat;
String returnStat;
//Creates an empty list.
int[] nums={};
//Adds a random number from 1-6 to each list element.
for (int i; i > 4; i++)
nums[].add(i, dice.random(6)+1); //Marks 'add' with "error: class expected"
//Sorts the list by decending order, then drops the
//lowest number by adding the three highest numbers
//in the list.
Arrays.sort(nums);
finalStat = nums[1] + nums[2] + nums[3];
//Converts the integer into a string to set into a
//texbox.
returnStat = finalStat.toString();
return returnStat;
}
My end goal is to use some kind of sorted list or method of removing the lowest value in a set. The point of this method is to generate 4 random numbers from 1-6, then drop the lowest and add the three highest together. The final number is going to be the text of a textbox, so it is converted to a string and returned. The remainder of the code works correctly, I am only having trouble with this method.
If anyone has any ideas, I'm all ears. I've researched a bit and found something about using ArrayList to make a new List object, but I'm not sure on the syntax for it. As a final note, I tried looking for this syntax in another question, but I couldn't find it anywhere on stackoverflow. Apologies if I missed something, somewhere.
'int nums[]' is not a List, it's an array.
List<Integer> intList = new ArrayList<>();
creates a new ArrayList for example.
You can access Elements in the list directly with the following Syntax :
intList.get(0); // Get the first Element
You can sort Lists with the Collections class :
Collections.sort(intList);
Here are some informations about Collections in Java : http://docs.oracle.com/javase/tutorial/collections/
Arrays are fixed size, so you need to allocate space for all the slots at the start. Then to put numbers into the array assign to nums[i]. No add() method needed.
int[] nums = new int[4];
for (int i = 0; i < 4; i++)
nums[i] = dice.random(6) + 1;
Arrays.sort(nums);
finalStat = nums[1] + nums[2] + nums[3];
Alternatively, if you really want a dynamically-sized array, use an ArrayList. An ArrayList can grow and shrink.
List<Integer> nums = new ArrayList<Integer>();
for (int i = 0; i < 4; i++)
nums.add(dice.random(6) + 1);
Collections.sort(nums);
finalStat = nums.get(1) + nums.get(2) + nums.get(3);
Notice how different the syntax is due to ArrayList being a class rather than a built-in type.
nums[].add(i, dice.random(6)+1); //Marks 'add' with "error: class
expected"
You are trying to use add on an array. List is a dynamic array, but that doesn't mean that array == List. you should use List instead.
List<Integer> nums=new ArrayList<Integer>();
//Adds a random number from 1-6 to each list element.
for (int i; i > 4; i++)
nums.add(i, dice.random(6)+1);
You're mixing arrays and lists.
Have a look at the tutorial:
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
http://docs.oracle.com/javase/tutorial/collections/index.html

Categories