This code is supposed to read the csv file, use an array to add all the Axillary (Array[2]) together and find an average.
The only twist is that the IF statement is used because I want to split the data to two different variables depending on the value of (Array[3]) which will be either 1 or 2. and find the averages of them separately.
When i run this code, the output value is 0 for both.
package javainputoutput;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.File;
import java.util.Scanner;
public class JavaInputOutput
{
public static void main(String[] args)
{
int totalOverAxillary = 0;
int countOverAxillary = 0;
int totalLessAxillary = 0;
int countLessAxillary = 0;
String fileName = "haberman.txt";
try
{
Scanner InputStream = new Scanner(new File(fileName));
while (InputStream.hasNextLine())
{
String line = InputStream.nextLine();
String[] ary = line.split(",");
int noPosAxillary = Integer.parseInt(ary[2]);
int survivalStatus = Integer.parseInt(ary[3]);
if(survivalStatus == 1)
{
totalOverAxillary =+ noPosAxillary;
countOverAxillary++;
}
else if(survivalStatus == 2)
{
totalLessAxillary =+ noPosAxillary;
countLessAxillary++;
}
}
InputStream.close();
int aveOverAxillary = totalOverAxillary / countOverAxillary;
int aveLessAxillary = totalLessAxillary / countLessAxillary;
System.out.print("The average number of positive axillary nodes "
+ "for patients that survived 5 years or longer is "
+ aveOverAxillary);
System.out.println();
System.out.print("The average number of positive axillary nodes "
+ "for patients that died within 5 years is "
+ aveLessAxillary);
}
catch(FileNotFoundException e)
{
System.out.println("Cannot find file " + fileName);
}
catch(IOException e)
{
System.out.println("Problem with input from file " + fileName);
}
}
}
It seems you messed up the += operator. Instead of this:
totalOverAxillary =+ noPosAxillary;
It should be this:
totalOverAxillary += noPosAxillary;
You have the above mistake in two places, make sure to fix both.
The effect of this is that the total values will be equal to the last values, instead of the sums.
And when you divide those values by the counts,
probably the counts are smaller than the values,
and integer division results in zeros.
Related
How do I get data from a text file and save it into a string?
For example, my text file has the numbers 1, 4, 5, 6, 8, and 10.4. These numbers can be on the same line or on separate lines. I want to concatenate them into a string, like so: 1 4 5 6 8 10.4
import java.io.File;
import java.io.FileNotFoundException;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.Scanner;
public class f {
public static void main(String args[]) {
int count = 0;
double totalcount = 0;
double average = 0;
Scanner read = new Scanner(System.in);
Scanner file;
String input = "";
String test = "";
double[] array1 = new double[100];
while (true) {
System.out.println("Enter name of file or enter quit to exit");
input = read.next();
if (input.equalsIgnoreCase("quit")) {
break;
}
try {
file = new Scanner(new File(input));
if (!file.hasNextLine()) {
System.out.println(input + " file is empty");
}
while (file.hasNext()) {
totalcount = totalcount + file.nextDouble();
count++;
}
while (file.hasNext()) {
test = test + (" ") + file.next();
}
System.out.println("bla" + test);
average = totalcount / count;
DecimalFormat df = new DecimalFormat("#.###");
df.setRoundingMode(RoundingMode.CEILING);
System.out.println("\nCount: " + count);
System.out.println("Total: " + df.format(totalcount));
System.out.println("Average: " + df.format(average));
System.out.println();
} catch (FileNotFoundException e) {
System.out.println(input + " doesn't exist");
}
}
}
}
My code does not work correctly.
Your code is working fine, the problem is, you trying to access content of your file two times.after first while loop , the hasnext() method will return false.because you already accessed all the element in first while loop.
so it will not execute -
while (file.hasNext()) {
test = test + (" ") + file.next();
}
Other than that your code is fine.
if you want store it in string also then do small modification in your first while loop as below-
while (file.hasNext()) {
Double d=file.nextDouble();
test = test + (" ")+d;
totalcount = totalcount + d;
count++;
}
I think this will give you what you want.
Hello i think below code will be useful for you ,as per your question i have txt file with data , first i am getting the location of file & then i am trying to get the content , at last i am printing it to the console
File f = new File("D:\\temp.txt");
String content11 = FileUtils.readFileToString(f);
System.out.println(content11);
So we want an application to allow the user to enter the names and grades of students the user should be prompted for the name of the file to create and for the number of students to be entered (1 grade per student). Then the program takes all of the grades and averages them. The problem is that it is not reading the file and always gives us a average of -0.0.
`
public static void main(String[] args) throws IOException {
System.out.println("What is the name of the file you would like to create?");
filename = p.next();
File fd = new File(filename + ".txt");
fd.createNewFile();
students(fd);
}
public static void students(File fd) throws IOException {
int numbstudents;
FileWriter ap = new FileWriter(fd, true);
BufferedWriter ad = new BufferedWriter(ap);
System.out.println("How many students would you like to add?");
numbstudents = p.nextInt();
int i = 0;
while (i != numbstudents) {
for (i = 0; i < numbstudents; i++) {
System.out.println("What is the name of student number " + i + " ?");
String name = p.next();
ad.write(name);
ad.newLine();
System.out.println("What grade did student number " + i + " acheive?");
String a = f.next();
ad.write(a);
ad.newLine();
}
}
read(fd);
ad.close();
}
public static void read(File fd) throws FileNotFoundException {
int counter = 0;
FileReader h;
BufferedReader g;
String test;
double average, total = 0;
int number = 0;
int i = 0;
try {
h = new FileReader(fd);
g = new BufferedReader(h);
while ((test = g.readLine()) != null) {
number += 1;
System.out.println(test);
counter = counter + 1;
i = counter % 2;
if (i == 0) {
total += Double.parseDouble(test);
}
}
average = total / (number - 1);
System.out.println("The students average is: " + average);
g.close();
fd.delete();
} catch (FileNotFoundException e) {
System.out.println("File could not be found.");
} catch (IOException e) {
System.out.println("Your file could not be read.");
}
}
}
`
You're attempting to read from the file before you've closed the writer.
The close() call includes flushing buffered data to disk. You're reading before data is flushed to disk.
As a side note, consider what you're accomplishing with this pair of statements:
while (i != numbstudents) {
for (i = 0; i < numbstudents; i++) {
The while is unnecessary. The for statement iterates over the comfortably numb students.
Also note the difference in conditions between the two. In general, when iterating over numbers, it's safer to use '<', '<=', '>' or '>=' than '==' or '!='. Otherwise, if you pass by the endpoint before an equality condition, it will continue happily past the end.
Finally, consider naming your methods with descriptive verb phrases. This will help you with breaking the big problem down into smaller pieces. For example, you could have one method called inputStudents() that reads input and creates and closes the file, called before another method printAverageOfStudents() that reads the file and computes the average.
I am working on an assignment, my program is supposed to read grades from a file and output an average. My code compiles, but the output is always 0.0.
Code is as follows:
import java.util.Scanner;
import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;
public class testScores
{
public static void main ( String [] args )
{
int i;
int c;
double [] testScores = new double[7];
i=0;
try
{
Scanner scan = new Scanner( new File ( "testScores.txt") );
while( scan.hasNext() )
{
String temp = scan.nextLine();
testScores[i] = Double.parseDouble(temp);
i++;
}
scan.close();
}
catch ( FileNotFoundException fnfe )
{
System.out.println("Unable to find the testScores.txt file. Program terminating.");
}
catch (Exception e)
{
e.printStackTrace();
}
double avgStart = 0;
double avgFinal;
int gradeCount = 1;
while ( i < testScores.length)
{
avgStart += testScores[i];
i++;
}
avgFinal = avgStart / i;
System.out.println("The final average of all of the test scores in the file testScores.txt are " + avgFinal + ".");
}
}
Please give any insight into it. I'am not sure how the code gets to zero.
If you divide by an integer then your result will be an integer
With integer division
1.0 / 2 == 0
so change
avgFinal = avgStart / i;
to
avgFinal = avgStart / (double) i;
Your i value is already equal to lenght of array. So its not going in while loop.
int j = 0;
int gradeCount = 1;
while ( j < testScores.length)
{
avgStart = avgStart += testScores[i];
j++;
}
avgFinal = avgStart / i;
System.out.println("The final average of all of the test scores in the file testScores.txt are " + avgFinal + ".");
}
Can you please explain exactly what the program is supposed to do.
I am pretty sure you want to reset i to 0 (i = 0) before the last while.
First of all - the program is not very well written. It is all static, doesn't follow the java object oriented programming paradigm. I guess it is OK for a students program though.
First check if the file is properly read. If you are reading line by line you should use while( scan.hasNextLine() )
The way you have written it testScores is always 7 items. If the file is longer you will get ArrayIndexOutOfBoundsException, if there are less you will get incorrect average because it will fill the array with 0. You can check the java collections for example ArrayList.
And now the actual problem that causes your program to return 0:
You use the i variable in the first cycle for scanning. Its value is increased when you use it in the second cycle.
You can use another variable or set the value of i to 0 before the second while and it will work.
I have the code below so far. I know the median is wrong because I've placed numbers in it and what I really want is for the program to extract these from the file on its own since the numbers may change. I am not sure how to have the program get the 2 numbers in order to retrieve and calculate the median. Please help. I am very new to this and it has taken me all day to get this far!
package trials;
import java.util.Scanner;
import java.io.IOException;
import java.io.File;
public class trials2 {
public static void main(String[] args) throws IOException {
// This is a Scanner object that reads from the keyboard
Scanner in = new Scanner(System.in);
// The following is set to find the file
System.out.println("Please enter the name of your data file: ");
String fileName = in.next();
// The file is then to be scanned
Scanner fileToRead = new Scanner(new File(fileName));
// This loop finds the contents within the file
double sum = 0;
int numStudents = 0;
double maxVal = 0, minVal = 0;
boolean bFirstTime = true;
double currVal;
while (fileToRead.hasNext()) {
if (fileToRead.hasNextDouble()) {
numStudents++;
currVal = fileToRead.nextDouble();
// The following will find the maximum and minimum values within the file
if (bFirstTime) {
maxVal = currVal;
minVal = currVal;
bFirstTime = false;
} else {
maxVal = Math.max(maxVal,currVal);
minVal = Math.min(minVal, currVal);
}
sum += currVal;
} else {
fileToRead.next();
}
}
// Prints out comments and results
System.out.println("***Welcome to the Exam Statistics Program!!***");
System.out.println();
System.out.println("Minimum = " + minVal);
System.out.println("Maximum = " + maxVal);
System.out.println("Average score: " + sum/numStudents);
System.out.println();
System.out.println("Number of scores by letter grade: ");
System.out.println();
System.out.println("There are " + numStudents + " scores");
}
}
There are a few steps to doing this.
At the beginning of your program, create an ArrayList<Double> for storing your values in.
Within your main loop, use the list's add method to add each value as you read it.
At the end of your loop, Use Collections.sort to sort your list.
Use the following logic to work out the median.
If the size of the list is zero, then there's no median.
If the size of the list is odd, then the median is the value at position size() / 2 of the list.
If the size of the list is even, then the median is the average of the value at position size() / 2 - 1 and size() / 2 of the list.
I deliberately haven't given you code, because I think you're enjoying learning how to do this for yourself. But feel free to post a comment if you need more detail on any particular step.
I having some trouble with an APCS assignment. The program is supposed to read strings with a length of two from a text file - test1.txt - and print out percentages of: a) girl-girl, boy-boy, boy-girl or girl-boy combinations, and b) the total number of individual groups.
I've been trying for an hour to figure this out! Although I'm suspicious of the String declaration in line 25, I don't have a way to confirm that. Furthermore, I'm worried that I messed up my if-else-if-else loop without prompting a compiler error.
The source code is attached for your reference. If you need any additional information, please don't hesitate to ask.
Since I'm a new user with a reputation < 10, please see the attached image:
For elaboration on what isn't working. I took a screenshot and wrote relevant comments on it!
/**
* Family takes user input of sets of boys, girls, and boys + girls. Results are then
* tabulated and displayed in a percentage form to the user. The total number of
* individuals are also displayed.
*
* #E. Chu
* #Alpha
*/
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
public class Family {
public static void main (String[] args) throws IOException {
int boyCount = 0;
int girlCount = 0;
double boyGroupCount = 0.0;
double girlGroupCount = 0.0;
int mixedGroupCount = 0;
int totalPersonCount = 0;
double totalGroupCount;
String currentToken = " ";
Scanner inFile = new Scanner (new File ("test1.txt"));
while (inFile.hasNextLine()) {
currentToken = inFile.nextLine( );
if (currentToken == "BG") {
boyCount++;
girlCount++;
mixedGroupCount++; }
else if (currentToken == "GB") {
boyCount++;
girlCount++;
mixedGroupCount++; }
else if (currentToken == "BB") {
boyCount += 2;
boyGroupCount++; }
else {
girlCount += 2;
girlGroupCount++; }
}
inFile.close();
totalPersonCount = boyCount + girlCount;
totalGroupCount = boyGroupCount + girlGroupCount + mixedGroupCount;
System.out.println("Sample Size: " + totalPersonCount);
System.out.println("Two Boys (%): " + boyGroupCount / totalGroupCount + "%");
System.out.println("One Boy, One Girl (%): " + mixedGroupCount + "%");
System.out.println("Two Girls (%): " + girlGroupCount / totalGroupCount + "%");
} // End of main method.
} // End of class Family.
currentToken == "BB" should be currentToken.equals("BB")
Don't use == use the method equals instead
Hint: you don't want to compare strings using ==, look into the equals method.