Java text file remove doubles from four column text file - java

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();
}
}

Related

Reading txt files in Java

I have program that has a section that requires me to read and append items to a txt file. I know how to do basic reading and appending but I am confused as to how I would read every 4th line in a txt file and then store it in a variable. Or even every alternate line.
Also, if there are double valued numbers, can I read it as a number and not a string?
To read say every fourth line from a text file you would read a line and update a counter. When the counter reaches 4, you save the line in a String variable. Something like this would do the job:
import java.io.*;
public class SkipLineReader {
public static void main(String[] args) throws IOException {
String line = "";
String savedLine = "";
int counter = 0;
FileInputStream fin = new FileInputStream("text_file.txt");
BufferedReader bufIn = new BufferedReader(new InputStreamReader(fin));
// Save every fourth line
while( (line = bufIn.readLine()) != null) {
counter++;
if( counter == 4 ) {
savedLine = line;
System.out.println(line);
}
}
}
}
To save every alternate line, you would save the line every time the counter reaches two and then reset the counter back to zero. Like this:
// Save every alternate line
while( (line = bufIn.readLine()) != null) {
counter++;
if( counter % 2 == 0 ) {
counter = 0;
savedLine = line;
System.out.println(line);
}
}
As for reading doubles from a file, you could do it with a BufferedReader and then use Double's parseDouble(string) method to retrieve the double value, but a better method is to use the Scanner object in java.util. The constructor for this class will accept a FileInputStream and there is a nextDouble() method that you can use to read a double value.
Here's some code that illustrates using a Scanner object to grab double values from a String (to read from a file, supply a FileInputStream into the Scanner class's constructor):
import java.util.*;
public class ScannerDemo {
public static void main(String[] args) {
String s = "Hello World! 3 + 3.0 = 6 true";
// create a new scanner with the specified String Object
Scanner scanner = new Scanner(s);
// use US locale to be able to identify doubles in the string
scanner.useLocale(Locale.US);
// find the next double token and print it
// loop for the whole scanner
while (scanner.hasNext()) {
// if the next is a double, print found and the double
if (scanner.hasNextDouble()) {
System.out.println("Found :" + scanner.nextDouble());
}
// if a double is not found, print "Not Found" and the token
System.out.println("Not Found :" + scanner.next());
}
// close the scanner
scanner.close();
}
}
This is my code example.
public static void main(String[] args) throws Exception {
// Read file by BufferedReader line by line.
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader("test.txt"));
String line = reader.readLine();
while (line != null) {
line = line.trim();
System.out.println(line);
// Using regular expression to check line is valid number
if (!line.trim().equals("") && line.trim().matches("^\\d+||^\\d+(\\.)\\d+$")) {
double value = Double.valueOf(line.trim());
System.out.println(value);
} else {
String value = line.trim();
System.out.println(value);
}
// Read next line
line = reader.readLine();
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}

Finishing File Class

I keep getting an error telling me lineNumber cannot be resolved to a variable? I'm not really sure how to fix this exactly. Am I not importing a certain file to java that helps with this?
And also how would I count the number of chars with spaces and without spaces.
Also I need a method to count unique words but I'm not really sure what unique words are.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.ArrayList;
import java.util.List;
public class LineWordChar {
public void main(String[] args) throws IOException {
// Convert our text file to string
String text = new Scanner( new File("way to your file"), "UTF-8" ).useDelimiter("\\A").next();
BufferedReader bf=new BufferedReader(new FileReader("way to your file"));
String lines="";
int linesi=0;
int words=0;
int chars=0;
String s="";
// while next lines are present in file int linesi will add 1
while ((lines=bf.readLine())!=null){
linesi++;}
// Tokenizer separate our big string "Text" to little string and count them
StringTokenizer st=new StringTokenizer(text);
while (st.hasMoreTokens()){
s = st.nextToken();
words++;
// We take every word during separation and count number of char in this words
for (int i = 0; i < s.length(); i++) {
chars++;}
}
System.out.println("Number of lines: "+linesi);
System.out.println("Number of words: "+words);
System.out.print("Number of chars: "+chars);
}
}
abstract class WordCount {
/**
* #return HashMap a map containing the Character count, Word count and
* Sentence count
* #throws FileNotFoundException
*
*/
public static void main() throws FileNotFoundException {
lineNumber=2; // as u want
File f = null;
ArrayList<Integer> list=new ArrayList<Integer>();
f = new File("file_stats.txt");
Scanner sc = new Scanner(f);
int totalLines=0;
int totalWords=0;
int totalChars=0;
int totalSentences=0;
while(sc.hasNextLine())
{
totalLines++;
if(totalLines==lineNumber){
String line = sc.nextLine();
totalChars += line.length();
totalWords += new StringTokenizer(line, " ,").countTokens(); //line.split("\\s").length;
totalSentences += line.split("\\.").length;
break;
}
sc.nextLine();
}
list.add(totalChars);
list.add(totalWords);
list.add(totalSentences);
System.out.println(lineNumber+";"+totalWords+";"+totalChars+";"+totalSentences);
}
}
In order to get your code running you have to do at least two changes:
Replace:
lineNumber=2; // as u want
with
int lineNumber=2; // as u want
Also, you need to modify your main method, you can not throw an exception in your main method declaration because there is nothing above it to catch the exception, you have to handle exceptions inside it:
public static void main(String[] args) {
// Convert our text file to string
try {
String text = new Scanner(new File("way to your file"), "UTF-8").useDelimiter("\\A").next();
BufferedReader bf = new BufferedReader(new FileReader("way to your file"));
String lines = "";
int linesi = 0;
int words = 0;
int chars = 0;
String s = "";
// while next lines are present in file int linesi will add 1
while ((lines = bf.readLine()) != null) {
linesi++;
}
// Tokenizer separate our big string "Text" to little string and count them
StringTokenizer st = new StringTokenizer(text);
while (st.hasMoreTokens()) {
s = st.nextToken();
words++;
// We take every word during separation and count number of char in this words
for (int i = 0; i < s.length(); i++) {
chars++;
}
}
System.out.println("Number of lines: " + linesi);
System.out.println("Number of words: " + words);
System.out.print("Number of chars: " + chars);
} catch (Exception e) {
e.printStackTrace();
}
}
I've used a global Exception catch, you can separate expetion in several catches, in order to handle them separatedly. It gives me an exception telling me an obvious FileNotFoundException, besides of that your code runs now.
lineNumber variable should be declared with datatype.
int lineNumber=2; // as u want
change the first line in the main method from just lineNumber to int lineNumber = 2 by setting its data type, as it is important to set data type of every variable in Java.

Saving an ArrayList to .txt file

So, I was wondering if it's possible to save values from an ArrayList to a file, such as "inputs.txt". I've seen a question similar to this: save changes (permanently) in an arraylist?, however that didn't work for me, so I'm wondering if I'm doing something wrong. Here are my files:
Main.class
package noodlegaming.geniusbot.main;
import java.io.*;
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
import java.util.logging.Logger;
public class Main {
public static Random rand = new Random();
public static void readFileByLine(String fileName) {
try {
File file = new File(fileName);
Scanner scanner = new Scanner(file);
while (scanner.hasNext()) {
SentencesToUse.appendToInputtedSentences(scanner.next().toString());
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
static File inputsFile = new File("inputs.txt");
static PrintWriter printWriter = new PrintWriter(inputsFile);
public static void main(String[] args) throws IOException, InterruptedException {
if(!inputsFile.exists()) {
inputsFile.createNewFile();
}
readFileByLine("inputs.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Hello, welcome to GeniusBot. Shortly, you will be speaking with a computer that learns from what you say.");
System.out.println("Because of this circumstance, we ask that you do not type any curses, swear words, or anything otherwise considered inappropriate,");
System.out.println("as it may come back to the light at a time you don't want it to.");
System.out.println("Please note that your responses won't be saved if you close the program.");
System.out.println("If you type printInputsSoFar, a list of all the stuff you've typed will be printed.");
System.out.println("If you type printInputsLeft, the number of inputs you have left will be printed.");
System.out.println("If you type clearInputs, the program will be closed and the inputs.txt file deleted, " +
"\nand recreated upon startup.");
System.out.println("Starting up GeniusBot.");
Thread.sleep(3000);
System.out.println("Hello! I am GeniusBot!");
br.readLine();
System.out.println("" + SentencesToUse.getBeginningSentence() + "");
for (int i = 0; i < 25; i++) {
String response = br.readLine();
if (response.equals("printInputsSoFar")) {
for (int j = 1; j < SentencesToUse.inputtedSentences.size(); j++) {
System.out.println(SentencesToUse.inputtedSentences.get(j));
}
i--;
} else if (response.equals("printInputsLeft")) {
int inputsLeft = 25 - i;
System.out.println("You have " + inputsLeft + " inputs left.");
i--;
} else if (response.equals("clearInputs")) {
printWriter.close();
inputsFile.delete();
Thread.currentThread().stop();
} else {
SentencesToUse.appendToInputtedSentences(response);
printWriter.println(response);
printWriter.flush();
int inputtedSentence = Main.rand.nextInt(SentencesToUse.inputtedSentences.size());
String inputtedSentenceToUse = SentencesToUse.inputtedSentences.get(inputtedSentence);
System.out.println(inputtedSentenceToUse);
}
if (i == 24) {
System.out.println("Well, it was nice meeting you, but I have to go. \nBye.");
Thread.currentThread().stop();
printWriter.close();
}
}
}
}
SentencesToUse.class:
package noodlegaming.geniusbot.main;
java.util.ArrayList;
import java.util.List;
public class SentencesToUse {
public static String[] beginningSentences = {"What a lovely day!", "How are you?", "What's your name?"};
static int beginningSentence = Main.rand.nextInt(beginningSentences.length);
static String beginningSentenceToUse = beginningSentences[beginningSentence];
public static String getBeginningSentence() {
return beginningSentenceToUse;
}
public static List<String> inputtedSentences = new ArrayList<String>();
public static void appendToInputtedSentences(String string) {
inputtedSentences.add(string);
}
public static void clearInputtedSentences() {
inputtedSentences.clear();
}
}
As stated in the comments, use a PrintWriter to write the values to a file instead:
PrintWriter pw = new PrintWriter(fos);
for (int i = 0; i < SentencesToUse.inputtedSentences.size(); i++) {
pw.write(SentencesToUse.inputtedSentences.get(i)+"\n"); // note the newline here
}
pw.flush(); // make sure everything in the buffer actually gets written.
And then, to read them back again:
try {
Scanner sc = new Scanner(f);
while (sc.hasNext()) {
SentencesToUse.inputtedSentences.ass(sc.nextLine());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
The pw.flush(); is incredibly important. When I was first learning java, I can't tell you how many hours I spent debugging because I didn't flush my streams. Note also the "\n". This ensures that there will be a newline, and that your sentences don't just run together in one giant blob. If each one already has a newline, then that's not necessary. Unlike print vs println, there is no writeln. You must manually specify the newline character.

Computing a text file

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);
}
}

Average of stacked integers from a txt file using BufferedReader class and Integer.parseInt

I'm supposed to somehow get the average of the stacked integers in the text file. I'm new to this and even getting them to print was difficult for me. I have to use something like this number = Integer.parseInt(readLine); there somewhere but I just don't know how. If anyone could give some hint of what to do I would be most thankful.
The text file has just a dozen integers stacked as in one number on one line. Nothing else. Here's my code so far:
import java.io.*;
public class GradesInFile {
public static void main(String[] args) throws IOException {
String fileName = "grades.txt";
String readRow = null;
boolean rowsLeft = true;
BufferedReader reader = null;
FileReader file = null;
file = new FileReader(fileName);
reader = new BufferedReader(file);
System.out.println("Grades: ");
while (rowsLeft) {
readRow = reader.readLine();
if (readRow == null) {
rowsLeft = false;
} else {
System.out.println(readRow);
}
}
System.out.println("Average: ");
reader.close();
}
}
You are almost there just think how to keep track of the values you have so once you get out of the while loop you can return the average. (Hint Hint keep a list of the numbers)
So:
while (rowsLeft) {
readRow = reader.readLine();
if (readRow == null) {
rowsLeft = false;
} else {
//Convert the String into a Number (int or float depending your input)
//Saving it on a list.
System.out.println(readRow);
}
}
//Now iterate over the list adding all your numbers
//Divide by the size of your list
//Voila
System.out.println("Average: ");
reader.close();

Categories