SlideShare a Scribd company logo
1 of 4
Download to read offline
//import statemnts for Random, Scanner and IO
import java.util.Random;
import java.util.Scanner;
import java.io.*;
public class Hobbits
{
public static void main(String[] args) throws IOException
{
final int NUM_HOBBITS = 5;
final int NUM_COLUMNS = 2;
String fileName = "hobbits.csv";
//call populateHobbits( ) to create the two dimensional array
double[][] hobbits = populateHobbits(NUM_HOBBITS, NUM_COLUMNS);
//display the number of hobbits
System.out.println(hobbits.length + " hobbits accepted Gandalf's invitation to lunchn");
//calculate the means of the columns
double[] hobbitMeans = getColMeans(hobbits);
//write hobbits array to file
writeHobbits(hobbits, fileName);
//read and display the file that has been read
readHobbitses(fileName);
//call displayColMeans to display hobbit means
displayColMeans(hobbitMeans);
}
//method to populate hobbits array with random double values
public static double[][] populateHobbits(int numHobbits, int numCols)
{
final double HT_MULTIPLIER = 10.0; //multiplier for the hobbit height
final double WT_MULTIPLIER = 250.0; //multiplier for the hobbit weight
//instantiate Random object
Random rand = new Random();
//declare two dim array with numHobbits rows numCols columns
double[][] hobbitArray = new double[numHobbits][numCols];
//assign random double values to all elements
for (int i = 0; i < numHobbits; i++) //outer loop is for rows
{
for (int j = 0; j < numCols; j++) //inner loop is for columns
{
//get a random double value in range [0.2, 0.4]
double randDouble = getRandDouble(rand);
//assign this double to the current array element
hobbitArray[i][j] = randDouble;
//determine which multiplier to use
if (j == 0) //this is column for height
hobbitArray[i][j] *= HI_MULTIPLIER;
else //this is column for weight
hobbitArray[i][j] *= WT_MULTIPLIER;
}
}
return hobbitArray; //return the two dimensional array
}
//method to write hobbits array to file
public static void writeHobbits(double[][] ar, String fileName) throws IOException
{
//open the file to write
PrintWriter outFile = new PrintWriter(fileName);
//print columen heading of the array of stats
outFile.println("HEIGHT,WEIGHT");
for (int i = 0; i < ar.length; i++)
{
for (int j = 0; j < ar[i].length; j++)
{
outFile.print(ar[i][j]);
//if at end of a row, add newline char
if (j == ar[i].length - 1)
outFile.print("n");
else //add the "," delimiter
outFile.print(",");
} //end of inner loop
} //end of outer loop
outFile.close(); //close outfile
System.out.println("The file was successfully writtenn");
} //end of method
//method to read the hobbits file
public static void readHobbitses(String fileName) throws IOException {
//open the file to read
File dataFile = new File(fileName);
Scanner inFile = new Scanner(dataFile);
//variable to contain the substrings of one line of file
String[] oneLine = new String[2];
int counter = 0; //keep track of line numbers
System.out.println("Data read from the " + fileName + " file:");
//read file, one line at a time
while (inFile.hasNext()) {
String dataLine = inFile.nextLine();
oneLine = dataLine.split(","); //split line with delimiter
if (counter > 0) //for second line and beyond, format doubles
{
System.out.printf("%.2ftt%.2fn", Double.parseDouble(oneLine[0]),
Double.parseDouble(oneLine[1]));
} else //if this first line, display the column heading
System.out.println(oneLine[0] + "t" + oneLine[1]);
if (inFile.hasNext())
counter++; //keep track of how many lines
} //end while loop read file
inFile.close(); //close the file
System.out.println("The file has now been successfully read.n");
} //end of method
//method to determine average values of columns two dim array
public static double[] getColMeans(double[][] ar) {
//local array to store means
//array is sized according to length second dimension of parameter
//first element is mean of first column
//second element is mean of second column, etc
double[] meanAr = new double[ar[0].length];
//nested for loop to iterate through elements in parameter
for (int i = 0; i < ar.length; i++) {
for (int j = 0; j < ar[i].length; j++) {
//sum the elements in the current column
meanAr[j] += ar[i][j];
}
} //end of outer loop
//replace the sum with the average; i.e. divide by number of rows
for (int i = 0; i < meanAr.length; i++)
meanAr[i] /= ar.length;
Lab16 Sample output

More Related Content

Similar to --import statemnts for Random- Scanner and IO import java-util-Random-.pdf

please navigate to cs112 webpage and go to assignments -- Trees. Th.pdf
please navigate to cs112 webpage and go to assignments -- Trees. Th.pdfplease navigate to cs112 webpage and go to assignments -- Trees. Th.pdf
please navigate to cs112 webpage and go to assignments -- Trees. Th.pdf
aioils
 
File & Exception Handling in C++.pptx
File & Exception Handling in C++.pptxFile & Exception Handling in C++.pptx
File & Exception Handling in C++.pptx
RutujaTandalwade
 
DisplayBook.java import java.io.File; import java.io.FileInput.pdf
DisplayBook.java import java.io.File; import java.io.FileInput.pdfDisplayBook.java import java.io.File; import java.io.FileInput.pdf
DisplayBook.java import java.io.File; import java.io.FileInput.pdf
sudheerforce
 
Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01
Rex Joe
 
csc1201_lecture13.ppt
csc1201_lecture13.pptcsc1201_lecture13.ppt
csc1201_lecture13.ppt
HEMAHEMS5
 
import org-jsoup-Jsoup- import org-jsoup-nodes-Document- import java-.docx
import org-jsoup-Jsoup- import org-jsoup-nodes-Document-  import java-.docximport org-jsoup-Jsoup- import org-jsoup-nodes-Document-  import java-.docx
import org-jsoup-Jsoup- import org-jsoup-nodes-Document- import java-.docx
RyanEAcTuckern
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
Dmitry Soshnikov
 

Similar to --import statemnts for Random- Scanner and IO import java-util-Random-.pdf (20)

Oop lecture9 11
Oop lecture9 11Oop lecture9 11
Oop lecture9 11
 
Java 7 - short intro to NIO.2
Java 7 - short intro to NIO.2Java 7 - short intro to NIO.2
Java 7 - short intro to NIO.2
 
please navigate to cs112 webpage and go to assignments -- Trees. Th.pdf
please navigate to cs112 webpage and go to assignments -- Trees. Th.pdfplease navigate to cs112 webpage and go to assignments -- Trees. Th.pdf
please navigate to cs112 webpage and go to assignments -- Trees. Th.pdf
 
Inheritance
InheritanceInheritance
Inheritance
 
C Programming Project
C Programming ProjectC Programming Project
C Programming Project
 
File & Exception Handling in C++.pptx
File & Exception Handling in C++.pptxFile & Exception Handling in C++.pptx
File & Exception Handling in C++.pptx
 
Exmaples of file handling
Exmaples of file handlingExmaples of file handling
Exmaples of file handling
 
DisplayBook.java import java.io.File; import java.io.FileInput.pdf
DisplayBook.java import java.io.File; import java.io.FileInput.pdfDisplayBook.java import java.io.File; import java.io.FileInput.pdf
DisplayBook.java import java.io.File; import java.io.FileInput.pdf
 
Input output files in java
Input output files in javaInput output files in java
Input output files in java
 
Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01
 
Files in c++
Files in c++Files in c++
Files in c++
 
csc1201_lecture13.ppt
csc1201_lecture13.pptcsc1201_lecture13.ppt
csc1201_lecture13.ppt
 
Explaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to ComeExplaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to Come
 
Files and streams In Java
Files and streams In JavaFiles and streams In Java
Files and streams In Java
 
files.pptx
files.pptxfiles.pptx
files.pptx
 
import org-jsoup-Jsoup- import org-jsoup-nodes-Document- import java-.docx
import org-jsoup-Jsoup- import org-jsoup-nodes-Document-  import java-.docximport org-jsoup-Jsoup- import org-jsoup-nodes-Document-  import java-.docx
import org-jsoup-Jsoup- import org-jsoup-nodes-Document- import java-.docx
 
Session 23 - JDBC
Session 23 - JDBCSession 23 - JDBC
Session 23 - JDBC
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File Handling
 
26 io -ii file handling
26  io -ii  file handling26  io -ii  file handling
26 io -ii file handling
 

More from ganisyedtrd

-- USING UNITY TRYING TO CREATE A CLICK TO PATH- THAT YOU CLICK ON AND.pdf
-- USING UNITY TRYING TO CREATE A CLICK TO PATH- THAT YOU CLICK ON AND.pdf-- USING UNITY TRYING TO CREATE A CLICK TO PATH- THAT YOU CLICK ON AND.pdf
-- USING UNITY TRYING TO CREATE A CLICK TO PATH- THAT YOU CLICK ON AND.pdf
ganisyedtrd
 
-- Write the compiler used- Visual studio or gcc -- Reminder that your.pdf
-- Write the compiler used- Visual studio or gcc -- Reminder that your.pdf-- Write the compiler used- Visual studio or gcc -- Reminder that your.pdf
-- Write the compiler used- Visual studio or gcc -- Reminder that your.pdf
ganisyedtrd
 
- In 150-250 words- respond to all questions- This is your initial dis.pdf
- In 150-250 words- respond to all questions- This is your initial dis.pdf- In 150-250 words- respond to all questions- This is your initial dis.pdf
- In 150-250 words- respond to all questions- This is your initial dis.pdf
ganisyedtrd
 

More from ganisyedtrd (20)

--12 Points- DEVORESTATS 2-5-074- Suppose thut the proportions of bloo.pdf
--12 Points- DEVORESTATS 2-5-074- Suppose thut the proportions of bloo.pdf--12 Points- DEVORESTATS 2-5-074- Suppose thut the proportions of bloo.pdf
--12 Points- DEVORESTATS 2-5-074- Suppose thut the proportions of bloo.pdf
 
--kindly help with the correct answer --must show diagram Explain what.pdf
--kindly help with the correct answer --must show diagram Explain what.pdf--kindly help with the correct answer --must show diagram Explain what.pdf
--kindly help with the correct answer --must show diagram Explain what.pdf
 
--- If you were start a business- what are the advantages in using equ.pdf
--- If you were start a business- what are the advantages in using equ.pdf--- If you were start a business- what are the advantages in using equ.pdf
--- If you were start a business- what are the advantages in using equ.pdf
 
--- Interpret the figure below given what you know about wood frogs---.pdf
--- Interpret the figure below given what you know about wood frogs---.pdf--- Interpret the figure below given what you know about wood frogs---.pdf
--- Interpret the figure below given what you know about wood frogs---.pdf
 
--------- Lala--- the noll (fnrmad plement) indicated by letter A is a.pdf
--------- Lala--- the noll (fnrmad plement) indicated by letter A is a.pdf--------- Lala--- the noll (fnrmad plement) indicated by letter A is a.pdf
--------- Lala--- the noll (fnrmad plement) indicated by letter A is a.pdf
 
--- Which of the following influences the instantaneous rate of change.pdf
--- Which of the following influences the instantaneous rate of change.pdf--- Which of the following influences the instantaneous rate of change.pdf
--- Which of the following influences the instantaneous rate of change.pdf
 
-- USING UNITY TRYING TO CREATE A CLICK TO PATH- THAT YOU CLICK ON AND.pdf
-- USING UNITY TRYING TO CREATE A CLICK TO PATH- THAT YOU CLICK ON AND.pdf-- USING UNITY TRYING TO CREATE A CLICK TO PATH- THAT YOU CLICK ON AND.pdf
-- USING UNITY TRYING TO CREATE A CLICK TO PATH- THAT YOU CLICK ON AND.pdf
 
-- Write the compiler used- Visual studio or gcc -- Reminder that your.pdf
-- Write the compiler used- Visual studio or gcc -- Reminder that your.pdf-- Write the compiler used- Visual studio or gcc -- Reminder that your.pdf
-- Write the compiler used- Visual studio or gcc -- Reminder that your.pdf
 
- There are 50 fish in a pond in January- The fish grow at a rate of 6.pdf
- There are 50 fish in a pond in January- The fish grow at a rate of 6.pdf- There are 50 fish in a pond in January- The fish grow at a rate of 6.pdf
- There are 50 fish in a pond in January- The fish grow at a rate of 6.pdf
 
- TIF B cells and T cells are able to alter their genome- What kind of.pdf
- TIF B cells and T cells are able to alter their genome- What kind of.pdf- TIF B cells and T cells are able to alter their genome- What kind of.pdf
- TIF B cells and T cells are able to alter their genome- What kind of.pdf
 
- The array data of integers is sorted in an increaning order- - The i.pdf
- The array data of integers is sorted in an increaning order- - The i.pdf- The array data of integers is sorted in an increaning order- - The i.pdf
- The array data of integers is sorted in an increaning order- - The i.pdf
 
- Quantitative (record completenessdocuments are present- forms authen.pdf
- Quantitative (record completenessdocuments are present- forms authen.pdf- Quantitative (record completenessdocuments are present- forms authen.pdf
- Quantitative (record completenessdocuments are present- forms authen.pdf
 
- Lab T Reriow Hemneork + Oun on March 10- 2023 2 anantwred Table 72 P.pdf
- Lab T Reriow Hemneork + Oun on March 10- 2023 2 anantwred Table 72 P.pdf- Lab T Reriow Hemneork + Oun on March 10- 2023 2 anantwred Table 72 P.pdf
- Lab T Reriow Hemneork + Oun on March 10- 2023 2 anantwred Table 72 P.pdf
 
- In 150-250 words- respond to all questions- This is your initial dis.pdf
- In 150-250 words- respond to all questions- This is your initial dis.pdf- In 150-250 words- respond to all questions- This is your initial dis.pdf
- In 150-250 words- respond to all questions- This is your initial dis.pdf
 
- Insert the following number into this tree 20 - Show all the steps o.pdf
- Insert the following number into this tree 20 - Show all the steps o.pdf- Insert the following number into this tree 20 - Show all the steps o.pdf
- Insert the following number into this tree 20 - Show all the steps o.pdf
 
- Bag breaks open- included as delay in the allowance factor ^ Conveyo.pdf
- Bag breaks open- included as delay in the allowance factor ^ Conveyo.pdf- Bag breaks open- included as delay in the allowance factor ^ Conveyo.pdf
- Bag breaks open- included as delay in the allowance factor ^ Conveyo.pdf
 
- If your class investigated two different types of tissues (plants)-.pdf
- If your class investigated two different types of tissues (plants)-.pdf- If your class investigated two different types of tissues (plants)-.pdf
- If your class investigated two different types of tissues (plants)-.pdf
 
- Cytosolic pathogens- - Where are they degraded- - What do their pept.pdf
- Cytosolic pathogens- - Where are they degraded- - What do their pept.pdf- Cytosolic pathogens- - Where are they degraded- - What do their pept.pdf
- Cytosolic pathogens- - Where are they degraded- - What do their pept.pdf
 
- Drag the labels of Group 1 to their respective targets to identify p.pdf
- Drag the labels of Group 1 to their respective targets to identify p.pdf- Drag the labels of Group 1 to their respective targets to identify p.pdf
- Drag the labels of Group 1 to their respective targets to identify p.pdf
 
- Each student must post ane (1) substantial intid post as a response.pdf
- Each student must post ane (1) substantial intid post as a response.pdf- Each student must post ane (1) substantial intid post as a response.pdf
- Each student must post ane (1) substantial intid post as a response.pdf
 

Recently uploaded

Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
AnaAcapella
 
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lessonQUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
httgc7rh9c
 

Recently uploaded (20)

Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
VAMOS CUIDAR DO NOSSO PLANETA! .
VAMOS CUIDAR DO NOSSO PLANETA!                    .VAMOS CUIDAR DO NOSSO PLANETA!                    .
VAMOS CUIDAR DO NOSSO PLANETA! .
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
Introduction to TechSoup’s Digital Marketing Services and Use Cases
Introduction to TechSoup’s Digital Marketing  Services and Use CasesIntroduction to TechSoup’s Digital Marketing  Services and Use Cases
Introduction to TechSoup’s Digital Marketing Services and Use Cases
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
Model Attribute _rec_name in the Odoo 17
Model Attribute _rec_name in the Odoo 17Model Attribute _rec_name in the Odoo 17
Model Attribute _rec_name in the Odoo 17
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
UGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdf
UGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdfUGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdf
UGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdf
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lessonQUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
 
21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 

--import statemnts for Random- Scanner and IO import java-util-Random-.pdf

  • 1. //import statemnts for Random, Scanner and IO import java.util.Random; import java.util.Scanner; import java.io.*; public class Hobbits { public static void main(String[] args) throws IOException { final int NUM_HOBBITS = 5; final int NUM_COLUMNS = 2; String fileName = "hobbits.csv"; //call populateHobbits( ) to create the two dimensional array double[][] hobbits = populateHobbits(NUM_HOBBITS, NUM_COLUMNS); //display the number of hobbits System.out.println(hobbits.length + " hobbits accepted Gandalf's invitation to lunchn"); //calculate the means of the columns double[] hobbitMeans = getColMeans(hobbits); //write hobbits array to file writeHobbits(hobbits, fileName); //read and display the file that has been read readHobbitses(fileName); //call displayColMeans to display hobbit means displayColMeans(hobbitMeans); } //method to populate hobbits array with random double values public static double[][] populateHobbits(int numHobbits, int numCols) { final double HT_MULTIPLIER = 10.0; //multiplier for the hobbit height final double WT_MULTIPLIER = 250.0; //multiplier for the hobbit weight //instantiate Random object Random rand = new Random(); //declare two dim array with numHobbits rows numCols columns double[][] hobbitArray = new double[numHobbits][numCols];
  • 2. //assign random double values to all elements for (int i = 0; i < numHobbits; i++) //outer loop is for rows { for (int j = 0; j < numCols; j++) //inner loop is for columns { //get a random double value in range [0.2, 0.4] double randDouble = getRandDouble(rand); //assign this double to the current array element hobbitArray[i][j] = randDouble; //determine which multiplier to use if (j == 0) //this is column for height hobbitArray[i][j] *= HI_MULTIPLIER; else //this is column for weight hobbitArray[i][j] *= WT_MULTIPLIER; } } return hobbitArray; //return the two dimensional array } //method to write hobbits array to file public static void writeHobbits(double[][] ar, String fileName) throws IOException { //open the file to write PrintWriter outFile = new PrintWriter(fileName); //print columen heading of the array of stats outFile.println("HEIGHT,WEIGHT"); for (int i = 0; i < ar.length; i++) { for (int j = 0; j < ar[i].length; j++) { outFile.print(ar[i][j]); //if at end of a row, add newline char if (j == ar[i].length - 1) outFile.print("n"); else //add the "," delimiter outFile.print(","); } //end of inner loop } //end of outer loop outFile.close(); //close outfile
  • 3. System.out.println("The file was successfully writtenn"); } //end of method //method to read the hobbits file public static void readHobbitses(String fileName) throws IOException { //open the file to read File dataFile = new File(fileName); Scanner inFile = new Scanner(dataFile); //variable to contain the substrings of one line of file String[] oneLine = new String[2]; int counter = 0; //keep track of line numbers System.out.println("Data read from the " + fileName + " file:"); //read file, one line at a time while (inFile.hasNext()) { String dataLine = inFile.nextLine(); oneLine = dataLine.split(","); //split line with delimiter if (counter > 0) //for second line and beyond, format doubles { System.out.printf("%.2ftt%.2fn", Double.parseDouble(oneLine[0]), Double.parseDouble(oneLine[1])); } else //if this first line, display the column heading System.out.println(oneLine[0] + "t" + oneLine[1]); if (inFile.hasNext()) counter++; //keep track of how many lines } //end while loop read file inFile.close(); //close the file System.out.println("The file has now been successfully read.n"); } //end of method //method to determine average values of columns two dim array public static double[] getColMeans(double[][] ar) { //local array to store means //array is sized according to length second dimension of parameter //first element is mean of first column //second element is mean of second column, etc double[] meanAr = new double[ar[0].length];
  • 4. //nested for loop to iterate through elements in parameter for (int i = 0; i < ar.length; i++) { for (int j = 0; j < ar[i].length; j++) { //sum the elements in the current column meanAr[j] += ar[i][j]; } } //end of outer loop //replace the sum with the average; i.e. divide by number of rows for (int i = 0; i < meanAr.length; i++) meanAr[i] /= ar.length; Lab16 Sample output