Repeated values with same array in different Objects [duplicate] - java

I have an error , my array return all the same value while i use print method that i create in the class. i don't know why, it must be different value. any suggestion ?
here's the code
Main class :
public class KmeanES {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Kmean coba= new Kmean();
coba.filldata();
coba.print()
}
}
Kmean class :
public class Kmean {
double[][] datadummy = {{15.26, 14.84, 0.871}, {5.763, 3.312, 2.221},
{14.88, 14.57, 0.881}, {5.554, 3.333, 1.018}, {4.956, 114.29, 14.09},
{0.905, 5.291, 3.337}, {2.699, 4.825, 1}, {13.84, 13.94, 0.8955},
{5.324, 3.379, 2.259}, {4.805, 1, 16.14}, {14.99, 0.9034, 5.658}};
//11 dummy data
Kmeandata data = new Kmeandata();
Kmeandata[] datafinal = new Kmeandata[11];
void filldata() {
double[] temp = new double[3];
for (int i = 0; i < 11; i++) {
for (int j = 0; j < 3; j++) {
temp[j] = this.datadummy[i][j];
}
this.data.setData(temp);
this.datafinal[i]=this.data;
datafinal[i].printdata();
}
}
void print() {
for (int i = 0; i < 11; i++) {
this.datafinal[i].printdata();
}
}
}
and Kmeandata class
public class Kmeandata {
String kelas;
public double[] data = new double[3];
public Kmeandata(String kelas, double[] data) {
this.setKelas(kelas);
this.setData(data);
}
public Kmeandata(double[] data) {
this.setKelas(null);
this.setData(data);
}
public Kmeandata() {
this.setKelas(null);
this.setData(null);
}
public String getKelas() {
return kelas;
}
public void setKelas(String kelas) {
this.kelas = kelas;
}
public double[] getData() {
return data;
}
public void setData(double[] data) {
this.data = data;
}
public void printdata() {
double[] temp = new double[3];
temp = this.getData();
System.out.println("");
for (int i = 0; i < 3; i++) {
System.out.printf("|" + temp[i] + "|");
}
}
}

You are passing in a reference to the temp array, not a copy. Move the definition of temp inside the outer for loop.
for (int i = 0; i < 11; i++) {
double[] temp = new double[3];
for (int j = 0; j < 3; j++) {
temp[j] = this.datadummy[i][j];
}
...
}

Related

Why am I getting this IndexOutOfBoundsException error?

hi so im currently trying to get past this error in my code, if anyone could explain where I went wrong, would be greatly appreciated.
public class Lab07vst100SD
{
public static void main (String[] args)
{
System.out.println();
int size = 10;
School bhs = new School(size);
System.out.println(bhs);
System.out.println(bhs.linearSearch("Meg"));
System.out.println(bhs.linearSearch("Sid"));
System.out.println();
bhs.selectionSort();
System.out.println(bhs);
System.out.println(bhs.binarySearch("Meg"));
System.out.println(bhs.binarySearch("Sid"));
System.out.println();
}
}
class School
{
private ArrayList<Student> students;
private int size;
public School (int s)
{
students = new ArrayList<Student>();
size = s;
}
public void addData()
{
String [] name = {"Tom","Ann","Bob","Jan","Joe","Sue","Jay","Meg","Art","Deb"};
int[] age = {21,34,18,45,27,19,30,38,40,35};
double[] gpa = {1.685,3.875,2.5,4.0,2.975,3.225,3.65,2.0,3.999,2.125};
for(int i = 0; i < name.length; i++)
{
students.add(new Student(name[i], age[i], gpa[i]));
}
size = students.size();
}
public void selectionSort ()
{
for(int h = 0; h < students.size(); h++)
{
int index = h;
Student least = students.get(h);
for (int t = 0; t < size; t++) {
if (students.get(t).equals(least)) {
least = students.get(t);
index = t;
}
Student temp = students.get(h);
students.set(h, least);
students.set(t, temp);
}
}
}
public int linearSearch (String str)
{
// new arraylist
ArrayList<String> names = new ArrayList<String>();
for (int q = 0; q < size; q++) {
names.add(students.get(q).getName());
}
//comparison
for (int y = 0; y < size; y++) {
if (names.get(y).equals(str))
return y;
}
return -1;
};
public int binarySearch (String str) {
// new arraylist and variables
ArrayList<String> names = new ArrayList<String>();
Boolean found = false;
int lo = 0;
int hi = size;
int mid = (lo + hi) / 2;
//for loop for to transverse the array.
for (int m = 0; m < size; m++) {
names.add(students.get(m).getName());
}
while (lo <= hi && !found) {
if (names.get(mid).compareTo(str) == 0)
{
found = true;
return mid;
}
if (names.get(mid).compareTo(str) < 0) {
lo = mid + 1;
mid = (lo + hi) / 2;
}
else {
hi = mid -1;
mid = (lo + hi) / 2;
}
}
if (found)
return mid;
else
return -1;
}
public String toString() {
String temp = "";
for (int s = 0; s < students.size(); s++) {
temp += students.get(s);
}
return temp;
}
}
also, I should mention this uses the student class.
here
public class Student
{
private String name;
private int age;
private double gpa;
public Student (String n, int a, double g)
{
name = n;
age = a;
gpa = g;
}
public String getName() {
return name; }
public int getAge() {
return age; }
public double getGPA() {
return gpa; }
public String toString()
{
String temp = name + " " + age + " " + gpa + "\n";
return temp;
}
}
the school class calls to the student class.
this is what comes back.
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 0 out of bounds for length 0
at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248)
at java.base/java.util.Objects.checkIndex(Objects.java:359)
at java.base/java.util.ArrayList.get(ArrayList.java:427)
at School.linearSearch(Lab07vst100SD.java:78)
at Lab07vst100SD.main(Lab07vst100SD.java:16)
I'm completely confused on why this is happening, I think it may have to do with the ArrayList, other than that, I'm not sure.
please help, and thank you
p.s. I'm new so please bear with my horrible format.
You need call addData:
public static void main (String[] args)
{
System.out.println();
int size = 10;
School bhs = new School(size);
bhs.addData(); // here
System.out.println(bhs);
System.out.println(bhs.linearSearch("Meg"));
System.out.println(bhs.linearSearch("Sid"));
System.out.println();
bhs.selectionSort();
System.out.println(bhs);
System.out.println(bhs.binarySearch("Meg"));
System.out.println(bhs.binarySearch("Sid"));
System.out.println();
}
...
class School
{
private ArrayList<Student> students;
private int size;
public School (int s)
{
students = new ArrayList<Student>(); // Here, it can throw IndexOutOfBoundsException
size = s;
}
...
Please see https://www.tutorialspoint.com/java/util/arraylist_add_index.htm
The capacity of ArrayList must be initialized before ArrayList.add method
.

Designing a filter interface with a template method pattern

I have done a filter interface that filters out all the strings that have more than 3 letters without any particular pattern. How do i now define a abstract class Filter with a public method filter that calls the method acept that can be implemented in different ways? All of this using Template method pattern?
public class WordFilter extends Filter{
public boolean accept(String obj){
return(((String) obj).length() <= 3);
}
}
import java.util.Arrays;
public class RunHere {
public static void main(String[] args) {
String[] theArray = { "oig3", "jt3jjt3", "wee", "02ri", "Adam", "lel", "32", "k" };
System.out.println(Arrays.toString(theArray));
WordFilter filt = new WordFilter();
String[] resultat = filter(theArray, filt);
System.out.println(Arrays.toString(resultat));
}
public static String[] filter(String[] a, Filter f){
String x;
int count = 0;
int pos = 0;
for (int i = 0; i < a.length; i++) {
x = a[i];
if (x.length() < 4) {
count++;
}
}
System.out.println("Count is :" + count);
String[] filtered = new String[count];
for (int i = 0; i < a.length; i++) {
if (f.accept(a[i])) {
filtered[pos] = a[i];
pos++;
}
}
return filtered;
}
}
public abstract class Filter {
abstract boolean accept(String x);
}
The Template Method Pattern defines the skeleton of an algorithm in a method, deferring some steps to subclasses.
But in the problem that you have given, i see that there is only one step( finding Strings of size n). i.e there is no step before or after finding string of size n.
If Something was there(multiple tasks), i would have done it like below. Which would implement the Template pattern.
public abstract class Filter {
abstract boolean accept(String x);
void BeforeStep() {
// Do something
}
void AfterStep() {
// do something
}
}
public static String[] filter(String[] a, Filter f) {
String x;
int count = 0;
int pos = 0;
**f.BeforeStep();**
for (int i = 0; i < a.length; i++) {
x = a[i];
if (x.length() < 4) {
count++;
}
}
System.out.println("Count is :" + count);
String[] filtered = new String[count];
for (int i = 0; i < a.length; i++) {
if (f.accept(a[i])) {
filtered[pos] = a[i];
pos++;
}
}
f.AfterStep();
return filtered;
}

Type mismatch: cannot convert from double [] to int []

I am trying to have the method return the new array that was made by the for loop.
import java.util.Arrays;
public class stocks {
public static void main(String[] args) {
double stockV [] = {55.6, 63.2, 68.1, 70.1, 72.4, 73.9, 71.5, 68.3, 67.1, 66.2};
double isOverprices [] = overpriced(stockV);
}
public int [] overpriced(double[] rsiValues)
{
for (int i = 0; i < rsiValues.length; i++)
{
if (rsiValues[i] > 70)
{
rsiValues[i] = 1;
}
else if (rsiValues[i] <= 70)
{
rsiValues[i] = 0;
}
return rsiValues;
}
}
}
Change to
public double[] overpriced(double[] rsiValues)
You are obviously returning what you pass into the method, so why do you think its kind will change?
Also, you want to return the values after the for loop has ended.
for (int i = 0; i < rsiValues.length; i++)
{
if (rsiValues[i] > 70)
{
rsiValues[i] = 1;
}
else if (rsiValues[i] <= 70)
{
rsiValues[i] = 0;
}
}
return rsiValues;
Add 'static' to the overpriced method signature.
The overpriced method should return an array of ints but you're returning an array of doubles.
Put your return statement outside of the for loop.
In the main method, change isOverprices to an int array
public static void main(String[] args) {
double stockV [] = {55.6, 63.2, 68.1, 70.1, 72.4, 73.9, 71.5, 68.3, 67.1, 66.2};
int isOverprices [] = overpriced(stockV);
for(int i: isOverprices) {
System.out.println(i);
}
}
public static int [] overpriced(double[] rsiValues){
int result [] = new int[rsiValues.length];
for (int i = 0; i < rsiValues.length; i++)
{
if (rsiValues[i] > 70)
{
result[i] = 1;
}
else if (rsiValues[i] <= 70)
{
result[i] = 0;
}
}
return result;
}

Implementing merge sort in java 7

I have a problem with implementation of merge sort in java. I am looking for the error almost week unfortunately without result. ArrayList at the entrance is the same as the output.
import java.util.ArrayList;
import java.util.Scanner;
public class MergeSort
{
private ArrayList<Integer> basicArrayList = new ArrayList<Integer>();
ArrayList<Integer> arrayListA = new ArrayList<Integer>();
ArrayList<Integer> arrayListB = new ArrayList<Integer>();
Scanner input = new Scanner(System.in);
private int firstIndexOfArrayList = 0;
private int lastIndexOfArrayListA;
private int lastIndexOfArrayListB;
public void Scal(ArrayList<Integer> basicArrayList, int p, int q, int r) {
this.firstIndexOfArrayList = p;
this.lastIndexOfArrayListA = q;
this.lastIndexOfArrayListB = r;
int numberOfElementsArrayListA = lastIndexOfArrayListA
- firstIndexOfArrayList + 1;
int numberOfElementsArrayListB = lastIndexOfArrayListB
- lastIndexOfArrayListA;
for (int i = 0; i < numberOfElementsArrayListA; i++) {
arrayListA.set(i, basicArrayList.get(firstIndexOfArrayList + i));
}
for (int j = 0; j < numberOfElementsArrayListB; j++) {
arrayListB.set(j, basicArrayList.get(lastIndexOfArrayListA + j));
}
arrayListA.add(Integer.MAX_VALUE);
arrayListB.add(Integer.MAX_VALUE);
int i = 0;
int j = 0;
for (int k = firstIndexOfArrayList; k <= lastIndexOfArrayListB; k++) {
if (arrayListA.get(i) <= arrayListB.get(j)) {
basicArrayList.set(k, arrayListA.get(i));
i = i + 1;
} else {
basicArrayList.set(k, arrayListB.get(j));
j = j + 1;
}
}
}
public void MergeSort(ArrayList basicArrayList, int p, int r) {
this.firstIndexOfArrayList = p;
this.lastIndexOfArrayListB = r;
if (firstIndexOfArrayList < lastIndexOfArrayListB) {
int lastIndexOfArrayListA = (firstIndexOfArrayList + lastIndexOfArrayListB) / 2;
MergeSort(basicArrayList, firstIndexOfArrayList,
lastIndexOfArrayListA);
MergeSort(basicArrayList, lastIndexOfArrayListA + 1,
lastIndexOfArrayListB);
Scal(basicArrayList, firstIndexOfArrayList,
lastIndexOfArrayListA,
lastIndexOfArrayListB);
}
}
public void setSize() {
System.out.println("Enter the number of elements to sort: ");
this.lastIndexOfArrayListB = input.nextInt();
}
public int getSize() {
return lastIndexOfArrayListB;
}
public void setData() {
System.out.println("Enter the numbers: ");
for (int i = 0; i < lastIndexOfArrayListB; i++) {
int number;
number = input.nextInt();
basicArrayList.add(number);
}
}
public void getTable() {
System.out.println(basicArrayList.toString());
}
public static void main(String[] args) {
MergeSort output = new MergeSort();
output.setSize();
output.setData();
output.MergeSort(output.basicArrayList,
output.firstIndexOfArrayList, (output.getSize() - 1));
output.getTable();
}
}
In terms of fixing your code I had a crack at it and as far as I can tell this seems to work. To do this a lot of your code had to be changed but it does now sort all Integers properly
import java.util.ArrayList;
import java.util.Scanner;
public class MergeSort
{
private ArrayList<Integer> basicArrayList = new ArrayList<Integer>();
Scanner input = new Scanner(System.in);
private int numbersToSort;
public void doMergeSort(int firstIndexOfArrayList,int lastIndexOfArrayListB, ArrayList<Integer> arrayList)
{
if(firstIndexOfArrayList<lastIndexOfArrayListB && (lastIndexOfArrayListB-firstIndexOfArrayList)>=1)
{
int mid = (lastIndexOfArrayListB + firstIndexOfArrayList)/2;
doMergeSort(firstIndexOfArrayList, mid, arrayList);
doMergeSort(mid+1, lastIndexOfArrayListB, arrayList);
Scal(firstIndexOfArrayList,mid,lastIndexOfArrayListB, arrayList);
}
}
public void Scal(int firstIndexOfArrayList,int lastIndexOfArrayListA,int lastIndexOfArrayListB, ArrayList<Integer> arrayList)
{
ArrayList<Integer> mergedSortedArray = new ArrayList<Integer>();
int leftIndex = firstIndexOfArrayList;
int rightIndex = lastIndexOfArrayListA+1;
while(leftIndex<=lastIndexOfArrayListA && rightIndex<=lastIndexOfArrayListB)
{
if(arrayList.get(leftIndex)<=arrayList.get(rightIndex))
{
mergedSortedArray.add(arrayList.get(leftIndex));
leftIndex++;
}
else
{
mergedSortedArray.add(arrayList.get(rightIndex));
rightIndex++;
}
}
while(leftIndex<=lastIndexOfArrayListA)
{
mergedSortedArray.add(arrayList.get(leftIndex));
leftIndex++;
}
while(rightIndex<=lastIndexOfArrayListB)
{
mergedSortedArray.add(arrayList.get(rightIndex));
rightIndex++;
}
int i = 0;
int j = firstIndexOfArrayList;
while(i<mergedSortedArray.size())
{
arrayList.set(j, mergedSortedArray.get(i++));
j++;
}
}
public void setSize()
{
System.out.println("Enter the number of elements to sort: ");
this.numbersToSort = input.nextInt();
}
public int getSize()
{
return numbersToSort;
}
public void setData()
{
System.out.println("Enter the numbers: ");
for (int i = 0; i < numbersToSort; i++)
{
int number;
number = input.nextInt();
basicArrayList.add(number);
}
}
public void getTable()
{
System.out.println(basicArrayList.toString());
}
public void runSort(ArrayList<Integer> arrayList)
{
doMergeSort(0, this.numbersToSort-1, arrayList);
}
public static void main(String[] args)
{
MergeSort output = new MergeSort();
output.setSize();
output.setData();
output.runSort(output.basicArrayList);
output.getTable();
}
}
Try this code. The following code takes an ArrayList input and outputs an ArrayList as well so it still works along the same basis of your code. The actual sort is handled in a different class MergeSort and is passes into ForMergeSort. Hope this helps
MergeSort.java
public class MergeSort
{
private int[] array;
private int[] tempMergArr;
private int length;
public void sort(int[] inputArr)
{
}
public int[] getSortedArray(int[] inputArr)
{
this.array = inputArr;
this.length = inputArr.length;
this.tempMergArr = new int[length];
doMergeSort(0, length - 1);
for(int i=0;i<length;i++)
{
int correctNumber = i+1;
System.out.println("Value "+correctNumber+" of the sorted array which was sorted via the Merge Sort is: "+inputArr[i]);
}
return inputArr;
}
private void doMergeSort(int lowerIndex, int higherIndex)
{
if (lowerIndex < higherIndex)
{
int middle = lowerIndex + (higherIndex - lowerIndex) / 2;
doMergeSort(lowerIndex, middle);
doMergeSort(middle + 1, higherIndex);
mergeParts(lowerIndex, middle, higherIndex);
}
}
private void mergeParts(int lowerIndex, int middle, int higherIndex)
{
for (int i = lowerIndex; i <= higherIndex; i++)
{
tempMergArr[i] = array[i];
}
int i = lowerIndex;
int j = middle + 1;
int k = lowerIndex;
while (i <= middle && j <= higherIndex)
{
if (tempMergArr[i] <= tempMergArr[j])
{
array[k] = tempMergArr[i];
i++;
}
else
{
array[k] = tempMergArr[j];
j++;
}
k++;
}
while (i <= middle)
{
array[k] = tempMergArr[i];
k++;
i++;
}
}
}
ForMergeSort.java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class ForMergeSort
{
ArrayList<Integer> arrayList = new ArrayList<Integer>();
ArrayList<Integer> sortedArrayList = new ArrayList<Integer>();
MergeSort mS = new MergeSort();
public void buildArrayList()
{
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of elements to sort: ");
int toSort = input.nextInt();
System.out.println("Enter the numbers: ");
for(int i =0; i<toSort; i++)
{
int number = input.nextInt();
arrayList.add(number);
}
}
public void runMergeSort(ArrayList<Integer> arrayList)
{
int[] arrayOfValues = new int[arrayList.size()];
int i = 0;
for(int a:arrayList)
{
arrayOfValues[i] = a;
i++;
}
MergeSort mS = new MergeSort();
for(int intOfArray:mS.getSortedArray(arrayOfValues))
{
sortedArrayList.add(intOfArray);
}
System.out.println(sortedArrayList.toString());
}
public static void main(String[] args)
{
ForMergeSort fMS = new ForMergeSort();
fMS.buildArrayList();
fMS.runMergeSort(fMS.arrayList);
}
}

array object all index have same value java

I have an error , my array return all the same value while i use print method that i create in the class. i don't know why, it must be different value. any suggestion ?
here's the code
Main class :
public class KmeanES {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Kmean coba= new Kmean();
coba.filldata();
coba.print()
}
}
Kmean class :
public class Kmean {
double[][] datadummy = {{15.26, 14.84, 0.871}, {5.763, 3.312, 2.221},
{14.88, 14.57, 0.881}, {5.554, 3.333, 1.018}, {4.956, 114.29, 14.09},
{0.905, 5.291, 3.337}, {2.699, 4.825, 1}, {13.84, 13.94, 0.8955},
{5.324, 3.379, 2.259}, {4.805, 1, 16.14}, {14.99, 0.9034, 5.658}};
//11 dummy data
Kmeandata data = new Kmeandata();
Kmeandata[] datafinal = new Kmeandata[11];
void filldata() {
double[] temp = new double[3];
for (int i = 0; i < 11; i++) {
for (int j = 0; j < 3; j++) {
temp[j] = this.datadummy[i][j];
}
this.data.setData(temp);
this.datafinal[i]=this.data;
datafinal[i].printdata();
}
}
void print() {
for (int i = 0; i < 11; i++) {
this.datafinal[i].printdata();
}
}
}
and Kmeandata class
public class Kmeandata {
String kelas;
public double[] data = new double[3];
public Kmeandata(String kelas, double[] data) {
this.setKelas(kelas);
this.setData(data);
}
public Kmeandata(double[] data) {
this.setKelas(null);
this.setData(data);
}
public Kmeandata() {
this.setKelas(null);
this.setData(null);
}
public String getKelas() {
return kelas;
}
public void setKelas(String kelas) {
this.kelas = kelas;
}
public double[] getData() {
return data;
}
public void setData(double[] data) {
this.data = data;
}
public void printdata() {
double[] temp = new double[3];
temp = this.getData();
System.out.println("");
for (int i = 0; i < 3; i++) {
System.out.printf("|" + temp[i] + "|");
}
}
}
You are passing in a reference to the temp array, not a copy. Move the definition of temp inside the outer for loop.
for (int i = 0; i < 11; i++) {
double[] temp = new double[3];
for (int j = 0; j < 3; j++) {
temp[j] = this.datadummy[i][j];
}
...
}

Categories

Resources