I am new to programming and for my class we were given an assignment where in java eclipse, we had to write a program that selects a text file(notepad) which has four numbers and computes it's average. We are required to use different methods and I am stuck, I researched everywhere and could not find anything, this is as far as I got and I don't know if I am at all close, the "getTheAverage" method is my issue.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.FileReader;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
public class Week04 {
public static void main(String[] args) throws IOException {
String theFile;
theFile = getTheFileName();
double theAverage;
theAverage = getTheAverage(theFile);
displayTheResult(theAverage,"The average is; ");
}
public static String getTheFileName(){
String theFile;
JFileChooser jfc = new JFileChooser();
jfc.showOpenDialog(null);
return theFile = jfc.getSelectedFile().getAbsolutePath();
}
public static double getTheAverage(String s) throws IOException{
double theAverage = 0;
FileReader fr = new FileReader(s);
BufferedReader br = new BufferedReader(fr);
String aLine;
while ( (aLine = br.readLine()) != null) {
theAverage = Double.parseDouble(s);
}
return theAverage;
}
public static void displayTheResult(double x, String s){
JOptionPane.showMessageDialog(null,s + x);
}
}
Try using a Scanner object instead. It seems like you are making this more difficult than it has to be.
// Get file name from user.
Scanner scnr = new Scanner(System.in);
System.out
.println("Please enter the name of the file containing numbers to use?");
String fileName = scnr.next();
scnr.close();
// Retrieve File the user entered
// Create File object
File file = new File(fileName);
try {
// Create new scanner object and pass it the file object from above.
Scanner fileScnr = new Scanner(file);
//Create values to keep track of numbers being read in
int total = 0;
int totalNumbers = 0;
// Loop through read in file and average values.
while (fileScnr.hasNext()) {
total += fileScnr.nextInt();
totalNumbers++;
}
//Average numbers
int average = total/totalNumbers;
// Close scanner.
fileScnr.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
// Quit Program if file input is bad.
System.exit(0);
}
Assuming that "average" indicates the arithmetic mean, you need to sum all the values parsed and then divide by the number of values you found. There are at least 4 problems with your code in this regard:
Double.parseDouble() is reading from the uninitialized variable s, instead of the value of the line you just read (which is in aLine)
You are not summing the values found
You are not keeping a tally of the NUMBER of values found
You are not dividing the sum by the tally
Based on your code, here's an example of how you might have done it.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.FileReader;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import java.util.ArrayList;
public class Week04 {
public static void main(String[] args) throws IOException {
String theFile;
theFile = getTheFileName();
double theAverage;
theAverage = getTheAverage(theFile);
displayTheResult(theAverage,"The average is; ");
}
public static String getTheFileName() {
String theFile;
JFileChooser jfc = new JFileChooser();
jfc.showOpenDialog(null);
return theFile = jfc.getSelectedFile().getAbsolutePath();
}
public static double getTheAverage(String s) throws IOException {
double value = 0, numValues = 0;
FileReader fr = new FileReader(s);
BufferedReader br = new BufferedReader(fr);
String aLine;
while ( (aLine = br.readLine()) != null) {
if (aLine.equals("")) continue;
value += Double.parseDouble(aLine);
numValues++;
}
if (numValues > 1) {
return value/numValues;
} else {
return value;
}
}
public static void displayTheResult(double x, String s){
JOptionPane.showMessageDialog(null,s + x);
}
}
Related
import java.awt.Graphics;
import java.awt.List;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundEsxception;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class Benford {
static Object i = null;
static ArrayList<String> list = new ArrayList<String>();
private static String data;
public static void BenfordPercents() {
int one = 0;
int two = 0;
int three = 0;
int four = 0;
int five = 0;
int six = 0;
int seven = 0;
int eight = 0;
int nine = 0;
return;
}
public static void main(String[] args) throws IOException {
DrawingPanel g = new DrawingPanel(500, 500);
Graphics brush = g.getGraphics();
String popData = null;
readCount(popData);
BenfordPercents();
}
public static void readCount(String popdata) throws IOException {
System.out.println("Please make sure the data file is name popData.txt");
System.out.println("We are loading popData.txt...");
Scanner console = new Scanner(System.in);
// Scanner console = new Scanner((new File("popData.txt")));
try {
i = new FileInputStream("popData.txt");
} catch (FileNotFoundException e) {
System.out.println("We cannot locate popData.txt");
System.out.println("Please make sure popData.txt is in the same location" + " as your code file!");
return;
}
System.out.println("popData.txt has loaded!");
System.out.println("");
System.out.println("Please press enter to show data!");
data = console.nextLine();
File file = new File(popdata + ".txt");
FileInputStream fis = new FileInputStream("popdata.txt");
byte[] flush = new byte[1024];
int length = 0;
while ((length = fis.read(flush)) != -1) {
list.add(new String(flush));
// System.out.println(new String(flush));
// System.out.println(list.toString());
}
// Scanner x = new Scanner((new File("popData.txt")));
// while(x.hasNext()){
// list.add(x.next());
// }
fis.close();
}
}
I have a text document with all the numbers of populiation from this link here:
https://en.wikipedia.org/wiki/List_of_countries_and_dependencies_by_population
The text document looks like this:
China 1369480000
India 1270250000
United 320865000
Indonesia 255461700
Brazil 204215000
Pakistan 189607000
..etc
..etc
the list is pretty long.
and when I try to store all of these numbers into an array list and I try to print the array list size it just returns 4?
If you want a list-entry for each line, you should prefer a BufferedReader.
FileInputStream fis = new FileInputStream("popdata.txt")
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
while((String line = br.readLine()) !=null) {
list.add(line);
}
The size of 4 is only the size of your arraylist - each element of your array list was build from an byte-array with a length of 1024. This means that your list either contains about 3K until 4K of data.
I have to write a code to take a text file, which contains integers and doubles, and to print the doubles in a file and the integers in another one. The text file is formatted in the following way:
double int int int
double int int int
...
double int int int
It is saved in the "raw.txt" file.
The output should look like:
int int int
int int int
...
int int int
This is what I have tried so far:
import java.io.*;
import java.util.*;
public class DATA {
public static void main(String[] args) throws FileNotFoundException {
PrintWriter writer = new PrintWriter(new File("sorted.txt"));
Scanner reader = new Scanner(new File("raw.txt"));
int temp = 0, count = 1;
while (reader.hasNext()) {
try {
temp = reader.nextInt();
}
catch (InputMismatchException e) {
reader.nextLine();
temp = (int) reader.nextDouble();
}
writer.print(temp);
if (count % 4 == 0)
writer.println();
count++;
}
writer.close();
reader.close();
}
}
The current code throws an InputMismatchException. All help is greatly appreciated.
Based on your provided code you only want to split the files and do not care about the double and int values itself. So you could handle the file as a normal text file and split the values by the separating blank character.
The snippet does some assumptions on the format of the raw.txt file and is not optimised. So it should be an easy task to amend it based on your needs.
public static void main(String[] args) throws IOException {
List<String> rawLines = Files.readAllLines(Paths.get("raw.txt"));
try (Writer intWriter = Files.newBufferedWriter(
Paths.get("int_values.txt"),
StandardOpenOption.CREATE_NEW);
Writer doubleWriter = Files.newBufferedWriter(
Paths.get("double_values.txt"),
StandardOpenOption.CREATE_NEW)) {
for (String line : rawLines) {
// the split might need to be amended if the values
// are not separated by a single blank
String[] values = line.split(" ");
// to be amended if there are not alway four values in a row
if (values.length != 4) {
continue;
}
doubleWriter.write(values[0]);
doubleWriter.write(System.lineSeparator());
intWriter.write(values[1]);
intWriter.write(' ');
intWriter.write(values[2]);
intWriter.write(' ');
intWriter.write(values[3]);
intWriter.write(' ');
intWriter.write(System.lineSeparator());
}
}
}
InputMismatchException can be thrown because it is nether Integer either Double
It is much better to read a part as a String and then decide
When it is deciding, it throws NumberFormatException which can be catched
In following code there are two writers separated as you wanted, It could looks better than this code maybe
I have corrected your writing to file. I havent tested it but I really think if you do writer.print(temp);, it will put all integers without spaces, which is useless then.
Try this code, but not tested
import java.io.*;
import java.util.*;
public class DATA {
public static void main(String[] args) throws FileNotFoundException {
PrintWriter writerInt = new PrintWriter(new File("sortedInt.txt"));
PrintWriter writerDou = new PrintWriter(new File("sortedDou.txt"));
Scanner reader = new Scanner(new File("raw.txt"));
int temp = 0, countInt = 1, countDou = 1;
while (reader.hasNext()) {
String next = reader.next();
try{
temp=Integer.parseInt(next);
writerInt.print(temp+" ");
if (countInt % 4 == 0)
writerInt.println();
countInt++;
}catch(NumberFormatException e){
try{
writerDou.print(Double.parseDouble(next)+" ");
if (countDou % 4 == 0)
writerDou.println();
countDou++;
}catch(NumberFormatException f){
System.out.println("Not a number");
}
}
}
writerInt.close();
writerDou.close();
reader.close();
}
}
I have a homework were the user have to input 10 word inside an array, but i cant find a way to do that
like for example if the user input this words:
abigail
wilbert
steve
android
lucky
hello
help
htc
matrix
kim
the output should be when i print the array
abigail
wilbert
steve
android
lucky
hello
help
htc
matrix
kim
this my program
import java.io.*;
class example
{
public static void main(String[] args) throws IOException
{
matrix obj=new matrix();
obj.practice();
}
}
class matrix
{
void practice() throws IOException
{
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
char A[][]=new char[10][10];
int r,c,i,j;
String x;
char b;
for(r=0;r<10;r++)
{
System.out.println("Enter the "+(r+1)+" word");
x=br.readLine();
for(c=0;c<x.length();c++)
{
A[r][c]=x.charAt(c);
}
}
for(i=0;i<10;i++)
{
for(j=0;j<10;j++)
{
System.out.print(A[i][j]);
}
} System.out.print("\n");
}
}
I'm not sure why your are using a multi-dimensional array. Here is a solution that will work for you that demonstrates some OO concepts.
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import javax.swing.*;
public class StringArrayOfWords {
//instance variables
private ArrayList<String> lines = new ArrayList<>();
private static StringArrayOfWords arr = new StringArrayOfWords();//declare object
public static void main(String[] args) throws Exception {
String [] printArray = arr.readFile();//use an array to hold contents of arr.readFile for easy printing
System.out.println(Arrays.toString(printArray));//Arrays.toString will print the contents of an Array
}
//method to read a file and call on object
public String [] readFile() throws Exception{
//display a gui window to choose a file to read in
JOptionPane.showMessageDialog(null, "Please choose a question file");
JFileChooser input = new JFileChooser();
int a = input.showOpenDialog(null);
String file = "";
if (a == JFileChooser.APPROVE_OPTION) {
File selectedFile = input.getSelectedFile();
file = selectedFile.getPath();
}
//use file input to read in line one at a time
FileInputStream fstream = new FileInputStream(file);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = br.readLine()) != null) {
lines.add(line);
}
//convert ArrayList to array
String[] arr = lines.toArray(new String[lines.size()]);
return arr;
}
}
Can anyone show me a basic guideline for how to do this sort of thing? Would you use an Array or an ArrayList, and why? Anything else I've found online is too complicated to understand for my level of experience with Java. The file is a simple text file with seven decimal values per line, and contains three lines. Here is what I have so far and am just testing it to see if I'm doing the ArrayList properly. It keeps printing an empty ArrayList that is just two brackets.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class SalesAnalysis
{
public static void main (String[] args) throws FileNotFoundException
{
Scanner salesDataFile = new Scanner(new File("SalesData.txt"));
ArrayList<Double> salesData = new ArrayList<Double>();
while(salesDataFile.hasNextDouble())
{
salesData.add(salesDataFile.nextDouble());
}
salesDataFile.close();
System.out.println(salesData);
}
}
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class SalesAnalysis
{
public static void main (String[] args) throws FileNotFoundException
{
Scanner salesDataFile = new Scanner(new File("SalesData.txt"));
ArrayList<Double> salesData = new ArrayList<Double>();
while(salesDataFile.hasNextLine()){
String line = salesDataFile.nextLine();
Scanner scanner = new Scanner(line);
scanner.useDelimiter(",");
while(scanner.hasNextDouble()){
salesData.add(scanner.nextDouble());
}
scanner.close();
}
salesDataFile.close();
System.out.println(salesData);
}
}
Read lines from file, then for each file get doubles using Scanner.
And for per line basis, you can just create Lists for every line, like:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class SalesAnalysis
{
public static void main (String[] args) throws FileNotFoundException
{
Scanner salesDataFile = new Scanner(new File("SalesData.txt"));
while(salesDataFile.hasNextLine()){
String line = salesDataFile.nextLine();
ArrayList<Double> salesData = new ArrayList<Double>();
Scanner scanner = new Scanner(line);
scanner.useDelimiter(",");
while(scanner.hasNextDouble()){
salesData.add(scanner.nextDouble());
}
scanner.close();
System.out.println(salesData);
}
salesDataFile.close();
}
}
As you are getting per line values inside first while() loop, you can do whatever with line.
// number of values in file
int totalNumValues = 0;
// total sum
double totalSum = 0;
while(salesDataFile.hasNextLine()){
String line = salesDataFile.nextLine();
ArrayList<Double> salesData = new ArrayList<Double>();
// total values in this line
int numValuesInLine = 0;
// sum in this line
double sumLine = 0;
Scanner scanner = new Scanner(line);
scanner.useDelimiter(",");
while(scanner.hasNextDouble()){
double value = scanner.nextDouble();
sumLine = sumLine + value;
numValuesInLine++;
totalNumValues++;
totalSum = totalSum + value;
}
scanner.close();
System.out.println(salesData);
}
I'd do something like this:
Scanner salesDataFile = new Scanner(new File("SalesData.txt"));
ArrayList<ArrayList< double > > salesData = new ArrayList<>();
while(salesDataFile.hasNextLine() )
{
String stringOfNumbers[] = salesDataFile.nextLine().split(",");
ArrayList< double > aux = new ArrayList<>( stringOfNumbers.length );
for( int i = 0; i < stringOfNumbers.length; ++i )
aux.get(i) = Double.parseDouble( stringOfNumbers[i] );
//... Perform your row calculations ...
salesData.add( aux );
}
salesDataFile.close();
System.out.println(salesData);
As #Justin Jasmann said, you have comma separated values, so technically they are more than just double values, why not read them as String and then parse them using Double.parseDouble(String s) after you have your comma separatad value by using string.split(","); on every line.
This is what you are looking for,
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class FileRead {
public static void main(String args[])
{
try{
// Open the file that is the first
FileInputStream fstream = new FileInputStream("textfile.txt");
// Use DataInputStream to read binary NOT text.
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
List<Double> saleNumbers= new ArrayList<Double>();
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Add number from file to list
saleNumbers.add( parseDecimal(strLine));
}
//Close the input stream
in.close();
System.out.println(saleNumbers);
}catch (Exception e){
e.printStackTrace();
}
}
public static double parseDecimal(String input) throws NullPointerException, ParseException{
if(input == null){
throw new NullPointerException();
}
input = input.trim();
NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.US);
ParsePosition parsePosition = new ParsePosition(0);
Number number = numberFormat.parse(input, parsePosition);
if(parsePosition.getIndex() != input.length()){
throw new ParseException("Invalid input", parsePosition.getIndex());
}
return number.doubleValue();
}
}
I've searched the internet for roughly an hour and a half now, and I can't for the life of me figure out where I've gone wrong.. Help!!
My problem is that every time I try and run it I don't receive an error until it searches for the file and without fail, it replies "File not found." I'm on a MAC I think I'm typing the directory in properly but something is messed up..
(When opening numEven.dat)
For my input I've tried "numEven.dat" (placing the dat file in the same directory as the java file)
I've also tried "/Users/java/numEven.dat" and "Users/java/numEven.dat"
I know it is in that directory. What am I doing wrong?
Main Class file:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class StatDriver
{
public static void main(String[] args)
{
String fileName = "";
Scanner scan = new Scanner(System.in);
double[] array = new double[20];
System.out.print(" Enter file name: ");
fileName = scan.next();
System.out.println("\n \n \n \n My Grades - View Statistics");
System.out.println(" ------------------------");
// int valueCount = readFile(array,fileName);
array = readFile(array, fileName);
Stat stat = new Stat(array, array.length);
// call each calc on Stat class and display results for each method
stat.calcAvg();
stat.calcMedian();
stat.findMax();
stat.findMin();
// print the return values for each of the above out to the user
}
public static double[] readFile(double[] array, String fileName)
{
int valueCount = 0;
FileIO importFile = new FileIO ();
importFile.main(array, fileName);
System.out.println(array);
valueCount = array.length;
// return valueCount;
return array;
}
}
FileIO class:
import java.util.Scanner;
import java.io.*;
public class FileIO
{
public void main (double[] array, String fileName)
{
double [] num = new double[5];
Scanner inFile;
int i = 0;
try
{
System.out.println(fileName);
inFile = new Scanner(new File("fileName"));
while(inFile.hasNextDouble())
{
array[i] = inFile.nextDouble();
i++;
}
inFile.close();
for(int x = 0; x < i; x++)
System.out.println(" " + num[x]);
}
catch(FileNotFoundException e)
{
System.out.println (" File not found");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println (" array index too large");
}
}
}
Try by changing
inFile = new Scanner(new File("fileName"));
with
inFile = new Scanner(new File(fileName));
in the method FileIO.main
Other than that (having no link to the problem), you could make the method FileIO.main static, and take advantage of Java collections to avoid hardcoding the number of elements of the double you want to read from the file. In the same method you are declaring a variable double[] num but not using it at all.