Displaying an array of integers does not work - java

I have the following piece of code used to calculate Heart Rate from an ECG Signal by detecting the QRS peaks:
public class Heart_Rate {
public static void main(String[] args) throws IOException{
// Read Text file
Path filePath = Paths.get("heartrate.txt");
Scanner scanner = new Scanner(filePath);
List<Double> rawData = new ArrayList<Double>();
while (scanner.hasNext()) {
if (scanner.hasNextDouble()) {
rawData.add(scanner.nextDouble());
} else {
scanner.next();
}
}
System.out.println(rawData);
//Find Max value for Threshold Level
Double maximum = Collections.max(rawData);
Double threshold = 0.7*maximum;
System.out.println("Maximum = " + maximum);
System.out.println("Threshold = " + threshold);
//Calculate Heart Rate from list "Raw Data"
int upflag = 0;
int last = 1;
int p = 0;
int t = 0;
int count = 0;
//List<Double> heartRate = new ArrayList<Double>();
int heartRate2[] = new int[50];
for (int i = 0; i < rawData.size(); i++) {
if (rawData.get(i)> threshold){
if (upflag == 0){
if (last > 0){
t = i - last;
p = 100*60/t;
//100 is the sampling rate
heartRate2[count] = p;
count = count + 1;
//heartRate.add(p);
}
last = i;
}
upflag = 50;
}
else {
if (upflag > 0){
upflag = upflag -1;
}
}
}
System.out.println("Count = " + count);
System.out.println("Heart Rate = " + heartRate2);
System.out.println("Heart Rate = " + heartRate2);
}
}
When I add the heart rate values calculated(p) to my ArrayList (called HeartRate), I received a proper array of values.
However, I tried to change all my values to int and save my values in an integer array (called heartRate2) I get the following result:
Heart Rate = [I#dd1e765
I need my values to be integers since heart rate is calculated in beats per minute. I also tried converting the double values to int but ended up receiving a similar result as above.

Use Arrays.toString(arr) to get a meaningful String representation for some array arr.

Related

Array Index Out Of Bounds Java [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 2 years ago.
I have an array thats supposed to be a size of 3 which takes in 3 dive totals. It takes in an array of 7 scores from a double []. I have used a test scenario to see if the diveScore() method works and the calculations are correct. But when i try to read the numbers from a file and put them into an array, the scoreArray that holds the calculated dive score for each dive fails to store the data. The scoreArray in my hard coded test case works fine. Here is the exception from the console when run. I have tried to look at the line where the error states but the test data that I commented out in the main file works fine with the 3 arrays of scores for each dive. What am I missing? Every for loop doesn't have <= in it like many articles have been shown to me by everyone.
Exception:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
Index 3 out of bounds for length 3
at Diver.diveScore(Diver.java:33)
at Main.readFile(Main.java:74)
at Main.main(Main.java:10)
Main File:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
Diver [] divers = new Diver[25];
int numDivers = readFile(divers);
System.out.println(numDivers);
/*Diver d = new Diver("Frank Stalteri", "Middlesex County College");
double [] scores = {6.2, 3.5, 8, 7.3, 6, 9.1, 4.8};
double [] scores2 = {7.4, 5.4, 8, 3.7, 2.5, 7.8, 4};
double [] scores3 = {4.6, 7.2, 7.3, 1.4, 3.6, 8, 4.7};
d.diveScore(1, scores, 2);
d.diveScore(2, scores2, 4);
d.diveScore(3, scores3, 3);
System.out.println(d.toString());
*/
}
public static int readFile(Diver [] divers) throws FileNotFoundException {
File f = new File("divers.dat");
Scanner kb = new Scanner(f);
Diver d;
int count = 0;
int diveNum = 1;
while (kb.hasNextLine()) {
String name = kb.nextLine();
String school = kb.nextLine();
String dive1 = kb.nextLine();
String dive2 = kb.nextLine();
String dive3 = kb.nextLine();
//String [] of size 8 (inlcudes the difficulty #)
String [] scores1 = dive1.split("\\s+");
String [] scores2 = dive2.split("\\s+");
String [] scores3 = dive3.split("\\s+");
//gets the difficulty from String [] then parses
double diff1 = Double.parseDouble(scores1[scores1.length - 1]);
double diff2 = Double.parseDouble(scores2[scores2.length - 1]);
double diff3 = Double.parseDouble(scores3[scores3.length - 1]);
//make new double [] of size 7
double [] scores1D = new double[scores1.length - 1];
double [] scores2D = new double[scores2.length - 1];
double [] scores3D = new double[scores3.length - 1];
//loops through String [] and casts numbers without difficulty number
for (int i = 0; i < scores1D.length; i++) {
scores1D[i] = Double.parseDouble(scores1[i]);
//System.out.println(scores1D[i]);
}
for (int i = 0; i < scores2D.length; i++) {
scores2D[i] = Double.parseDouble(scores2[i]);
//System.out.println(scores2D[i]);
}
for (int i = 0; i < scores3D.length; i++) {
scores3D[i] = Double.parseDouble(scores3[i]);
//System.out.println(scores3D[i]);
}
d = new Diver(name, school);
divers[count] = d;
count++;
d.diveScore(diveNum, scores1D, diff1);
diveNum++;
d.diveScore(diveNum, scores2D, diff2);
diveNum++;
d.diveScore(diveNum, scores3D, diff3);
//System.out.println(d.toString());
}
kb.close();
return count;
}
public static void printDivers(Diver [] divers, int numDivers) {
System.out.println("All Divers\n");
for (int i = 0; i < divers.length; i++) {
if (divers[i] != null) {
System.out.println(divers[i]);
}
}
}
}
Diver File:
public class Diver {
private String name;
private String school;
private double [] scoreArray = new double [3];
private double totalScore;
Diver() {
}
Diver(String name, String school) {
this.name = name;
this.school = school;
}
//loop through score array and calculate the total score for each dive attempt
public double [] diveScore(int diveNum, double [] scores, double difficulty) {
double min = min(scores);
double max = max(scores);
double total = 0;
for (int i = 0; i < scores.length; i++) {
total += scores[i];
}
total -= max;
total -= min;
total *= difficulty;
scoreArray[diveNum - 1] = Math.round(total * 100.0) / 100.0;
return scoreArray;
}
//finds smallest score in array of scores
private double min(double [] scores) {
java.util.Arrays.parallelSort(scores);
double min = scores[0];
return min;
}
//finds largest score in array of scores
private double max(double [] scores) {
java.util.Arrays.parallelSort(scores);
double max = scores[scores.length - 1];
return max;
}
//calculates total of the 3 dives
public double totalScore() {
for (int i = 0; i < scoreArray.length; i++) {
totalScore += scoreArray[i];
}
return totalScore;
}
public String toString() {
String str = name + ", " + school + ": " + totalScore() + "\n" + "Dive 1: " + scoreArray[0] + "\n" + "Dive 2: " + scoreArray[1] + "\n" + "Dive 3: " + scoreArray[2] + "\n";
return str;
}
public boolean equals(Diver d) {
boolean value = true;
if (d == null || !(d instanceof Diver)) {
value = false;
return value;
}
Diver diver = (Diver) d;
if (this.totalScore == d.totalScore) {
value = true;
return value;
}
return value;
}
}
Your first diver must start at 0
Main > readFile > while loop
int diveNum = 0;

How to not print whole index if given number not found in table

I got this script to find given number from table and print number and index.
I'm having problem with number that are not in the table. I should print "number is not found" etc. and I tried with else, but not working. Any suggestions what to do with this?
with it prints whole table index.
import java.util.Scanner;
public class EtsitynAlkionIndeksi {
public static void main(String[] args) {
Scanner lukija = new Scanner(System.in);
int[] taulukko = new int[10];
taulukko[0] = 6;
taulukko[1] = 2;
taulukko[2] = 8;
taulukko[3] = 1;
taulukko[4] = 3;
taulukko[5] = 0;
taulukko[6] = 9;
taulukko[7] = 7;
System.out.print("Mitä etsitään? ");
int etsittava = Integer.valueOf(lukija.nextLine());
// Toteuta etsimistoiminnallisuus tänne
int indeksi = 0;
while (indeksi < taulukko.length) {
int arvo = taulukko[indeksi];
int eiLoydy = 0;
if (etsittava == arvo) {
System.out.println("Luku " + etsittava + " löytyy indeksistä " + indeksi + ".");
} else {
System.out.println("Ei löydy " + eiLoydy);
}
indeksi++;
}
}
}
Use break as follows:
import java.util.Scanner;
public class EtsitynAlkionIndeksi {
public static void main(String[] args) {
Scanner lukija = new Scanner(System.in);
int[] taulukko = new int[10];
taulukko[0] = 6;
taulukko[1] = 2;
taulukko[2] = 8;
taulukko[3] = 1;
taulukko[4] = 3;
taulukko[5] = 0;
taulukko[6] = 9;
taulukko[7] = 7;
System.out.print("Mitä etsitään? ");
int etsittava = Integer.valueOf(lukija.nextLine());
// Toteuta etsimistoiminnallisuus tänne
int indeksi = 0;
while (indeksi < taulukko.length) {
int arvo = taulukko[indeksi];
if (etsittava == arvo) {
System.out.println("Luku " + etsittava + " löytyy indeksistä " + indeksi + ".");
break;
}
indeksi++;
}
if (indeksi == taulukko.length) {
System.out.println("Ei löydy ");
}
}
}
A sample run:
Mitä etsitään? 3
Luku 3 löytyy indeksistä 4.
The statement, break; forces the loop to terminate. Also, note that I have moved System.out.println("Ei löydy " + eiLoydy); outside the while loop with the condition, if (indeksi == taulukko.length) i.e. if the value of indeksi has reached a value equal to taulukko.length, it means that the loop has not been terminated prematurely concluding that the lookup value has not been found.

Find mean median mode from text file java

I have a text file called numbers.txt and its full of numbers. I need to find the mean median and mode of the numbers. I can read the file but I don't know any more than that.
import java.io.File;
import java.util.Scanner;
public class Terms {
public static void main(String[] args)throws Exception {
File file =
new File("C:\\Users\\coderva.org\\Documents\\numbers.txt");
Scanner sc = new Scanner(file);
while (sc.hasNextLine())
System.out.println(sc.nextLine());
}
}
According to the definitions of mean, median and mode:
public static void main(String[] args) {
File file = new File("C:\\Users\\coderva.org\\Documents\\numbers.txt");
Scanner sc = null;
try {
sc = new Scanner(file);
} catch (FileNotFoundException e) {
System.out.println("File not found");
e.printStackTrace();
return;
}
ArrayList<Float> list = new ArrayList<Float>();
while (sc.hasNextFloat())
list.add(sc.nextFloat());
int size = list.size();
if (size == 0) {
System.out.println("Empty list");
return;
}
Collections.sort(list);
for (int i = 0; i < size; i++) {
System.out.print(list.get(i) + " ");
}
System.out.println();
// mean value, classical way
float sum = 0;
for (float x : list) {
sum += x;
}
float mean = sum / size; // mean as integer
//median
float median;
if (size % 2 == 0) {
float x1 = list.get(size / 2 - 1);
float x2 = list.get(size / 2);
median = (x1 + x2) / 2;
} else {
median = list.get(size / 2);
}
//mode
Float mode = null;
int counter = 1;
for (int i = 0; i < size; i++) {
int freq = Collections.frequency(list, list.get(i));
if (freq > counter) {
mode = list.get(i);
counter = freq;
}
}
System.out.println("Mean=" + mean);
System.out.println("Median=" + median);
if (mode == null) {
System.out.println("No mode found");
} else {
System.out.println("Mode=" + mode);
}
}
You can create a list of numbers as such:
List<Integer> numberList = new ArrayList<>();
while (sc.hasNextInt())
numberList.add(sc.nextInt());
Or when you have doubles or floats:
List<Double> numberList = new ArrayList<>();
while (sc.hasNextDouble())
numberList.add(sc.nextDouble());
List<Float> numberList = new ArrayList<>();
while (sc.hasNextFloat())
numberList.add(sc.nextFloat());
From there you can calculate the mean as follows:
sum = numberList.stream().mapToInt(Integer::intValue).sum();
average = sum / numberList.size();
And so on for the other properties you need.
Note The types are of sum and average are depended on which types you read from the file.

Mean, Median, and Mode - Newb - Java

We had a lab in Comsci I couldn't figure out. I did a lot of research on this site and others for help but they were over my head. What threw me off were the arrays. Anyway, thanks in advance. I already got my grade, just want to know how to do this :D
PS: I got mean, I just couldn't find the even numbered median and by mode I just gave up.
import java.util.Arrays;
import java.util.Random;
public class TextLab06st
{
public static void main(String args[])
{
System.out.println("\nTextLab06\n");
System.out.print("Enter the quantity of random numbers ===>> ");
int listSize = Expo.enterInt();
System.out.println();
Statistics intList = new Statistics(listSize);
intList.randomize();
intList.computeMean();
intList.computeMedian();
intList.computeMode();
intList.displayStats();
System.out.println();
}
}
class Statistics
{
private int list[]; // the actual array of integers
private int size; // user-entered number of integers in the array
private double mean;
private double median;
private int mode;
public Statistics(int s)
{
size = s;
list = new int[size];
mean = median = mode = 0;
}
public void randomize()
{
Random rand = new Random(12345);
for (int k = 0; k < size; k++)
list[k] = rand.nextInt(31) + 1; // range of 1..31
}
public void computeMean()
{
double total=0;
for (int f = 0; f < size; f++)
{
total = total + list[f];
}
mean = total / size;
}
public void computeMedian()
{
int total2 = 0;
Arrays.sort(list);
if (size / 2 == 1)
{
// total2 =
}
else
{
total2 = size / 2;
median = list[total2];
}
}
public void computeMode()
{
// precondition: The list array has exactly 1 mode.
}
public void displayStats()
{
System.out.println(Arrays.toString(list));
System.out.println();
System.out.println("Mean: " + mean);
System.out.println("Median: " + median);
System.out.println("Mode: " + mode);
}
}
Here are two implementations for your median() and mode() methods:
public void computeMedian() {
Arrays.sort(list);
if ( (list.size & 1) == 0 ) {
// even: take the average of the two middle elements
median = (list[(size/2)-1] + list[(size/2)]) / 2;
} else {
// odd: take the middle element
median = list[size/2];
}
}
public void computeMode() {
// precondition: The list array has exactly 1 mode.
Map<Integer, Integer> values = new HashMap<Integer, Integer>();
for (int i=0; i < list.size; ++i) {
if (values.get(list[i]) == null) {
values.put(list[i], 1);
} else {
values.put(list[i], values.get(list[i])+1);
}
}
int greatestTotal = 0;
// iterate over the Map and find element with greatest occurrence
Iterator it = values.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
if (pair.getValue() > greatestTotal) {
mode = pair.getKey();
greatestTotal = pair.getValue();
}
it.remove();
}
}

converting single dimensional array into multidimensional array

I'm trying to convert my single dimensional array into a multidimensional array. Convert the existing Interest Calculator Batch application from several single dimensional arrays
into 1 multi-dimensional array. Use the following data type: double[][] values;
Hint: The maximum number of data sets(5) will be your row and the each data array (from the original InterestCalculatorBatch)(7)will be a column.
2.All data will be contained within a
single multi-dimensional array.
3. Modify the sortBySimple and displayInterest methods to accept a single multi-dimensional array instead of multiple single dimensional arrays
I fixed the displayInterest to accept a single multi dimensional array. I am just confused if I have the sortBySimple set up correctly and when the program calculates the interest if I need to fix those or keep them as is. Thank you for the help.
import java.util.Scanner;
public class InterestCalculatorBatchMDA {
public static void main(String[] args )
{
int cnt = 0;
double[][] arrPrincipalAmt = new double[5][7];
double[][] arrInterestRate = new double[5][7];
double[][] arrTerm = new double[5][7];
double[][] arrSimple = new double[5][7];
double[][] arrCompoundMonthly = new double[5][7];
double[][] arrCompoundDaily = new double[5][7];
double[][] arrCompoundWeekly = new double[5][7];
do{
arrPrincipalAmt[cnt] = getPrincipalAmount(1);
arrInterestRate[cnt] = getInterestRate(1);
arrTerm[cnt] = getTerm(1);
arrSimple[cnt] = round(calculateSimpleInterest(arrPrincipalAmt[cnt], arrInterestRate[cnt], arrTerm[cnt]),5);
arrCompoundMonthly[cnt] = round(calculateCompoundInterest(arrPrincipalAmt[cnt], arrInterestRate[cnt],arrTerm[cnt] ,12.0 ),5);
arrCompoundWeekly[cnt] = round(calculateCompoundInterest(arrPrincipalAmt[cnt], arrInterestRate[cnt], arrTerm[cnt], 52.0 ),5);
arrCompoundDaily[cnt] = round(calculateCompoundInterest(arrPrincipalAmt[cnt], arrInterestRate[cnt], arrTerm[cnt], 365.0 ),5);
cnt++;
}while (cnt < 5 && askYesNo("Enter another set of data (Yes/No):"));
displayInterest(arrPrincipalAmt,arrInterestRate,arrTerm,arrSimple,arrCompoundMonthly,arrCompoundWeekly,arrCompoundDaily,cnt);
sortBySimple(arrPrincipalAmt,arrInterestRate,arrTerm,arrSimple,arrCompoundMonthly,arrCompoundWeekly,arrCompoundDaily,cnt);
displayInterest(arrPrincipalAmt,arrInterestRate,arrTerm,arrSimple,arrCompoundMonthly,arrCompoundWeekly,arrCompoundDaily,cnt);
}
/** Round **/
public static double round(double numb1, double numb2) {
double round = ((double) Math.round(numb1*(Math.pow(10, numb2)))/(Math.pow(10, numb2)));;
return round;
}
/** Calculate Simple **/
public static double calculateSimpleInterest(double numb1, double numb2, double numb3) {
double calculateSimpleInterest = ((numb1)*(numb2/100.0)*(numb3/12.0));
return calculateSimpleInterest;
}
/** Calculate Compounded Daily **/
public static double calculateCompoundInterest(double numb1, double numb2, double numb3, double numb4 ) {
double calculateCompoundInterest = (numb1*Math.pow((1.0+((numb2/100.0)/numb4)),(numb4*(numb3/12.0))))-numb1;
return calculateCompoundInterest;
}
/** Get principal amount **/
public static double getPrincipalAmount(double numb1) {
Scanner input = new Scanner(System.in);
double numb2 = 1;
do{System.out.print("Enter Loan Amount: ");
numb2 = input.nextDouble();
if(numb2 > 0);
else{
System.out.println("Data Error: Loan amount must be greater than zero. You entered " +numb2);
}
}while (numb2 < 0);
return numb2;
}
/** Get interest rate **/
public static double getInterestRate(double numb1) {
Scanner input = new Scanner(System.in);
double numb2=1;
do{System.out.print("Enter Yearly Interest Rate (1 to 100 percent): ");
numb2 = input.nextDouble();
double getInterestRate = 0;
if (numb2 >= 0 && numb2 <= 100)
getInterestRate = numb2;
else{
System.out.println("Data Error: Interest rate must be greater than or equal to zero and less than or equal to 100. You entered " +numb2);
}
}while (numb2 <= 0 || numb2 >= 100);
return numb2;
}
/** Get term **/
public static double getTerm(double numb1) {
Scanner input = new Scanner(System.in);
double numb2=1;
do{System.out.print("Enter the Term (in months): ");
numb2 = input.nextInt();
double getTerm = 0;
if (numb2 > 0)
getTerm = numb2;
else{
System.out.println("Data Error: Loan amount must be greater than zero. You entered " +numb2);
}
}while (numb2 <= 0);
return numb2;
}
/** Sort by simple interest **/
public static void sortBySimple(double[][] arrPrincipalAmt ,double[][] arrInterestRate, double[][] arrTerm, double[][] arrSimple, double[][] arrCompoundMonthly, double[][] arrCompoundWeekly, double[][] arrCompoundDaily, double count){
for(int i = 0;i<count;i++)
{
for(int j=i+1; j<count;j++)
{
if(arrSimple[i][j] < arrSimple[i][j])
{
double temp = arrSimple[i][j];
arrSimple[i][j] = arrSimple[i][j];
arrSimple[i][j] = temp;
double temp1 = arrPrincipalAmt[i][j];
arrPrincipalAmt[i][j] = arrPrincipalAmt[i][j];
arrPrincipalAmt[i][j] = temp1;
double temp2 = arrInterestRate[i][j];
arrInterestRate[i][j] = arrInterestRate[i][j];
arrInterestRate[i][j] = temp2;
double temp3 = arrTerm[i][j];
arrTerm[i][j] = arrTerm[i][j];
arrTerm[i][j] = temp3;
double temp4 = arrSimple[i][j];
arrSimple[i][j] = arrSimple[i][j];
arrSimple[i][j] = temp4;
double temp5 = arrCompoundMonthly[i][j];
arrCompoundMonthly[i][j] = arrCompoundMonthly[i][j];
arrCompoundMonthly[i][j] = temp5;
double temp6 = arrCompoundDaily[i][j];
arrCompoundDaily[i][j] = arrCompoundDaily[i][j];
arrCompoundDaily[i][j] = temp6;
double temp7 = arrCompoundWeekly[i][j];
arrCompoundWeekly[i][j] = arrCompoundWeekly[i][j];
arrCompoundWeekly[i][j] = temp7;
}
}
}
}
/** Display Interest **/
public static void displayInterest(double[][] amt ,double[][] interest, double[][] term, double[][] simple, double[][] monthly, double[][] weekly, double[][] arrCompoundDaily, int count){
int i=0;
System.out.println("[Line #] [Principal Amount] [Interest Rate] [Term] [Simple Interest] [Compound Monthly] [Compound Weekly] [Compound Daily]");
do{
System.out.print((i+1)+" ");
System.out.print(amt[i][i]+" ");
System.out.print(+interest[i][i]+" ");
System.out.print(+ term[i][i]+" ");
System.out.print(+simple[i][i]+" ");
System.out.print(+monthly[i][i]+" ");
System.out.print(+weekly[i][i]+" ");
System.out.println(+arrCompoundDaily[i][i]);
i++;
}while(i < count);
}
/**ask yes or no **/
public static boolean askYesNo(String question) {
Scanner input = new Scanner(System.in);
String enteredText;
boolean isAnswerValid;
do{
isAnswerValid = false;
System.out.println(question);
enteredText = input.nextLine();
if (enteredText.length() > 0)
{
enteredText = enteredText.toUpperCase();
if(enteredText.equals("YES") || enteredText.equals("Y") || enteredText.equals("NO") || enteredText.equals("N"))
{
isAnswerValid = true;
}
}
if(isAnswerValid == false)
{
System.out.println("Please enter 'Yes' or 'No'?");
}
} while(isAnswerValid == false);
if(enteredText.equals("YES") || enteredText.equals("Y"))
{
return true;
}
return false;
}
}
Your code looks like an attempt to write C in Java. Java is an OO language, and you will have much more success if you design and write your programs in to make use of that. Data structures that are "smeared" across multiple arrays like that are fundamentally awkward to deal with.
The first thing you need to do to remedy this is to create a class that represents an entry in the arrays.
Trying to fix the program while retaining the current "smeared" data structure design is ... to be blunt ... a waste of time.

Categories

Resources