I have a textfile that has hundreds of doubles, all separated by commas and I am trying to write a method to get each of the doubles into an array list of doubles. Here's my code:
public void ReadFile(String inputfile) throws FileNotFoundException {
File myFile = new File(inputfile);
Scanner sc = new Scanner(myFile);
try {
while (sc.hasNextDouble()) {
int i = 0;
arraylist.add(sc.useDelimiter(","));
i++;
}
} catch (Exception e) {
System.out.println("Error");
}
sc.close();
}
The trouble I am having is with the line arraylist.add(sc.useDelimiter(","))'
I get an error saying "The method add(Double) in the type ArrayList is not applicable for the arguments (Scanner)". I am unsure of what to do to fix this. Any help?
As #Hovercraft said you need to set the delimiter once and move it up to where you initialized the scanner. It should look like this:
public void ReadFile(String inputfile) throws FileNotFoundException {
File myFile = new File(inputfile);
Scanner sc = new Scanner(myFile);
List<double> doublelist = new ArrayList<Double>();
//this is where you set the delimiter
sc.useDelimiter(",")
try {
while (sc.hasNextDouble()) {
doublelist.add(sc.nextDouble());
}
} catch (Exception e) {
System.out.println("Error");
}
sc.close();
}
You have to move the useDelimiter outside of loop. You have to also call nextDouble to iterate the numbers in the file.
public static List<Double> readFile(String inputfile) throws FileNotFoundException{
List<Double> arraylist = new ArrayList<Double>();
File myFile = new File(inputfile);
Scanner sc = new Scanner(myFile);
sc.useDelimiter(",");
try {
while (sc.hasNextDouble()) {
Double number = sc.nextDouble();
arraylist.add(number);
}
}catch (Exception e) {
System.out.println("Error");
}
sc.close();
return arraylist;
}
Also please follow proper naming convention in Java. A method name should start with a lower case letter.
Related
public static void main(String[] args) throws IOException{
try {
List<String> line = Files.readAllLines(Paths.get("/home/madhu/Desktop/demo.txt"));
Scanner scanner = new Scanner((Readable) line);
List<FogDevice> fogdevices =new ArrayList<FogDevice>();
while(scanner.hasNextLine()){
String data[]=scanner.nextLine().split(" ");
System.out.println(data);
fogdevices.add(createFogDevice(data[0],Boolean.parseBoolean(data[1]),Long.parseLong(data[2]),Integer.parseInt(data[3]),Double.parseDouble(data[4]),Double.parseDouble(data[5]),Double.parseDouble(data[6])));
}
scanner.close();
System.out.println(fogdevices);
}catch (NumberFormatException e) {
System.out.println(e);
}
}
private static FogDevice createFogDevice(String name2, boolean x2,long mips2,int ram2, double ratepermips2,
double busypower2, double idlepower2) {
--------
---------some activity-----
return fogdevice ;
}
Format of demo.txt :
FD1,true,102400,4000,0.01,103,83.25
FD0,false,102400,4000,0.01,103,83.25
i want output in the below form by using createfogdevice function.
fogdevice1 : FD1,true,102400,4000,0.01,103,83.25
fogdevice2 : FD0,false,102400,4000,0.01,103,83.25
The problem is that you're confusing and mixing two different approaches to reading a file line-by-line. You started off using the nio method readAllLines, and then tried to switch gears to a Scanner and nextLine().
Either approach will work, you just have to pick one and stick with it.
So, if you like like readAllLines:
try {
List<String> line = Files.readAllLines(Paths.get("/home/madhu/Desktop/demo.txt"));
List<FogDevices> fogdevices = new ArrayList<>();
for (String l : line) {
String data[] = l.split("\\s*,\\s*");
System.out.println(data);
fogdevices.add(
createFogDevice(
data[0],
Boolean.parseBoolean(data[1]),
Long.parseLong(data[2]),
Integer.parseInt(data[3]),
Double.parseDouble(data[4]),
Double.parseDouble(data[5]),
Double.parseDouble(data[6])
));
}
System.out.println(fogdevices);
} catch (NumberFormatException e) {
System.out.println(e);
}
Or if you prefer to go with Scanner:
try {
Scanner scanner = new Scanner(Paths.get("/home/madhu/Desktop/demo.txt"));
List<FogDevices> fogdevices = new ArrayList<FogDevices>();
while (scanner.hasNextLine()) {
String data[] = scanner.nextLine().split("\\s*,\\s*");
System.out.println(data);
fogdevices.add(
createFogDevice(
data[0],
Boolean.parseBoolean(data[1]),
Long.parseLong(data[2]),
Integer.parseInt(data[3]),
Double.parseDouble(data[4]),
Double.parseDouble(data[5]),
Double.parseDouble(data[6])
));
}
scanner.close();
System.out.println(fogdevices);
} catch (NumberFormatException e) {
System.out.println(e);
}
Basically, I had to create a scanner for a given file and read through the file (the name is input through the terminal by the user) once counting the number of lines in the file. Then after, I had to create an array of objects from the file, of the correct size (where the num of lines comes in). Then I had to create another scanner for the file and read through it again, storing it in the array I created. And lastly, had to return the array in the method.
My problem is I cannot seem to get the second scanner to actually store the file objects in the array.
I've tried using .nextLine inside a for loop that also calls the array, but it doesn't seem to be working.
public static Data[] getData(String filename) {
Scanner input = new Scanner(new File(filename));
int count = 0;
while (input.hasNextLine()) {
input.nextLine();
count++;
}
System.out.println(count);
Data[] data = new Data[count];
Scanner input1 = new Scanner(new File(filename));
while (input1.hasNextLine()) {
for (int i = 0; i < count; i++) {
System.out.println(data[i].nextLine);
}
}
return data;
}
I expect the output to successfully read the input file so that it can be accessed by other methods that I have created (not shown).
You should definitely use an IDE if you don't have one, try intellij... There you have autocompletion and syntax checking and much more.
It is not clear what you want to do in your for loop, because there are several mistakes, for example the readline() function works only with the scanner objekt, so you can do input.nextline() or input1.nextline()`...
so I just show you, how you can get the Data from a file with Scanner:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class Readfile {
public static void getData(String filename) throws FileNotFoundException {
ArrayList<String> test = new ArrayList<>(); //arraylist to store the data
Scanner inputSc = new Scanner(new File(filename)); //scanner of the file
while (inputSc.hasNextLine()) {
String str = inputSc.nextLine();
System.out.println(str); //print the line which was read from the file
test.add(str); //adds the line to the arraylist
//for you it would be something like data[i] = str; and i is a counter
}
inputSc.close();
}
public static void main(String[] args) {
try {
getData("/home/user/documents/bla.txt"); //path to file
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
You don't need to read thru the file twice - just use an ArrayList to hold the data that's coming in from the file, like this, and then return Data[] at the end:
public static Data[] getData(String filename) {
List<Data> result = new ArrayList<>();
try (Scanner input = new Scanner(new File(filename))){
while (input.hasNextLine()) {
Data data = new Data(input.nextLine());
result.add(data);
}
}
return result.toArray(new Data[0]);
}
Not clear what Data.class do you mean, if you switch it to String, the problem obviously would be in this line
System.out.println(data[i].nextLine);
if you want to assign and print simultaneously write this
for (int i = 0; i < count; i++) {
data[i] = input1.next();
System.out.println(data[i]);
}
and dont forget to close your Scanners, better use try-with-resources.
If your Data is your custom class you'd better learn about Serialization-Deserialization
Or use some ObjectMapper-s(Jackson, for example) to store your class instances and restore them.
Your way of opening the file just to count the lines and then again looping through its lines to store them in the array is not that efficient, but it could be just a school assignment.
Try this:
public static Data[] getData(String filename) {
Scanner input = null;
try {
input = new Scanner(new File(filename));
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
int count = 0;
while (input.hasNextLine()) {
input.nextLine();
count++;
}
input.close();
System.out.println(count);
Data[] data = new Data[count];
try {
input = new Scanner(new File(filename));
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
for (int i = 0; i < count; i++) {
Data d = new Data(input.nextLine(), 0, 0);
data[i] = d;
System.out.println(data[i].name);
}
input.close();
return data;
}
After the 1st loop you must close the Scanner and reopen it so to start all over from the first line of the file.
I am trying to read from a text file, but whenever the program gets to my while loop it just skips over it. I used a previous example I had to check to see if I did it correctly, but it doesn't seem to be working this time.
EDIT: to clarify, the while with "b++" under it is being skipped.
EDIT 2: Updated code.
public static void main(String[] args) throws FileNotFoundException {
ToDoItem td = new ToDoItem();
ToDoList tl = new ToDoList();
File file = new File("ToDoItems.txt");
Scanner ReadFile = new Scanner(file);
Scanner keyboard = new Scanner(System.in);
ArrayList<String> list = new ArrayList<>();
String inputline;
System.out.println("Welcome to the list maker!" + "\n" + "Please start typing.");
try (PrintWriter fout = new PrintWriter(new File("ToDoItems.txt"))) {
do {
System.out.println("add to the list? [y/n]");
inputline = keyboard.nextLine();
if ("y".equals(inputline)) {
fout.print(td.getDescription() + "\n");
} else {
System.out.println("Here is the list so far:");
while (ReadFile.hasNext()) {
String listString = ReadFile.nextLine();
list.add(listString);
}
}
} while ("y".equals(inputline));
} catch (FileNotFoundException e) {
System.err.println(e.getMessage());
}
System.out.println(list);
}
Ideally I want it to print a part of the Array each time it passes through the while loop. But it just ends up skipping over it.
I checked the text file itself, and it does have the information I want to print to it. Yet for some reason the scanner won't read it properly.
I guess your problem is that you are trying to read a file that you are currently using, try close the fout object before read it, something like this:
public static void main(String[] args){
File file = new File("ToDoItems.txt");
ToDoItem td = new ToDoItem();
ToDoList tl = new ToDoList();
Scanner keyboard = new Scanner(System.in);
ArrayList<String> list = new ArrayList<>();
String inputline;
System.out.println("Welcome to the list maker!" + "\n" + "Please start typing.");
try (PrintWriter fout = new PrintWriter(file)) {
// ^^ here
do {
System.out.println("add to the list? [y/n]");
inputline = keyboard.nextLine();
if ("y".equals(inputline)) {
fout.print(td.getDescription() + System.lineSeparator());
} else {
// Important line is here!
fout.close(); // <--- Close printwriter before read file
System.out.println("Here is the list so far:");
Scanner ReadFile = new Scanner(file);
while (ReadFile.hasNext()) {
String listString = ReadFile.nextLine();
list.add(listString);
}
}
} while ("y".equals(inputline));
} catch (FileNotFoundException e) {
System.err.println(e.getMessage());
}
System.out.println(list);
}
String[] stringArray = new String[b]; is problematic as your int b = 0;.
Also, it seems like you do not know how large your array will even be. I would suggest you use an ArrayList instead. That way you will not need a counter, just add to the ArrayList.
It would be better to try and catch your FileNotFoundException instead of throwing at the main but I guess you know that your file will always be there.
Its easy when have a file of all doubles, but when
there is a non-double somewhere in between,
i wouldnt be able to catch all of them.
For example:
604.2
609.2
6042
604.4
4234.324
312
gfsdgfreg
6043
604.3
The output:
604.2
609.2
6042.0
604.4
4234.324
312.0
Apparently, two doubles are missing. Is there a way
to catch all of them just by using hasNextDouble()?
Thx in advance if u dont get a reply. I saw somewhere
that I could parse each of them to double and catch the
exception, but i am really not that advanced
what i have here is:
import java.util.*;
import java.io.*;
public class Lab11{
public static void main(String[] args)
throws FileNotFoundException{
File nums = new File("file.txt");
int size = arrSize(nums);
double[] phoneNums = copy(nums,size);
for(int i=0;i<phoneNums.length;i++)
System.out.println(phoneNums[i]);
}
public static int arrSize(File f)
throws FileNotFoundException{
int arrSize = 0;
Scanner in = new Scanner(f);
while(in.hasNextDouble()){
arrSize++;
in.next();
}
in.close();
return arrSize;
}
public static double[] copy(File f,int size)
throws FileNotFoundException{
Scanner in = new Scanner(f);
double[] list = new double[size];
int i = 0;
while(in.hasNextDouble()){
list[i++] = in.nextDouble();
}
in.close();
return list;
}
}
I would give your two while loops the following structure:
while(in.hasNext()) {
if(in.hasNextDouble()) {
// your inner while loop code here
} else {
in.next();
}
}
Otherwise, you'll miss everything after the first instance of a non-double.
Since you are using
while(in.hasNextDouble()){
arrSize++;
in.next();
}
As soon as it reaches a non-double, it will stop, and won't proceed further.
You have to keep looping through every line in the while loop, and within this loop, use an if statement to check whether what you're reading is a double or not.
Like Takendarkk said, once a non-double is found in the input in.hasNextDouble() will evaluate to false, ending your loop.
Here is an example of a (hopefully) more simplified way of doing what you are doing:
// create a new list for our doubles
List<Double> doubles = new LinkedList<>();
try {
// open our doubles file reader
BufferedReader reader = Files.newBufferedReader(Paths.get("doubles.txt"), Charset.defaultCharset());
// read our doubles file
String line;
while ((line = reader.readLine()) != null) {
if (line.matches("^[0-9]*(\\.[0-9]+)?$")) {
doubles.add(Double.parseDouble(line));
}
}
// close our doubles file reader
reader.close();
} catch (IOException e) {
e.printStackTrace(); // for the sake of the example
}
// output our doubles
for (Double d : doubles) {
System.out.println("Double: " + d);
}
Hope this helps
How can I load .txt file into string array?
private void FileLoader() {
try {
File file = new File("/some.txt");
Scanner sc = new Scanner(new FileInputStream(file), "Windows-1251");
//Obviously, exception
int i = 0;
while (sc.hasNextLine()) {
morphBuffer[i] = sc.nextLine();
i++;
//Obviously, exception
}
sc.close();
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(null, "File not found: " + e);
return;
}
}
There is an issue with array's length, because I don't know how long my array will be.
Of course i saw this question, but there is not an array of string. I need it, because I have to work with whole text, also with null strings.
How can I load a text file into string array?
Starting with Java 7, you can do it in a single line of code:
List<String> allLines = Files.readAllLines("/some.txt", Charset.forName("Cp1251"));
If you need your data in a string array rather than a List<String>, call toArray(new Strinf[0]) on the result of the readAllLines method:
String[] allLines = Files.readAllLines("/some.txt", Charset.forName("Cp1251")).toArray(new String[0]);
Use List
private void FileLoader() {
try {
File file = new File("/some.txt");
Scanner sc = new Scanner(new FileInputStream(file), "Windows-1251");
List<String> mylist = new ArrayList<String>();
while (sc.hasNextLine()) {
mylist.add(sc.nextLine());
}
sc.close();
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(null, "File not found: " + e);
return;
}
}
You can use Collection ArrayList
while (sc.hasNextLine()) {
list.add(sc.nextLine());
i++;
//Obviously, exception
}
http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html