Comparing The Index and Values of Two Arrays - java

I created 4 arrays to store employee-data (ID, Name, Age, Salary).
String[] empID = new String[arrayLength];
String[] empName = new String[arrayLength];
int[] empAge = new int[arrayLength];
double[] empPay = new double[arraylength];
I sorted the salary arrays in ascending order.
Arrays.sort(empPay);
I want the index of the elements in the sorted array (empPay) against the original array (tempPay) similar to the code below.
double[] price = {12,4,65.89,33.5,24,90};
double[] pr = {4,12,24,33.5,65.89,90};
int[] pos = new int[6];
int prCount = 0;
do {
for (int i=0;i<price.length;i++) {
if (pr[prCount] == price[i]) {
pos[prCount] = i;
prCount++;
}
}
} while (prCount<pr.length);
System.out.println(Arrays.toString(pos));
When I apply this logic to my code, I get an "IndexOutOfBoundException"
...
inPay = scanner.nextDouble();
for (...) {
empPay[count] = inPay;
tempPay[count] = inPay;
}
Arrays.sort(empPay);
int[] index = new int[arrayLength];
int listCount = 0;
do {
for (int j=0;j<tempPay.length;j++) {
if (empPay[listCount] == tempPay[j]) {
index[listCount] = j;
listCount++;
}
}
} while (listCount<empPay.length);
System.out.println(Arrays.toString(index));
Why does the logic work in the first code and not the second. I want to display all employee information properly aligned.
Please, Kindly avoid objects or collections or other sophisticated approach to the problem. I teach Grade 9 kids.

Related

How to check the equal indexes of two different Arrays and put the correct value

Considering I have two arrays for example:
String [] countrys = {"USA", "AUSTRALIA"}; // indexes 0,1
String [] numberStates = {"50", "6"}; //indexes 0,1
I am a little amateur in this of the arrays and assign the correct value to equal indexes.
What I am looking for is to assign the correct value, for example, from the US country, assign 50 states and the next one is Austrlia to assign the 6 states.
I have searched for similar tutorials, but I still do not have a clear idea how to assign the correct indexes of 2 arrays.
//complete code snippet
Unit<Length> AddCorrectNumberStateToCountry = null;
String queryCountry = “USA”
String[] countrys = {"USA", "AUSTRALIA"};
String[] numberStates = {"50", "6"};
for(int t = 0; t < countrys.length; t++) {
if (queryCountry.contains(countrys [t])) {
AddCorrectNumberStateToCountry = STATES.plus(?????);
//here need know put exactly numberStates value by check index STATES.plus(?)
}
}
I apologize to Elliott Frisch, he was right, my mistake was mine
For some mysterious reason, the value of states in number 1 threw me nuller point
double [] numberStates = {1 /* <---- nuller point
i change to 0 and solve my problem */,
50, 6};
Also change the array from int to double
The answer of Elliot Frisch
First, you should decide on appropriate types for the values. A number of states can be represented as an int (not clear why you would want a String or a Unit). The plural of "country" is "countries". And you can do something like,
String queryCountry = "USA";
String[] countries = { "USA", "AUSTRALIA" };
int[] numberStates = { 50, 6 };
int statesInCountry = -1;
for (int t = 0; t < countries.length; t++) {
if (countries[t].contains(queryCountry)) {
statesInCountry = numberStates[t];
}
}
But a Map or a custom Java type would be better.
Many thanks to Elliot Frisch.
You should create a class like this:
public class CountryInfo {
private String name;
private int numberOfStates;
public CountryInfo(String name, int numberOfState) {
this.name = name;
this.numberOfStates = numberOfStates;
}
public String getName() {
return name;
}
public int getNumberOfStates() {
return numberOfStates;
}
}
then
String [] countries = {"USA", "AUSTRALIA"}; // indexes 0,1
String [] numberStates = {"50", "6"}; //indexes 0,1
List<CountryInfo> list = new ArrayList<>();
for (int i = 0; i < numberStates.length; i++) {
list.add(new CountryInfo(countries[i]), numberStates[i]);
}
to access element, you can:
list.get(0).getName();
list.get(0).getNumberOfStates();

Task dealing with sorting 2d array

I have been assigned a task that requires me to utilise a 2D Array. I have to read in a file and export it to a 2D array. I can only have a single method but I am unable to sort the array correctly. I am supposed to sort the data in 3 ways (alphabetically by name and with scores highest to lowest; highest to lowest scores for each student and highest to lowest by the average of 3 scores.) So far I have
import java.util.*;
import java.io.*;
public class ScoreSorter {
public static void main(String[] args) {
int student_num = 30;
String[][] DataInTableArr = new String[30][6];
try {
BufferedReader ReadIn = new BufferedReader(new FileReader("classZ.csv"));
for (int i = 0; i < 30; i++) {
String DataIn = ReadIn.readLine();
String[] DataInArr = DataIn.split(",");
DataInTableArr[i][0] = DataInArr[0];
DataInTableArr[i][1] = DataInArr[1];
DataInTableArr[i][2] = DataInArr[2];
DataInTableArr[i][3] = DataInArr[3];
int temptest1 = Integer.parseInt(DataInArr[1]);
int temptest2 = Integer.parseInt(DataInArr[2]);
int temptest3 = Integer.parseInt(DataInArr[3]);
}
} catch (Exception e) {
System.out.println("Whoops, you messed up, RESTART THE PROGRAM!!!!!");
}
}
}
I have no idea as to how to solve the rest of the task... I would appreciate if someone could tell me of the most efficient way and perhaps an example...
One plausible way is to create a Student class which implements Comparable interface, with the following members:
String name;
int scoreOne;
int scoreTwo;
int scoreThree;
compareTo(Student s) { //implement the comparison following 3 criteria you mentioned }
And, read the files row by row, for each row we create a Student object, and put all rows in a TreeSet. In this way, the TreeSet together with the compareTo method will help us sort the Students automatically.
Finally, iterate the sorted TreeSet to fill up the 2D array.
import java.util.*;
import java.io.*;
public class ScoreSorter {
public static void main(String[] args) {
int student_num = 30;
String[][] DataInTableArr = new String[30][6];
try {
BufferedReader ReadIn = new BufferedReader(new FileReader("classZ.csv"));
for (int i = 0; i < 30; i++) {
String DataIn = ReadIn.readLine();
String[] DataInArr = DataIn.split(",");
DataInTableArr[i][0] = DataInArr[0];
DataInTableArr[i][1] = DataInArr[1];
DataInTableArr[i][2] = DataInArr[2];
DataInTableArr[i][3] = DataInArr[3];
int temptest1 = Integer.parseInt(DataInArr[1]);
int temptest2 = Integer.parseInt(DataInArr[2]);
int temptest3 = Integer.parseInt(DataInArr[3]);
}
/*Code To be Inserted Here*/
} catch (Exception e) {
System.out.println("Whoops, you messed up, RESTART THE PROGRAM!!!!!");
}
}
}
If there are 6 columns such that First is name and the other 3 are scores then what does other 2 columns contain?? I ignore your array declaration :
String[][] DataInTableArr = new String[30][6];
and assume it to be 30x4 array
String[][] DataInTableArr = new String[30][4];
Logic for sorting Alphabetically
if(DataInTableArr[i][0].compareTo(DataInTableArr[i+1][0])){
/* Sorting Name of adjacent rows*/
String temp = DataInTableArr[i][0];
DataInTableArr[i][0] = DataInTableArr[i+1][0];
DataInTableArr[i+1][0] = temp;
/*Sorting the three marks similarly*/
temp = DataInTableArr[i][1];
DataInTableArr[i][1] = DataInTableArr[i+1][1];
DataInTableArr[i+1][1] = temp;
temp = DataInTableArr[i][2];
DataInTableArr[i][2] = DataInTableArr[i+1][2];
DataInTableArr[i+1][2] = temp;
temp = DataInTableArr[i][3];
DataInTableArr[i][3] = DataInTableArr[i+1][3];
DataInTableArr[i+1][3] = temp;
}
Put the above code in bubble sorting algorithm i.e. 2 loops.
Logic for sorting according to highest marks
In this case you have to find the highest marks in all three subjects of each DataInTableArr[i] and then compare the highest marks with that of next row.
Logic for sorting according to Average marks
Calculate the average of each i'th row as
(Integer.parseInt(DataInTableArr[i][1]) + Integer.parseInt(DataInTableArr[i][2]) + Integer.parseInt(DataInTableArr[i][3]))/3
and compare it with [i+1] th rows average.(same formula just replace [i] with [i+1])

Sorting arraylist to relative it's another arraylist in Java [duplicate]

This question already has answers here:
Sorting two arrays simultaneously
(9 answers)
Closed 8 years ago.
Warnings: These examples are just examples. Not same my code, so don't think it's duplicate or it's bad question and vote down!
This title may be a little confusing sorry for that. Here's my problem;
I have two Arraylist. One of them takes a string and onether one takes integer. Let me illustrate it
arrList1 = {"apple", "strawberry", "banana", "watermelon"};
arrList2 = { 60, 90, 77 , 160};
arrList2 store how much fruits in arrList1 in same index number. For example there are 60 apples, 90 strawberry, 77 banana, 160 watermelon.
Also I have two more Arraylist like above;
arrList3 = { "strawberry", "watermelon", "apple", "banana" };
arrList4 = { 45, 40 , 10 , 11 };
arrList1 and arrList3 have same string but different index number. Now I want to print like by divide arrList2's number by arrList1 number and print objects by amount order. Let me illustrate it;
apple = 60/10 = 6
strawberry = 90/45 = 2
banana = 77/11 = 7
watermelon = 160/40 = 4
We divided and get some numbers and print to console ordered by amounts;
Banana // first because we got 7
Apple // second because we got 6 and etc
Watermelon
Strawberry
So, how I do it effectively?
To be clear, there are two questions here:
How do I efficiently do the lookup for each fruit in each pair of arrays?
How do I efficiently sort the results of dividing the corresponding entries' values?
You appear to have arrays, and not ArrayList(s). Next, you should create a Fruit class that implements Comparable<Fruit>. It should have two fields, an amount and a name. You could then use a Map<String, Integer> to perform your division, and finally build and sort a List of Fruit(s). Something like this,
public class Fruit implements Comparable<Fruit> {
private final String name;
private int amount;
public Fruit(String name, int amount) {
super();
this.name = (name != null) ? name.trim() : "";
setAmount(amount);
}
public void setAmount(int amount) {
this.amount = amount;
}
public int getAmount() {
return amount;
}
public String getName() {
return name;
}
#Override
public boolean equals(Object o) {
if (o instanceof Fruit) {
Fruit that = (Fruit) o;
return this.name.equals(that.name);
}
return false;
}
#Override
public String toString() {
return String.format("%s = %d", name, amount);
}
#Override
public int compareTo(Fruit o) {
return Integer.valueOf(o.amount).compareTo(amount);
}
#Override
public int hashCode() {
return this.name.hashCode();
}
public static void main(String[] args) {
String[] arrList1 = { "apple", "strawberry", "banana", "watermelon" };
int[] arrList2 = { 60, 90, 77, 160 };
String[] arrList3 = { "strawberry", "watermelon", "apple", "banana" };
int[] arrList4 = { 45, 40, 10, 11 };
Map<String, Integer> map = new TreeMap<>();
for (int i = 0; i < arrList1.length; i++) {
map.put(arrList1[i], arrList2[i]);
}
List<Fruit> al = new ArrayList<>();
for (int i = 0; i < arrList3.length; i++) {
String key = arrList3[i];
int val = map.get(key) / arrList4[i];
al.add(new Fruit(key, val));
}
Collections.sort(al);
System.out.println(al);
}
}
Which (when I run it here) outputs,
[banana = 7, apple = 6, watermelon = 4, strawberry = 2]
public class Main {
public static void main(String[] args) {
String[] arrList1 = { "apple", "strawberry", "banana", "watermelon" };
Integer[] arrList2 = { 60, 90, 77, 160 };
String[] arrList3 = { "strawberry", "watermelon", "apple", "banana" };
Integer[] arrList4 = { 45, 40, 10, 11 };
HashMap<String, Integer> result = new HashMap<>();
for (int i = 0; i < arrList1.length; i++) {
for (int j = 0; j < arrList3.length; j++) {
if (arrList1[i].contains(arrList3[j])) {
result.put(arrList1[i], arrList2[i] + arrList4[j]);
}
}
}
LinkedHashMap sorted = sortHashMap(result);
Set<String> keys = sorted.keySet();
for(String k:keys){
System.out.println(k+" -- "+sorted.get(k));
}
System.out.println("End");
}
public static LinkedHashMap sortHashMap(HashMap passedMap) {
List mapKeys = new ArrayList(passedMap.keySet());
List mapValues = new ArrayList(passedMap.values());
Collections.sort(mapValues);
Collections.sort(mapKeys);
LinkedHashMap sortedMap = new LinkedHashMap();
Iterator valueIt = mapValues.iterator();
while (valueIt.hasNext()) {
Object val = valueIt.next();
Iterator keyIt = mapKeys.iterator();
while (keyIt.hasNext()) {
Object key = keyIt.next();
String comp1 = passedMap.get(key).toString();
String comp2 = val.toString();
if (comp1.equals(comp2)) {
passedMap.remove(key);
mapKeys.remove(key);
sortedMap.put((String) key, (Integer) val);
break;
}
}
}
return sortedMap;
}
}
That is it, of course is doesn't have the best programming practices. I recommend using generics on it.
So, how I do it effectively?
Don't use seperate arrays. Encapsulate the data you need within POJOs (Plain Old Java Objects) and make use of the Collections API
But, without using List or Map, you need to build, at least, two more arrays (or at least I did ;))...
The first will hold the results of the calcaultions. To do this, you need some way to find the matching indexes from arrList1 in arrList3, for example...
This will find the index of the given value in the given array or return -1 if it was not found...
public static int find(String value, String[] list) {
int matchIndex = -1;
for (int index = 0; index < list.length; index++) {
if (list[index].equals(value)) {
matchIndex = index;
break;
}
}
return matchIndex;
}
Next, we need to calculate the results ...
int[] results = new int[arrList1.length];
for (int index = 0; index < arrList1.length; index++) {
String v1 = arrList1[index];
int v2 = arrList2[index];
int subIndex = find(v1, arrList3);
if (subIndex != -1) {
int v4 = arrList4[subIndex];
results[index] = (v2 / v4);
System.out.println(v1 + " = " + v2 + " / " + v4 + " = " + results[index]);
}
}
This will generate the output of...
apple = 60 / 10 = 6
strawberry = 90 / 45 = 2
banana = 77 / 11 = 7
watermelon = 160 / 40 = 4
And store the results of the calculations in the results array...
Now comes the fun part...We could sort ALL the arrays, but that just seems messy to me, or we could create a "proxy" array whose individual elements pointed to the index in the other arrays. This would represent a "virtual" sorted view of all the arrays...
int[] proxy = new int[arrList1.length];
for (int index = 0; index < proxy.length; index++) {
proxy[index] = index;
}
for (int n = 0; n < results.length; n++) {
for (int m = 0; m < results.length - 1 - n; m++) {
if ((results[proxy[m + 1]] - (results[proxy[m]])) > 0) {
int index = proxy[m];
proxy[m] = proxy[m + 1];
proxy[m + 1] = index;
}
}
}
This means that proxy[0] will hold the index of the first item, when sorted.
And if we use this to print the results...
for (int index : proxy) {
System.out.println(arrList1[index] + " = " + results[index]);
}
We get something like...
banana = 7
apple = 6
watermelon = 4
strawberry = 2
I know, it might sound confusing to start with, but this means that all the original arrays remain unaffected and you reduce the risk of the arrays becoming out of sequence.
If you needed the list in sorted order, you could easily create new arrays and apply the values accordingly (like we did when printing the results)
Having said all that. POJOs, which could hold the various properties and List and/or a sorted Map would be significantly easier :P
You can use maps:
Map<String, Integer> fruit1 = new HashMap<String, Integer>();
Map<String, Integer> fruit2 = new HashMap<String, Integer>();
then:
fruit1.put("apple", 60);
fruit2.put("apple", 10);
And lastly:
System.out.println(fruit1.get("apple")/fruit2.get("apple"));
EDIT: To have it sorted use another map - this time TreeMap which maintains sorted order (be key):
Map<Integer, String> results = new TreeMap<Integer, String>();
results.add(fruit1.get("apple")/fruit2.get("apple"), "apple");
// add more...
Then to print them so they look like you specified in your question:
for(Map.Entry<Integer,String> entry : results.entrySet()) {
System.out.println(entry.getValue() + ": " + entry.getKey());
}
This will print:
apple: 6
//and so on...

Problems with calling a member of array of strings

With the help of the community i managed to get this problem solved: How to convert String to the name of the Array?
But now i get 'nullPointerExceptions'. Here is the code i use:
public class IroncladsAdder
{
public static String weaponId = null;
public static String ship = null;
public static String wing = null;
//map code
private static Map<String, List<Integer>> arrays = new HashMap<String, List<Integer>>();
public void Holder(String... names) {
for (String name : names) {
arrays.put(name, new ArrayList<Integer>());
}
}
//adds weapons to fleets and stations
public static void AddWeapons(CargoAPI cargo, String fac, int count, int type) {
String arrayName = null;
int quantity = (int) (Math.random()*5f + count/2) + 1;
if (count == 1) {quantity = 1;}
if (type == 0) {arrayName = fac+"_mil_weps";}
else if (type == 1) {arrayName = fac+"_civ_weps";}
else {arrayName = fac+"_tech_weps";}
List<Integer> array = arrays.get(arrayName);
for (int j = 0; j <= count; j++)
{
weaponId = valueOf(arrays.get(arrayName).get((int) (Math.random() * arrays.get(arrayName).size())));
cargo.addWeapons(weaponId, quantity);
}
}
Here is an example of the array:
//high-tech UIN weapons
private static String [] uin_tech_weps =
{
"med-en-uin-partpulse",
"lrg-en-uin-partacc",
"med-bal-uin-driver",
"lrg-bal-uin-terminator",
"lrg-bal-uin-hvydriver",
"lrg-bal-uin-shotgundriver",
"lrg-en-uin-empbeam",
};
Error indicates that something is wrong with this construction:
weaponId = valueOf(arrays.get(arrayName).get((int) (Math.random() * arrays.get(arrayName).size())));
NOTE: i`m using Intellij IDEA and Java 6. Application most of the time has advices/fixes for some errors and in this case shows that everything is ok.
What i need is to get a String out of the specific array (that is using a code-generated name) and assign it to 'weaponId'.
When your application start the map with the arrays is empty, then when you try to get the array with name X you get back a null value.
First solution: at startup/construction time fill the map with empty arrays/List for all the arrays names.
Second solution: use this method in order to obtain the array.
protected List<Integer> getArray(String arrayName) {
List<Integer> array = map.get(arrayName);
if (array == null) {
array = new ArrayList<Integer>();
map.put(arrayName, array);
}
return array;
}
P.s.
You can change this code:
weaponId = valueOf(arrays.get(arrayName).get((int) (Math.random() * arrays.get(arrayName).size())));
into
weaponId = valueOf(array.get((int) (Math.random() * array.size())));
Ok. Now there is a different error - 'java.lang.IndexOutOfBoundsException: Index: 0, Size: 0'
Made the code look like this:
private static Map <String, List<Integer>> arrays = new HashMap<String, List<Integer>>();
public static List<Integer> getArray(String arrayName) {
List<Integer> array = arrays.get(arrayName);
if (array == null) {
array = new ArrayList<Integer>();
arrays.put("rsf_civ_weps", array);
arrays.put("rsf_mil_weps", array);
arrays.put("rsf_tech_weps", array);
arrays.put("isa_civ_weps", array);
arrays.put("isa_mil_weps", array);
arrays.put("isa_tech_weps", array);
arrays.put("uin_mil_weps", array);
arrays.put("uin_tech_weps", array);
arrays.put("uin_civ_weps", array);
arrays.put("xle_civ_weps", array);
arrays.put("xle_mil_weps", array);
arrays.put("xle_tech_weps", array);
}
return array;
}
This is how i now call the array and weaponId:
List<Integer> array = arrays.get(arrayName);
for (int j = 0; j <= count; j++)
{
weaponId = valueOf(array.get((int) (Math.random() * array.size())));
cargo.addWeapons(weaponId, quantity);
}
What`s wrong?

Creating two Dimensional array with existing arrays in java

I have four arrays of strings and I would like to create a two dimensional array of 3 columns and dynamic rows.
the arrays are like:
String[] first_name;
String[] last_name;
String[] unit;
String[] phone_number;
Object[][] obj = new Object[first_name.length()][3]
My problem is how do I achieve something like this:
obj = {first_name[index] + " " + last_name[index], unit[index], phone_number[index]}
Please help out!!!
I am assuming that by dynamic rows you mean that it depends on the number of elements in the first_name array.
So you could simply iterate:
String[][]obj = new String[first_name.length][3];
for (int i = 0; i < first_name.length; i++)
{
obj[i][0] = first_name[i] + " " + last_name[i];
obj[i][1] = unit[i];
obj[i][2] = phone_number[i];
}
However, this approach is not very good. You should consider creating an object for example named Employee which as the 3 fields, and then you just have an array of Employee
For example:
public class Employee
{
String name;
String unit;
String phoneNumber;
public Employee(String name, String unit, String phoneNumber)
{
//... rest of constructor to copy the fields
}
//... setters and getters
}
And then you just have:
Employee[] employees = new Employee[first_name.length];
for (int i = 0; i < first_name.length; i++)
{
employees[i] = new Employee(first_name[i] + " " + last_name[i], unit[i], phone_number[i]);
}
Would this help?
int len = first_name.lenghth();
String[][] arr2d = new String[len][3];
for (int i=0; i < len; i++) {
arr2d[i][0] = first_name[i] + " " + last_name[i];
arr2d[i][1] = unit[i];
arr2d[i][2] = phone_number[i];
}
this could be what you are looking for: (Assume that the four arrays have same length)
String[][] result = new String[first_name.length][3];
for(int i =0; i<first_name.length;i++){
result[i][0]=first_name[i]+" "+last_name[i];
result[i][1]=unit[i];
result[i][2]=phone_number[i];
}
String[] first_name = new String[length];
String[] last_name = new String[length];//length means your length of string
String[] unit = new String[length];
String[] phone_number = new String[length];
Object[][] obj = new Object[first_name.length][3];
for(int index =0;index<first_name.length;index++){
obj[index][0] = first_name[index] + " " + last_name[index];
obj[index][1] = unit[index];
obj[index][2] = phone_number[index];
}
There are a couple of ways to make 3-D arrays.
I would avoid Object[][], I never like the handling or performance.
Since a 3-D array is just an array of arrays, an easy approach would to use the List data structure.
List[] or List> should do the trick. This way you have all the built-ins of a Collection object plus you can also Apache commons, lambdaJ or Guava on top of it.
If you are dead set on using primitive arrays then you could also make a regular 2-D array, [], that can act like a 3-D array, [][].
Here is simple wrapper method I made around a basic array that will function the same as 3-D array.
public class MyThreeDArray{
int MAX_ROW;
int MAX_COL;
int[] arr;
public MyThreeDArray(final int MAX_ROW, final int MAX_COL){
this.MAX_ROW = MAX_ROW;
this.MAX_COL = MAX_COL;
arr = new int[MAX_ROW * MAX_COL];
}
private int findIndex(int row, int col) throws IllegalArgumentException{
if(row < 0 && row >= MAX_ROW ){
throw new IllegalArgumentException("Invaild row value");
}
if(col < 0 && col >= MAX_COL ){
throw new IllegalArgumentException("Invaild col value");
}
return ( row * MAX_COL + col );
}
public int get(int row, int col){
return arr[findIndex(row, col)];
}
public void set(int row, int col, int value){
arr[findIndex(row, col)] = value;
}
}
Also keep in mind I never tested any of this.
So if you did this with Strings then row 0 might contain the first name values, ... and row 4 could have the unit values.
To retrieve person A's data with this wrapper could make a call similar to this:
String firstName = myWrapper.get(0,0);
String lastName = myWrapper.get(0,1);
String phone = myWrapper.get(0,2);
String unit = myWrapper.get(0,3);
And person B's data would be stored in the second row.
But why try to combine arrays together? You could easy make a POJO called person
public class Person{
String firstName;
String lastName;
String phone;
String unit;
public Person(){}
//ToDo: Getters and Setters
}
This way could just easily add validation and clearly call a specific person without any trouble.
Person[] customers = new Person[5];
or better yet
List<Person> customers = new ArrayList<Person>();
You could create a List of 1D arrays: List<String []> arrayList = new ...
Then you can do arrayList.add(first_name);

Categories

Resources