converting a string array to a double array - java

I am trying to convert a list of numbers from a txt file into an array of numbers. There is 26 numbers, and each is on a different line in the text file. My code is
import java.io.*;
public class rocket {
public static void main(String[] args) throws IOException, FileNotFoundException
{
BufferedReader b = new BufferedReader(new InputStreamReader(new FileInputStream("/Users/Jeremy/Documents/workspace/altitude.txt")));
String[] stringArray = new String[25];
double[] doubleArray = new double[stringArray.length];
for(int i=0; i<25; i++)
{
stringArray[i] = b.readLine();
doubleArray[i] = Double.parseDouble(stringArray[i]);
}
for(int i = 0; i<doubleArray.length; i++)
{
System.out.println(doubleArray[i]);
}
}
}
But every time I run it I get a number format exception. And if I try to just print out the strings I get an indexOutOfBounds exception

in question you have mentioned that there is 26 strings so declate
String[] stringArray = new String[26];
And The number format exception is occuring as readline returns with the linbreak. To read line you can do the following
public String[] readLines(String filename) throws IOException {
FileReader fileReader = new FileReader(filename);
BufferedReader bufferedReader = new BufferedReader(fileReader);
List<String> lines = new ArrayList<String>();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
lines.add(line);
}
bufferedReader.close();
return lines.toArray(new String[lines.size()]);
}
So by this logic you can get double by
public static Double[] readLines(String filename) throws IOException {
FileReader fileReader = new FileReader(filename);
BufferedReader bufferedReader = new BufferedReader(fileReader);
List<Double> lines = new ArrayList<Double>();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
lines.add(Double.parseDouble(line));
}
bufferedReader.close();
return lines.toArray(new Double[lines.size()]);
}

Try
BufferedReader b = new BufferedReader(
new InputStreamReader(
new FileInputStream(
"D:/git-repo/general/misc_test/src/java/com/greytip/cougar/module/test/v2/controller/so/dump/data.txt")));
List<String> lines = new ArrayList<String>();
String line = null;
while ((line = b.readLine()) != null) {
lines.add(line);
}
String[] stringArray = lines.toArray(new String[lines.size()]);
double[] doubleArray = new double[stringArray.length];
for (int i = 0; i < stringArray.length; i++) {
doubleArray[i] = Double.parseDouble(stringArray[i]);
}
for (int i = 0; i < doubleArray.length; i++) {
System.out.println(doubleArray[i]);
}

String[] stringArray = new String[26];
try this

import java.io.*;
public class Rocket {
public static void main(String[] args) throws IOException, FileNotFoundException
{
BufferedReader b = new BufferedReader(new InputStreamReader(new FileInputStream("/Users/Jeremy/Documents/workspace/altitude.txt")));
String[] stringArray = new String[25];
double[] doubleArray = new double[stringArray.length];
for(int i=0; i<25; i++)
{
stringArray[i] = b.readLine();
try{
doubleArray[i] = Double.parseDouble(stringArray[i]);
}catch(Exception e)
{
e.printStackTrace();
}
}
for(int i = 0; i<doubleArray.length; i++)
{
System.out.println(doubleArray[i]);
}
}
}
Handle the Exception when parse a string to double please.

Related

incompatible types: String[] cannot be converted to String

I'm being completely beaten up by types in Java.
I have coordinates in a txt file, which ultimately I want to format into an array of these co-ordinates, with each array item being a double.
Each line of my txt file looks like so:
13.716 , 6.576600074768066
Currently, I'm trying to split this line into an array of two Strings, which I will then try and parse into doubles, but I keep getting the error in the title. Where am I going wrong?
Any other better approaches on converting my Arraylist of Strings to a formatted list of double coordinates would be great, like so
[[0,1], [0,2], 0,4]
Code:
public static String[] getFileContents(String path) throws FileNotFoundException, IOException
{
InputStream in = new FileInputStream(new File(path));
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
List<String> data = new ArrayList<String>();
StringBuilder out = new StringBuilder();
String line;
// Skips 1376 characters before accessing data
reader.skip(1378);
while ((line = reader.readLine()) != null) {
data.add(line);
// System.out.println(line);
}
for (int i=0; i < data.size(); i++){
data.set(i, data.get(i).split(","));
}
// String[] dataArr = data.toArray(new String[data.size()]);
// Test that dataArr[0] is correct
// System.out.println(data.size());
// List<String> formattedData = new ArrayList<String>();
// for (int i = 0; i < data.size(); i++){
// formattedData.add(dataArr[i].split(","));
// }
reader.close();
return dataArr;
}
The split(",") method return array of string string[] and you can't set string by array of string.
Crate point class with let lan double variabels and then create array of this point and them fill them with data from reading each line:
class Point{
double lat;
double len;
Point(double lat, double len){
this.lat = lat;
this.len = len;
}
}
And then use this class in your code:
public static String[] getFileContents(String path) throws FileNotFoundException, IOException
{
InputStream in = new FileInputStream(new File(path));
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
List<String> data = new ArrayList<String>();
StringBuilder out = new StringBuilder();
String line;
// Skips 1376 characters before accessing data
reader.skip(1378);
while ((line = reader.readLine()) != null) {
data.add(line);
// System.out.println(line);
}
List<Point> points = new ArrayList<Point>();
for (int i=0; i < data.size(); i++){
double lat = Double.parseDouble(data.get(i).split(",")[0]);
double len = Double.parseDouble(data.get(i).split(",")[1]);
points.add(new Point(lat, len));
//data.set(i, data.get(i).split(","));
}
// String[] dataArr = data.toArray(new String[data.size()]);
// Test that dataArr[0] is correct
// System.out.println(data.size());
// List<String> formattedData = new ArrayList<String>();
// for (int i = 0; i < data.size(); i++){
// formattedData.add(dataArr[i].split(","));
// }
reader.close();
return dataArr;
}
you can update your while loop like this
while ((line = reader.readLine()) != null) {
String[] splits = line.split(",");
for(String s : splits) {
data.add(s);
}
}

Java File Read in As Array

I am really stuck here, I can't seem to read in the arrays properly.
I can't seem to read in these arrays into columns. Looking for a solution to help me finally make an array out of these numbers.
public class TextFileInputAndOutput
{
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader("USStateCapitalsSelected.txt"));
int lineCounter = 1;
String line;
while ((line = reader.readLine()) != null) {
// parse line using any method.
// example 1:
Scanner intScanner = new Scanner(line);
while (intScanner.hasNextLine()) {
String nextInt = intScanner.nextLine();
System.out.println(nextInt + "Herro");
if (intScanner.hasNextDouble() == true) {
Scanner scanner = new Scanner(line);
while (scanner.hasNextDouble()) {
String nextString = scanner.next();
System.out.println(nextString);
}
}
}
}
}
}
You can use com.google.common.io.Files:
Sample.txt:
nameA labA quizeA
nameB labB quizeB
Code:
public static void main(String[] args) throws Exception {
File myFile = new File("Sample.txt");
ArrayList<String> names = new ArrayList<String>();
ArrayList<String> labs = new ArrayList<String>();
ArrayList<String> quizes = new ArrayList<String>();
for (String line : Files.readLines(myFile, Charset.defaultCharset())) {
String[] cols = line.split(" ");
names.add(cols[0]);
labs.add(cols[1]);
quizes.add(cols[2]);
}
System.out.println(names);
System.out.println(labs);
System.out.println(quizes);
}
Tryb this
try{
File file = new File("filename");
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
String line = sc.nextLine();
String[] temp = line.split(" ");
//add values to arraylist
names.add(temp[0]);
labs.add(temp[1]);
quizes.add(temp[2]);
}
}catch (Exception ex) {
ex.printStackTrace();
}

Read txt file and convert to array

I don't understand why this code won't read a .txt file then convert it to an array. I don't have the exact number of rows to begin with (to set the array) so I count the .txt files rows with a while loop.
This program should count the number of rows it imports then create a new array to copy & print the information to the console.
public class Cre{
public void openFile() throws IOException{
BufferedReader in = new BufferedReader(new FileReader("C:\\Users\\file.txt"));
String line = in.readLine();
int i=0;
String linecounterguy = "null";
int count = 0;
while(line!= null) { ///to count number of rows///
linecounterguy = in.readLine();
count += 1;
}
String[] array = new String[count+1];
String line1 = "try";
while(line!= null)
{
line1 = in.readLine();
System.out.println(line1);
}
in.close();
for (int j = 0; j < array.length-1 ; j++) {
linecounterguy = in.readLine();
System.out.println(array[j]);
}
}
}
Main Class
> public class JavaApplication8 {
>
> /**
> * #param args the command line arguments
> */
> public static void main(String[] args) throws IOException {
>
>
> Cre k = new Cre();
> k.openFile();
>
>
> } }
Here is a little method that will get you started with reading a text file into an array of strings. Hope this helps!
public String[] readLines(String filename) throws IOException {
FileReader fileReader = new FileReader(filename);
BufferedReader bufferedReader = new BufferedReader(fileReader);
List<String> lines = new ArrayList<String>();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
lines.add(line);
}
bufferedReader.close();
return lines.toArray(new String[lines.size()]);
}

How do I get the single element from the text file by using ArrayList?

My text file includes:
Mary,123,s100,59.2
Melinda,345,A100,10.1
Hong,234,S200,118.2
Ahmed,678,S100,58.5
Rohan,432,S200,115.5
Peter,654,S100,59.5
My code:
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new FileReader("competitors.txt")) ;
String line;
ArrayList<String> lines = new ArrayList<String>();
while ((line = br.readLine()) != null)
{
lines.add(line);
}
String[] lineobject= {lines.get(0)};
System.out.println(lineobject[0]);
}
}
I don't know why it can not get the single value of first row, can anyone help?Thanks.
lines.get(0) is "Mary,123,s100,59.2", not {"Mary","123","s100","59.2"}
So you should do;
String[] lineobjects = lines.get(0).split(",");
System.out.println(lineobjects);
System.out.println(lineobjects[0]); // prints "Mary"
Your code works fine for me. However, you should make sure to place the file competitors.txt in the right directory.
This is simpler and should also do the job:
public static void main(String[] args) throws IOException {
List<String> lines = Files.readAllLines(Paths.get("competitors.txt"));
System.out.println(lines.get(0));
}
You may replace the line with some another signs instead of using, (I use %in my case),and split using.split("%"),Then store in a vector file..
Vector data;
Vector columns;
String line;
data = new Vector();
columns = new Vector();
try {
FileInputStream fis = new FileInputStream(PRJT_PATH+"\\YOUR\\PROJECT\\"+PATH);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
StringTokenizer st1 = new StringTokenizer(br.readLine(), " ");
while (st1.hasMoreTokens())
columns.addElement(st1.nextToken());
int i=0;
while ((line = br.readLine()) != null) {
StringTokenizer st2 = new StringTokenizer(line, " ");
while (st2.hasMoreTokens()){
data.addElement(st2.nextToken());}
String clr[]=line.split("%");
Vector v=new Vector();
v.add(clr[0]);
v.add(clr[1]);
i++;
}
br.close();
fis.close();
} catch (Exception e) {
e.getMessage();
}

Reading text from file and storing each word from every line into separate variables

I have a .txt file with the following content:
1 1111 47
2 2222 92
3 3333 81
I would like to read line-by-line and store each word into different variables.
For example: When I read the first line "1 1111 47", I would like store the first word "1" into var_1, "1111" into var_2, and "47" into var_3. Then, when it goes to the next line, the values should be stored into the same var_1, var_2 and var_3 variables respectively.
My initial approach is as follows:
import java.io.*;
class ReadFromFile
{
public static void main(String[] args) throws IOException
{
int i;
FileInputStream fin;
try
{
fin = new FileInputStream(args[0]);
}
catch(FileNotFoundException fex)
{
System.out.println("File not found");
return;
}
do
{
i = fin.read();
if(i != -1)
System.out.print((char) i);
} while(i != -1);
fin.close();
}
}
Kindly give me your suggestions. Thank You
public static void main(String[] args) throws IOException {
File file = new File("/path/to/InputFile");
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String line = null;
while( (line = br.readLine())!= null ){
// \\s+ means any number of whitespaces between tokens
String [] tokens = line.split("\\s+");
String var_1 = tokens[0];
String var_2 = tokens[1];
String var_3 = tokens[2];
}
}
try {
BufferedReader fr = new BufferedReader(new InputStreamReader(new FileInputStream(file), "ASCII"));
while(true)
{
String line = fr.readLine();
if(line==null)
break;
String[] words = line.split(" ");//those are your words
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}
Hope this Helps!
Check out BufferedReader for reading lines. You'll have to explode the line afterwards using something like StringTokenizer or String's split.
import java.io.*;
import java.util.Scanner;
class Example {
public static void main(String[] args) throws Exception {
File f = new File("main.txt");
StringBuffer txt = new StringBuffer();
FileOutputStream fos = new FileOutputStream(f);
for (int i = 0; i < args.length; i++) {
txt.append(args[i] + " ");
}
fos.write(txt.toString().getBytes());
fos.close();
FileInputStream fis = new FileInputStream("main.txt");
InputStreamReader input = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(input);
String data;
String result = new String();
StringBuffer txt1 = new StringBuffer();
StringBuffer txt2 = new StringBuffer();
File f1 = new File("even.txt");
FileOutputStream fos1 = new FileOutputStream(f1);
File f2 = new File("odd.txt");
FileOutputStream fos2 = new FileOutputStream(f2);
while ((data = br.readLine()) != null) {
result = result.concat(data);
String[] words = data.split(" ");
for (int j = 0; j < words.length; j++) {
if (j % 2 == 0) {
System.out.println(words[j]);
txt1.append(words[j] + " ");
} else {
System.out.println(words[j]);
txt2.append(words[j] + " ");
}
}
}
fos1.write(txt1.toString().getBytes());
fos1.close();
fos2.write(txt2.toString().getBytes());
fos2.close();
br.close();
}
}

Categories

Resources