Storing a text file of numbers into an array in java - java

Hi guys i have a text file in the following path C:/Users/Marc/Downloads/vector25 which contains comma-separated values in the following format
-6.08,70.93,-9.35,-86.09,-28.41,27.94,75.15,91.03,-84.21,97.84,
-51.53,77.95,88.37,26.14,-23.58,-18.4,-4.62,46.52,-19.47,17.54,
85.33,52.53,27.97,10.73,-5.82,
How would i read this text file and store those doubles in an array ?
I'm currently thinking of trying a buffered reader but so far the answer eludes me can anyone point me in the right direction ?
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class subvector {
public static void main(String[] args){
FileReader file = null;
try {
file = new FileReader("C:/Users/Marc/Downloads/vector25");
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
ArrayList<Double> list = new ArrayList<Double>();
int i=0;
try {
Scanner input = new Scanner(file);
while(input.hasNext())
{
list.add(input.nextDouble());
i++;
}
input.close();
}
catch(Exception e)
{
e.printStackTrace();
}
for(double k:list){
System.out.println(k);
}
}

You should use a delimeter
Scanner input = new Scanner(file);
input.useDelimeter(",");

Scanner.nextDouble() uses whitespace as the delimiter by default. Your input has commas as delimiter. You should use input.useDelimiter(",") to set commas as the delimiter before calling input.hasNext(). Then it should work as expected.

I think your code snippet will not for the specified data i.e. -6.08,70.93,-9.35,-86.09,-28.41,27.94,75.15,91.03,-84.21,97.84, -51.53,77.95,88.37,26.14,-23.58,-18.4,-4.62,46.52,-19.47,17.54, 85.33,52.53,27.97,10.73,-5.82,
But your program will work fine these type of data :
19.60
63.0
635.00
896.63
47.25
I have modified your program and tested with your data also. It's working as expected.
public static void main(String[] args) {
FileReader file = null;
try {
file = new FileReader("D:\\log4j\\vector25.txt");
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
ArrayList<Double> list = new ArrayList<Double>();
int i=0;
Double d= null;
try {
BufferedReader input = new BufferedReader(file);
String s=null;
while((s=input.readLine())!=null) {
StringTokenizer st = new StringTokenizer(s,",");
while(st.hasMoreTokens()) {
try {
d = Double.parseDouble(st.nextToken());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
list.add(i, d);
}
}
input.close();
} catch(Exception e) {
e.printStackTrace();
}
for(double k:list) {
System.out.println(k);
}
}
Please review it and let me know if you update anything.
This is my first POST on stackoverflow.
Thanks, Prasad

Related

Problem converting .dat file to .csv file

I'm trying to convert .dat file to csv file but I have a problem with it. Below is my code:
public class Main {
public static void main(String[] args) {
DatToCsv dataToCsv = new DatToCsvImpl(); //creating object of DataToCsvImpl class
try {
// Three parameter should be giving to convertDatToCsv function namely input file location and output file
// location and fixed column size respectively
dataToCsv.convertDatToCsv("testing.dat", "testing.csv", 5);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Code 2:
public interface DatToCsv {
public void convertDatToCsv(String datFileLocation,String outputFile, int column)throws IOException;
}
Code 3:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class DatToCsvImpl implements DatToCsv {
#Override
public void convertDatToCsv(String datFileLocation, String outputFile, int column) throws IOException {
// creating instance of file writer, buffer reader and writer
String st;
FileWriter writer;
BufferedWriter bw;
BufferedReader br;
String csvData = "";
int count = 0;
try {
File file = new File(datFileLocation); // .dat file location
writer = new FileWriter(outputFile); // .csv file location
bw = new BufferedWriter(writer); // giving writer to buffer writer constructor to initilize
br = new BufferedReader(new FileReader(file)); // giving input file (.dat) file to buffer reader
StringBuilder sb = new StringBuilder();
/*
* Using while loop (as long as) upto end of file getting data by line by line
*/
while ((st = br.readLine()) != null) {
/*
* replacing multiple space into single space and comma separated of single
* space
*/
st = st.trim().replaceAll(" +", ",");
// if first line of file consider to be heading
if (count == 0) {
csvData = st;
} else {
csvData = csvData + "," + st;
}
count++;
}
// converting all comma seperated value to string array
String csvArray[] = csvData.split(",");
int runningCount = 1;
for (String str : csvArray) {
if (runningCount == column) { // compare fixed column size to running count every fixed column size new
// line added \n
sb.append(str + "\n");
runningCount = 1;
} else {
sb.append(str + ","); // otherwise comma added at the end of every key
runningCount++;
}
}
bw.write(sb.toString());
/*
* flush is because if data 1024bytes not it not store to csv file so we need to
* explicitly mention push data to csv
*/
bw.flush();
writer.close();
br.close();
bw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
For whatever reason it doesnt work and it doesnt accept my input and the output is nowhere to be found. I have tried googling for help to find the input and output but I still couldnt do it. Any help is appreciated thanks

hasNextLine() always returns false

I'm trying to make a spell checker and going to open the words in .txt file in a linked list but hasNextLine() always returns false.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Serializable;
import java.util.LinkedList;
import java.util.Scanner;
public class backEnd {
String string;
String[] splitted;
public backEnd(String s){
string=s;
}
public void splitter(){
splitted =string.split(" ");
for (int x=0; x<splitted.length; x++){
System.out.println(splitted[x]);
}
}
public void spellChecker(){
Serializable data = new String[100];
LinkedList<String> l=new LinkedList<String>();
File f= new File("WordDict.txt");
if(!f.exists())
try {
f.createNewFile();
}
catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
FileInputStream Fis=new FileInputStream(f);
Scanner sc = new Scanner(Fis);
System.out.println("Check outside nextline");
this is the point where it should take words line by line from .txt file but it always breaks the loop.
while (sc.hasNextLine()){
System.out.println("Check in nextline");
data = sc.nextLine();
l.add( (String) data);
}
sc.close();
}
catch(FileNotFoundException fnf){
fnf.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
System.out.println("\nProgram terminated Safely...");
}
int x=0;
int y=0;
while(x<splitted.length){
while(y<l.size()){
if(l.get(y)==splitted[x]){
System.out.println("Matched.");
y++;
}`enter code here`
}
System.out.println("Wrong spelling of: "+splitted[x]);
x++;
}
}
}
The obvious reason seems to be that the file WordDict.txt doesn't exist,
so your code creates it, but it's empty, so it has no next line.
In this code, put a breakpoint on f.createNewFile():
File f= new File("WordDict.txt");
if(!f.exists())
try {
f.createNewFile();
}
catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
FileInputStream Fis=new FileInputStream(f);
Scanner sc = new Scanner(Fis);
System.out.println("Check outside nextline");
Another obvious reason can be that the file exists but it's empty.
Most probably your problem is the first one, and your confusion comes from your assumption of the execution directory. That is, the program is probably not executed where you think. To verify what, change WordDict.txt to absolute path.
sc.hasNextLine() returns true just because is a Empty file!!! Try to write something on it.
In addition your while loop is infinite and a not correct compair (string == string is wrong):
int x=0;
int y=0;
while(x<splitted.length){
while(y<l.size()){
if(l.get(y)==splitted[x]){
System.out.println("Matched.");
y++;
}`enter code here`
}
System.out.println("Wrong spelling of: "+splitted[x]);
x++;
}
This loop maybe should be something like this:
int x=0;
int y=0;
while(x<splitted.length){
while(y<l.size()){
if(l.get(y).equals(splitted[x])){
System.out.println("l.get("+ y +") is "+ l.get(y) +", splitted["+x+"] is "+ splitted[x]);
System.out.println("Matched.");
y++;
x++;
}else{
System.out.println("Wrong spelling of: "+splitted[x]);
y++;
}
}
}

How to read a line from a txt file with int and String elements?

I'm trying to create a List by reading a txt file. For example:
12345; Mary Jane ; 20
12365; Annabelle Gibson; NA
Each line contains: number; name; Grade (grade can be a String or a int)
I created the following method;
public static List <Pauta>leFicheiro( String nomeF) throws FileNotFoundException{
List<Pauta> pautaT = new LinkedList<Pauta>();
try {
Scanner s = new Scanner(new File (nomeF));
try{
List<Pauta> pautaS =pautaT;
while ( s.hasNextLine()){
String line = s.nextLine();
String tokens[]= line.split(";");
if(s.hasNextInt()) {
System.out.println ("next int = " + s.nextInt());
}
pautaS.add(new Pauta (s.nextInt(), tokens[1],tokens[2]);
}
pautaT = pautaS;
}
finally {
s.close();
}
}
catch (FileNotFoundException e){
e.printStackTrace();
}
catch (ParseException e){
e.printStackTrace();
}
return pautaT;
}
Pauta is a class that receives as arguments ( int, String, String), I thought Grade as a String to make it more simple, but if you have ideas on how to still create a List (main goal) by having it String or int I would be thankful.
Now the problem is: The part s.nextInt() is returning error : InputMismatchException
So I put this following code:
catch (InputMismatchException e) {
System.out.print(e.getMessage());}
which says it returns a null.
How can I solve this?
Instead of using the s.nextInt(), parse the first token to an Integer.
See the example below.
public static void main(String... args) throws FileNotFoundException {
List<Pauta> pautaT = new LinkedList<Pauta>();
try {
Scanner s = new Scanner(new File("test.txt"));
try{
List<Pauta> pautaS =pautaT;
while ( s.hasNextLine()){
String line = s.nextLine();
String tokens[]= line.split(";");
pautaS.add(new Pauta (Integer.parseInt(tokens[0]), tokens[1],tokens[2]));
}
pautaT = pautaS;
}
finally {
s.close();
}
}
catch (FileNotFoundException e){
e.printStackTrace();
}
}
This results in the list to be populated.
Yo may use StringTokenizer and save each token of the same line into a variable and then use them as you want.

PrintWriter issue with even numbers

I'm having an issue here: I had this program printing all even numbers 0 through 1000 but after a friend made some changes it only prints "0" now. I've worked with it for a while and can't figure out if it's a loop issue or a printwriter issue. I took the loop out of the printWriter method and still nothing. What exactly am I doing wrong?
import java.io.FileNotFoundException;
import java.io.File;
import java.io.PrintWriter;
public class NumberWriter {
public static void main(String[] args) {
String fileName = "numbers.txt";
try {
PrintWriter outputStream = new PrintWriter(fileName);
for(int i = 0; i <= 1000; i++){
if (i%2==0){
outputStream.println(i + "");
outputStream.close();
}
}
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Don't close your PrintWriter (outputStream) or you won't get any more output. And your code can be optimized to increment by 2 and bypass the even test (this works because every even number is a multiple of two). And Java now has The try-with-resources Statement so you don't have to remember to close your PrintWriter,
try (PrintWriter outputStream = new PrintWriter(fileName)) {
for(int i = 0; i <= 1000; i += 2){
outputStream.println(Integer.toString(i));
}
} catch (FileNotFoundException e) {
e.printStackTrace():
}

Reading a text file in Java and printing backwards with recursion

Write a Java program that recursively reads ten names from a file, and then outputs the total number of characters in the names, the list of names, and the list of names in reverse order. All looping must be performed recursively.
Jay Walker
Erol Flintstone
C. Erol Madre
Billy Pilgrim
Mickey Angels
José Francisco de San Martín
Squarebob Sponge Pants
Mischa Ternoff
Chester Peak
Al Italia
Ben Dover
Pat Pending
I am 100% lost. I would like advice on where would be the first place to start. Thinking about the program, I wanted to build a main that would call a scanner that would read the file first. When reading the file, it would count the characters in the text (quick question, would a scanner count the spaces between the characters?).
Next I was thinking of just a simple print function that would display the entire names.txt file.
Finally, the part the I'm 110% lost...how the heck would I go about listing the names in reverse order? What would I use? How does recursion fit in all this?
Something like this:
Reader(Stream strm)
{
string line;
if(!strm.eof())
{
line = strm.ReadLine();
Reader(strm);
}
// Info - char counte etc
string parseResult = Parse(line);
Print(parseResult);
}
Recursion will stop at the end of file and will start to unroll. The last message will be printed first.
Pseudocode for the recursion part:
function printLines(lines):
if lines not empty:
print first line from lines // this prints lines in order
call printLines(remaining lines)
print first line again // this prints lines in reverse order
Example output for lines ["line1", "line2", "line3"]
line1 // 1st output for printLines(["line1", "line2", "line3"])
line2 // 1st output for printLines(["line2", "line3"])
line3 // 1st output for printLines(["line3"])
// no output for printLines([])
line3 // 2nd output for printLines(["line3"])
line2 // 2nd output for printLines(["line2", "line3"])
line1 // 2nd output for printines(["line1", "line2", "line3"])
You can read file with scanner.nextLine(). It would read an entire line includiing spaces.
For how to print a string backwards using recursion, imagine that as a way containing houses on sides. You want to visit houses backwards (although you entered the way forwards). So you decided to go ahead until the way's end, and then back step by step and print neighbour house names.
function print( i )
if i == wayEnd
return
print(i + 1) // go ahead
// after you return, print:
output house at i
ADD
The code of method should be then:
private static Scanner scanner;
private static void readFile() {
if (!scanner.hasNext()) return;
String line = scanner.nextLine();
readFile();
System.out.println(line);
}
Just you have to call readFile() from main:
public static void main(String[] args) {
scanner = new Scanner(new File("myText.txt"));
readFile();
}
Am not good at scanning but using Desolator's scanner you can do the rest of the part as follows,
private Scanner scanner;
static Map<String, Integer> counts = new HashMap<String, Integer>();
public static void main(String[] args) {
scanner = new Scanner(new File("myText.txt"));
readFile();
System.out.println(counts);
}
private void readFile() {
if (!scanner.hasNext()) return;
String line = scanner.nextLine();
String[] names = line.split("([\\W\\s]+)");
for(int i=0;i<names.length;i++) {
populateMap(names[i]);
}
readFile();
}
static void populateMap(String str) {
counts.put(reverse(str), str.length());
}
static String reverse(String s) {
if(s.length() == 0)
return "";
return s.charAt(s.length() - 1) + reverse(s.substring(0,s.length()-1));
}
To train my Java skills I wrote you the following code:
import java.util.*;
import java.io.*;
public class RecursiveReadNames{
public static final int MAXLINES = 10;
public static void main(String[] args) throws FileNotFoundException {
Scanner scan = new Scanner(new File("listOfNames.txt"));
String[] names = new String[MAXLINES];
readNames(names, scan, 0);
printNames(names,0);
System.out.println();
printNamesReverse(names,0);
System.out.println(totalNumberOfCharsInNames(names, 0,0));
}
static String[] readNames(String[] names, Scanner scan, int curLine) {
if(curLine >= MAXLINES)
return names;
names[curLine] = scan.nextLine();
return readNames(names, scan, curLine+1);
}
static void printNames(String[] names, int cur) {
if(cur >= names.length)
return;
System.out.println(names[cur]);
printNames(names, cur+1);
}
static void printNamesReverse(String[] names, int cur) {
if(cur >= names.length)
return;
printNamesReverse(names, cur+1);
System.out.println(names[cur]);
}
static int totalNumberOfCharsInNames(String[] names, int cur, int sum) {
if(cur >= names.length)
return sum;
return totalNumberOfCharsInNames(names, cur+1, sum+names[cur].length());
}
}
do something like this
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class Test {
public static void printname(String name,BufferedReader br)
{
if(name!=null && br!=null)
{
try {
Test.printname(br.readLine(), br);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(name);
}
}
static Scanner scanner1 = new Scanner(System.in);
public static void main(String[] args)
{
//print the names and total character in each name
try {
FileInputStream fin=new FileInputStream("d:\\file.txt");
BufferedReader br=new BufferedReader(new InputStreamReader(fin));
String n;
while((n=br.readLine())!=null)
{
System.out.println(n+" length:"+n.length());
}
fin.close();
br.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//print names in reverse order
try {
FileInputStream f=new FileInputStream("d:\\file.txt");
BufferedReader br=new BufferedReader(new InputStreamReader(f));
try {
Test.printname(br.readLine(),br);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
f.close();
br.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
notice that I'm passing br object
import java.util.Scanner;
import java.io.*;
class Listnames{
public static void recursiveRead(Scanner scanner) {
String name;
if(scanner.hasNext())
{name=scanner.next();
recursiveRead(scanner);
System.out.println(name.length() +" "+ name);
}
}
public static void main(String[] args)
{
try{
Scanner scanner=new Scanner(new File("name.txt"));
scanner.useDelimiter(System.getProperty("line.separator"));
recursiveRead(scanner);
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}

Categories

Resources