I have a text file that I have to use in my program. I have already created
a file reader to display the contents of the file. However, I don't want to display all of the content but display the number of words.
For example, my file named database is a file that displays the priceof each individual and has four lines that display the name, age, activity and the price. I want to create a report which shows the total number of basketball players and total number of soccer players and then display the average price.
Here is my code so far:
String fileName = "database.txt";
try {
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferReader = new BufferedReader(fileReader);
while ((line = bufferReader.readLine()) != null) {
}
}
How can I count and add the total values of basketball as well as soccer for the output as well as obtaining each fee and calculating the total and average?
You can the try the below code. You can split the lines from file with whitespace and use them. I have used an if condition in else part, because if any other type of sport comes in the file.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Player {
public static void main(String[] args) throws IOException {
int basketballCount = 0;
int soccerCount = 0;
double basketballFee = 0.0;
double soccerFee = 0.0;
BufferedReader read = new BufferedReader(new FileReader("database.txt"));
String line;
while ((line = read.readLine()) != null) {
String parts[] = line.split(" ");
if (parts[3].equals("basketball")) {
basketballCount++;
basketballFee = basketballFee + Double.parseDouble(parts[4]);
} else if (parts[3].equals("soccer")) {
soccerCount++;
soccerFee = soccerFee + Double.parseDouble(parts[4]);
}
}
System.out.println("Total Player: "+basketballCount + "\tTotal Fee: " + basketballFee + "\tAvg Fee:" + basketballFee/basketballCount);
System.out.println("Total Player: "+soccerCount + "\tTotal Fee: " + soccerFee + "\tAvg Fee:" + soccerFee/soccerCount);
}
}
You might want to take a look at String#split(). Essentially, the code will look like this:
String[] tokens = line.split(" ");
double value = Double.valueOf(tokens[4]);
String sport = tokens[3];
Then you can do whatever you want to those values. The official documentation for the method:
Splits this string around matches of the given regular expression.
This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array
Returns:
the array of strings computed by splitting this string around matches of the given regular expression
This code reads the file using Scanner and then finds average of basketball fee and soccer fee it is self explanatory if there is any please comment
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class StackOverflow
{
public static void main(String[] args) throws FileNotFoundException
{
Scanner sc = new Scanner(new File("database.txt"));
int basketball = 0;
int soccer = 0;
double basketfee = 0.0, soccerfee = 0.0;
while (sc.hasNextLine())
{
String line = sc.nextLine();
if (line.contains("basketball"))
{
basketball++;
String fee = line.substring(line.lastIndexOf(' '));
fee = fee.trim();
basketfee = basketfee + Double.parseDouble(fee);
}
else if (line.contains("soccer"))
{
soccer++;
String fee = line.substring(line.lastIndexOf(' '));
fee = fee.trim();
soccerfee = soccerfee + Double.parseDouble(fee);
}
}
System.out.println("Average fee for basketball is " + basketfee / basketball);
System.out.println("Average fee for soccer is " + soccerfee / soccer);
}
}
Related
Have to add extra line "String x=in.readLine();" after reading character "sec=(char)in.read();" otherwise program is not proceeding further to take more inputs, see comment below in code. Please note I don't want to use scanner class.
import java.io.*;
class marks
{
public static void main(String args[])
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
int rl,m1,m2,m3,tot=0;
String nm,cl;
nm=cl="";
char sec='A';
double avg=0.0d;
try
{
System.out.println("Enter the information of the student");
System.out.print("roll no:");
rl=Integer.parseInt(in.readLine());
System.out.print("class:");
cl=in.readLine();
System.out.print("section:");
sec=(char)in.read();
String x=in.readLine(); /* have to add this line only then marks of 3 subject can be inputed */
System.out.println("marks of three subjects "+x);
m1=Integer.parseInt(in.readLine());
m2=Integer.parseInt(in.readLine());
m3=Integer.parseInt(in.readLine());
tot=m1+m2+m3;
avg=tot/3.0d;
System.out.println("total marks of the students = "+tot);
System.out.println("avg marks of the students = "+avg);
}
catch (Exception e)
{};
}
}
How about replacing:
sec=(char)in.read();
with:
sec = in.readLine().charAt(0);
solved
import java.io.BufferedReader;
import java.io.InputStreamReader;
class Marks {
public static void main(String args[]) {
try (BufferedReader in = new BufferedReader(new InputStreamReader(System.in))) {
int rl, m1, m2, m3, tot = 0;
String nm, cl;
nm = cl = "";
char sec = 'A';
double avg = 0.0d;
System.out.println("Enter the information of the student");
System.out.print("roll no:");
rl = Integer.parseInt(in.readLine());
System.out.print("class:");
cl = in.readLine();
System.out.print("section:");
sec = in.readLine().charAt(0); //changes are here, instead of
// String x = in.readLine(); /* have to add this line only then marks of 3
// subject can be inputed */
System.out.println("marks of three subjects ");
m1 = Integer.parseInt(in.readLine());
m2 = Integer.parseInt(in.readLine());
m3 = Integer.parseInt(in.readLine());
tot = m1 + m2 + m3;
avg = tot / 3.0d;
System.out.println("total marks of the students = " + tot);
System.out.println("avg marks of the students = " + avg);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output
Enter the information of the student
roll no:21
class:10
section:c
marks of three subjects
56
65
56
total marks of the students = 177
avg marks of the students = 59.0
The problem is when you use in.read() according to documentation:"Reads a single character," but you are actually typing 'two' characters: one char and one '\n' which is stored in the InputStreamReader's buffer and will be read again when you use in.readLine();
my program is meant to read from a txt and print certain parts of it. when i try to set Double d4 it gives me an error saying that string is
empty although it's not. and it's also not an issue of formatting since d1-5 worked fine when i removed the line. i also printed data[5] and that showed the proper line from the txt.
import java.util.Scanner;
import java.io.*;
import java.text.DecimalFormat;
import java.util.ArrayList;
public class AAAAAA {
public static void main (String[] args)throws IOException {
final String fileName = "classQuizzes.txt";
//1)
Scanner sc = new Scanner(new File(fileName));
//declarations
String input;
double total = 0.0;
double num = 0;
double count = 0;
double average = 0;
String lastName;
String firstName;
double minimum;
double max;
//2) process rows
input = sc.nextLine();
System.out.println(input);
while (sc.hasNextLine()) {
String line = sc.nextLine();
System.out.println(line);
// split the line into pieces of data separated by the spaces
String[] data = line.split(" ");
// get the name from data[]
System.out.println("d5 " +data[4]);
firstName = data[0];
lastName = data[1];
Double d1 = Double.valueOf(data[2]);
Double d2 = Double.valueOf(data[3]);
Double d3 = Double.valueOf(data[4]);
Double d4 = Double.valueOf(data[5]);
Double d5 = Double.valueOf(data[6]);
// do the same...
System.out.println("data " + d3);
total += d1 + d2 + d3 + d5;
count++;
//find average (decimal 2 points)
System.out.println(count);
average = total / count;
System.out.println("Total = " + total);
System.out.println("Average = " + average);
//3) class statistics
//while
}
System.out.println("Program created by");
}
}
The line might not be empty, but when you split it at spaces, if there are two spaces in a row, you will get empty strings in the split. To prevent this, change
String[] data = line.split(" ");
to
String[] data = line.split(" *");
or, perhaps better, since it will deal with tabs and other white space:
String[] data = line.split("\\s*");
To track down these kinds of problems yourself (and to verify that I've diagnosed the problem correctly), you should print out each element of the split array, as well as verify the array length is what you expect.
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);
I have a homework assignment to read data from a file which contains names and scores per game of basketball players. The program is supposed to output the names and scores of the players, as well as tally each player's average score per game, and finally display the player with the highest average. I am currently stuck on trying to get the average and a newline character for each player.
Here is a pic of the input file I am reading the data from.
and here is my code:
import java.util.Scanner;
import java.io.File;
import java.io.PrintWriter;
import java.io.IOException;
public class BasketballTeam
{
public static void main(String[] args) throws IOException
{
File f = new File("BasketballData.txt");
if (f.exists())
{
Scanner input = new Scanner(f);
int games = 0;
int totalScore = 0;
double avg = 0.0;
while (input.hasNext())
{
String s = input.next();
System.out.printf("%-9s", s);
int a = input.nextInt();
while (input.hasNextInt())
{
if (a == -1)
{
avg = (double)totalScore/games;
System.out.printf("%14s%.2f\n", "Average of ", avg);
games = 0;
totalScore = 0;
s = input.next();
}
else
{
System.out.printf("%5s", a);
games++;
totalScore = totalScore + a;
a = input.nextInt();
}
}
}
}
}
}
When I run the program, my output is just a single line that looks like:
Smith 13 19 8 12Badgley 5Burch 15 18 16Watson......and so on
Why am I not getting any newline characters or my average? I want my output to look like this:
Smith 13 19 8 12 Average of 13
Badgley 5 Average of 5
Burch 15 18 16 Average of 16.33
.....and so on
Thanks in advanced for any suggestions/corrections.
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class BasketballTeam
{
public static void main(String[] args) throws IOException
{
File f = new File("BasketballData.txt");
if (f.exists())
{
Scanner input = new Scanner(f);
int games = 0;
int totalScore = 0;
double avg = 0.0;
while (input.hasNext())
{
String s = input.next();
System.out.printf("%-9s", s);
while (input.hasNextInt())
{
int a = input.nextInt();
if(a != -1)
{
System.out.printf("%5s", a);
games++;
totalScore = totalScore + a;
}
}
avg = (double)totalScore/games;
System.out.printf("%14s%.2f\n", "Average of ", avg);
games = 0;
totalScore = 0;
System.out.println();
}
input.close();
}
}
}
This is what you are looking for. You don't even need the -1 at the end of each line in the file you can get rid of that if you want unless it is part of the specification. It will work without the -1. Your inner loop you just want to add up your totals then outside of the inner loop get your average and display. Then reset your variables. You were pretty close just needed to change a couple things. If you have any questions on how this works just ask away. Hope this helps!
Try
avg = ((double)totalScore/(double)games);
and replace \n with \r\n:
System.out.printf("%14s%.2f\r\n", "Average of ", avg);
I would highly recommend using a FileReader:
File file = new File("/filePath");
FileReader fr = new FileReader(file);
Scanner scanner = new Scanner(fr);
//and so on...
In this line a = input.nextInt(), you already advance to the next int, so the test input.hasNextInt() will be false when you reach -1.
One possible solution is to change the loop to:
while (input.hasNext()) {
String s = input.next();
System.out.printf("%-9s", s);
int a = 0;
while (input.hasNextInt()) {
a = input.nextInt();
if (a == -1) {
avg = (double) totalScore / games;
System.out.printf("%14s%.2f\n", "Average of ", avg);
games = 0;
totalScore = 0;
} else {
System.out.printf("%5s", a);
games++;
totalScore = totalScore + a;
}
}
}
I'm new to Java, and struggling with something I've never had trouble with in the past. For whatever reason, I can't scan an int (or a double) in my code, but I can scan a string just fine. I'm posting the snippet where my scanner isn't functioning, please let me know if I should include the rest of the program.
import java.util.Scanner;
import java.io.File;
import java.io.PrintWriter;
import java.io.IOException;
public class DZP3
{
public static void main(String[] args) throws IOException
{
announce();
Scanner scan = new Scanner(System.in);
//Prompt user for input file
System.out.println("Greetings! Please enter the filename of the plaintext olympics data file you'd like to open.");
String txtFilename = scan.nextLine();
//Opens olympics data txt file specified, exits if it does not exist
File medalsInput = new File (txtFilename);
if(!medalsInput.exists())
{
System.out.println("File not found. Reload and try again.");
System.exit(1);
}
//Prompt user for output file
System.out.println("Thanks. Please enter the filename of the plaintext data output file.");
String outputTxt = scan.nextLine();
//Create output file specified
File medalsOutput = new File (outputTxt);
//Prompt user for medal cutoff X value
System.out.println("Thanks. Please enter the minimum number of medals a nation must have earned to be counted for calculation 2 listed above. \nEnter the value, as an integer:");
int medalsCutoff = 0;
medalsCutoff = scan.nextInt();
fileProcessing(medalsInput, medalsOutput, medalsCutoff);
}
}
Near the bottom, medalsCutoff is not accepting any scanned value whatsoever. I've tried putting it in a method other than main, I've tried rearranging it, creating a separate scanner just for it, and a few other things. The debugger shows that, no matter what, I'm stuck on that line of code. What have I done wrong? I'm at a loss.
EDIT: Here's the fileProcessing method, and what comes after. The announce method is just system.out.println.
public static void fileProcessing(File medalsIn, File medalsOut, int medalsMin) throws IOException
{
//Initialize necessary variables and strings
int maxTotMedals = -1;
int natCountMedalsMin = 0;
int natHiScore = -1;
String natName;
String answerOne = "DEFAULT";
int answerTwo = 0;
String answerFour = "DEFAULT";
//Create Printwriter
PrintWriter pw = new PrintWriter(medalsOut);
//Create scanner to read from file, loop until end of file
Scanner filescan = new Scanner(medalsIn);
while (filescan.hasNext())
{
//Initializes medal counting variables at zero, resetting the values with each line
int gCount = 0;
int sCount = 0;
int bCount = 0;
natName = filescan.next();
int lineMedals = 0;
while (lineMedals < 4); //Runs 4 times to cover all four years
{
gCount += filescan.nextInt();
sCount += filescan.nextInt();
bCount += filescan.nextInt();
lineMedals++;
}
int totalMedals = gCount + sCount + bCount;
//Sees if this line's medals have exceeded previous total medal record, if yes, sets country name as answer to question one
if (totalMedals > maxTotMedals)
{
answerOne = natName;
maxTotMedals = totalMedals;
}
if (totalMedals >= medalsMin)
{
natCountMedalsMin++; //For answer two
}
//Score calculation
int natScore = gCount*3;
natScore += sCount*2;
natScore += bCount;
//Compares score to highest score, for answer four
if (natScore > natHiScore)
{
answerFour = natName;
natHiScore = natScore;
}
//Write nation name and score to file
pw.println(natName + " " + natScore);
}
//Define answer two after all countries have been counted
answerTwo = natCountMedalsMin;
//Close output file
pw.close();
//Send results to answer method
answerPrint(answerOne, answerTwo, answerFour, medalsMin, natHiScore);
}
//This method outputs the answers to the user.
public static void answerPrint(String answerEin, int answerZwei, String answerVier, int medalsMini, int HiScore)
{
System.out.println("File read successfully.");
System.out.println("The nation that earned the greatest number of medals is " + answerEin + ".");
System.out.println(answerZwei + " countries earned more than " + medalsMini + " medals.");
System.out.println("The nation with the highest score is " + answerVier + " with a score of " + HiScore + ".");
System.out.println("Thank you for using this program. Until next time!");
}
EDIT 2: This has been solved, I had a stray semicolon in my fileProcessing method that caused an infinite loop. Thank you all for your help.
while (lineMedals < 4);
Above line has a semicolon at the end. It is an infinite loop.
after file creation ,you use this below method
File medalsOutput = new File (outputTxt);
medalsOutput.createNewFile()
in ur code file not got created and exiting via syste.exit(1)