I have a text file with multiple lines of numbers like this:
0.0336 0.0243 0.0261
0.0075 0.1788 0.0669
I need to make a Java program to reformat them to one number per line:
0.0336
0.0243
0.0261
0.0075
0.1788
0.0669
Here is my code and it does not work:
while (scanner.hasNext())
{
String[] arr = scanner.nextLine().split("\\s+");
for(int i =0; i< arr.length; i++){
System.out.println(arr[i]);
}
}
This code results in an extra line whenever there is a new line, for example:
0.0336
0.0243
0.0261
//extra line here, which should be ignored
0.0075
0.1788
0.0669
Is there a way to ignore the line?
I tried the same you did it's working fine on my text file. I did this
BufferedReader source = new BufferedReader(new FileReader("/path/of/file/stack.txt"));
scanner = new Scanner(source);
while (scanner.hasNext()) {
String[] arr = scanner.nextLine().split("\\s+");
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
Related
All the examples that i have seen involve specifying the number of rows and columns at the start of the file but the method I'm working on reads a file with the following:
1.0 2.0
3.0 4.0
and using this data creates a 2d array and stores it without specifying the number of rows and columns.
Here's the code I have written:
public static double[][] readMatrixFrom(String file) throws FileNotFoundException {
Scanner input = new Scanner(new FileReader(file));
int rows =0;
int columns =0;
while(input.hasNextLine()){
String line = input.nextLine();
rows++;
columns = line.length();
}
double[][] d = new double[rows][columns]
return d;
}
I'm unsure of how to add these values now that I have created the 2d array. i tried this but got an InputMismatchException.
Scanner s1 = new Scanner(file);
double[][] d = new double[rows][columns]
for (int i= 0;i<rows;i++) {
for (int j= 0;i<rows;j++) {
d[i][j] = s1.nextDouble();
}
}
if you just want to use the basic arrays you can achieve it with something like
Scanner input = new Scanner(new FileReader(file));
int row=0;
int col =0;
String s="";
//count number of rows
while(input.hasNextLine()) {
row++;
s=input.nextLine();
}
//count number of columns
for(char c: s.toCharArray()) {
if(c==' ')
col++;
}
col++; // since columns is one greater than the number of spaces
//close the file
input.close();
// and open it again to start reading it from the begining
input = new Scanner(new FileReader(file));
//declare a new array
double[][] d = new double[row][col];
int rowNum=0;
while(input.hasNextLine()) {
for(int i=0; i< col; i++) {
d[rowNum][i]= input.nextDouble();
}
rowNum++;
}
However if you prefer to use java collection you can avoid reading the file again. Just store the strings in a list and iterate over the list to extract elements from it.
Based on your input, Your columns = line.length(); is returning 7 rather than 2 as it returns the String length.
Hence try calculating the no of columns in the row columns = line.split(" ").length;
Also while trying to read your input you were using index i for the 2nd for-loop. It should be like below,
for (int i= 0;i<rows;i++) {
for (int j= 0;j<columns;j++) {
d[i][j] = s1.nextDouble();
}
}
In order to work with arrays of unknown size you should read the data into a Collection (such as a List). However, Collection(s) only work with the wrapper-types; so you will need to copy the elements back into an array of double(s) if that is what you really need. Something like,
public static double[][] readMatrixFrom(String file) throws FileNotFoundException {
Scanner input = new Scanner(new FileReader(file));
List<List<Double>> al = new ArrayList<>();
while (input.hasNextLine()) {
String line = input.nextLine();
List<Double> ll = new ArrayList<>();
Scanner sc = new Scanner(line);
while (sc.hasNextDouble()) {
ll.add(sc.nextDouble());
}
al.add(ll);
}
double[][] d = new double[al.size()][];
for (int i = 0; i < al.size(); i++) {
List<Double> list = al.get(i);
d[i] = new double[list.size()];
for (int j = 0; j < d[i].length; j++) {
d[i][j] = list.get(j);
}
}
return d;
}
Which I tested by creating a file in my home folder with your contents and running it like so
public static void main(String[] args) {
String file = System.getProperty("user.home") + File.separator + "temp.txt";
try {
System.out.println(Arrays.deepToString(readMatrixFrom(file)));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
And I get (as I assume you wanted)
[[1.0, 2.0], [3.0, 4.0]]
I have created a method that reads a file set like this (//... are comments, ignore them):
5 // n jobs
2 // n tools
1 4 5 6 2
1 5 4 2 3
The matrix represents the tools used for each job but it doesn't really matter here.
Here is the method :
public static JobS inputJobMatrix(){
String line = ""; // Line in tokenizer
int jobN = inputJobN(); //First number of the file (jobs) works
int toolN = inputToolN(); //Second number of the file (tools) works
//Instancing JobS object
JobS inputJobS = new JobS(jobN, toolN);
int[][] tabFill = new int[jobN][toolN];
int[] tabFillOrder = new int[jobN];
try {
// Initializing reader.
FileReader fr = new FileReader("input.txt");
BufferedReader br = new BufferedReader(fr);
StringTokenizer st = new StringTokenizer(line);
for(int i=0; i<3; i++){ //ReachFirstLine of matrix
line = br.readLine();
//System.out.println(line);
}
//Instancing tab for Job Order 1...n
int[] a = new int[jobN];
for (int i=0; i<jobN; i++){
a[i]=i+1;
}
//Filling Order tab with Job order
JobS.fillLine(tabFillOrder, a, 0); //Fills the tab with the tab a (make a copy of it we could say)
//Reading the matrix line by line and filling tab line
for(int i=0; i<jobN; i++){
for(int j=0; j<toolN; j++){
String str = st.nextToken();
System.out.println(str);
tabFill[i][j] = Integer.parseInt(str);
}
line = br.readLine();
}
inputJobS.setJobS(tabFill);
br.close();
} catch (IOException e) {
System.out.println("File not found exception in inputJobMatrix.");
}
return inputJobS;
}
Which results in :
Exception in thread "main" java.util.NoSuchElementException
at java.util.StringTokenizer.nextToken(Unknown Source)
at pProgra.ReadJobS.inputJobMatrix(ReadJobS.java:84)
at pProgra.PPMain.main(PPMain.java:14)
I've tried looking for problems in my loops but didnt find any, and i can't understand why it doesn't work.
The goal here is to fill a bidimensionnal int array with the matrix of the input file (for exemple the one i've given previously with jobs and tools) and use that array for my object (JobS, i'll give the constructor here too if it can help) :
public class JobS {
private int[] jobOrder;
private int[][] jobS;
public JobS(int jobs, int tools){// Creates one more line for the title (jobOrder).
super();
int[][] tab = new int[jobs][tools];
int[] tab2 = new int[jobs];
this.jobS = tab;
this.jobOrder = tab2;
}
And the setter i use at the end:
public void setJobS(int[][] jobS) {
this.jobS = jobS;
}
I tried detailing the code as much as possible with comments, I hope you will understand what i want to do.
This is the first time i'm trying to do a "complex" application so maybe i'm just stupid and forgot something, but right now i've been searching for an hour and still have no clue what is causing this ..
Hope you can help, thanks in advance !
L.L.
as you can see the String line is empty:
String line = ""; // Line in tokenizer
so here st is empty:
StringTokenizer st = new StringTokenizer(line);
hence when you call this:
String str = st.nextToken();
an exception occurs.
ensure that the line has some data first, by instantiating the StringTokenizer after the for loop.
Example
change this:
StringTokenizer st = new StringTokenizer(line);
for(int i=0; i<3; i++){ //ReachFirstLine of matrix
line = br.readLine();
//System.out.println(line);
}
to this:
for(int i=0; i<3; i++){ //ReachFirstLine of matrix
line = br.readLine();
//System.out.println(line);
}
StringTokenizer st = new StringTokenizer(line);
side note - this code:
line = br.readLine();
will overwrite the value of line at each iteration within the loop, that could be what you wanted but if you want to append all the lines of text the readLine() gets then you can do this:
line += br.readLine();
I need to read a text file, and break the text into blocks of 6 characters (including spaces), pad zeroes to the end of text to meet the requirement.
I tried doing it and here is what I have done.
File file = new File("Sample.txt");
String line;
try {
Scanner sc = new Scanner(file);
while(sc.hasNext()){
line = sc.next();
int chunk = line.length();
int block_size=6;
if((chunk%block_size) != 0)
{
StringBuilder sb = new StringBuilder(line);
int val = chunk%block_size;
for(int i=0; i<val; i++){
sb.append(" ");
}
line = new String(sb.toString());
}
int group = line.length() / block_size;
String[] b = new String[group];
System.out.println(line);
System.out.println(chunk);
int j =0;
for(int i=0; i<group;i++){
b[i] = line.substring(j,j+block_size);
j += block_size;
}
System.out.println("String after spliting is: ");
for(int i=0; i<group;i++){
System.out.println(b[i]);
}
}
}
Now this works fine when the text in the input file has no spaces between words. But when I add spaces gives me a different output. I am stuck up at this point. Any suggestions on the same ?
I don't want to write the solution for you, but I'd advise you that what you're trying to accomplish might be easier to do using a BufferedReader with a FileReader and by using Reader.read(buf) where buf is a char[6];
I want to seperate all words in a text file. There can be lots of words in one line. I tried that code but didnt work.What can i do?
this is text file:
desem ki vakitlerden
bir nisan akşamıdır
rüzgarların en ferahlatıcısı senden esiyor
sen de açıyor çiçeklerin en solmazı
ormanların en kuytusunu sen de gezmekteyim
demişken sana ormanların
senden güzeli yok
vakitlerden geçmekteyim
çiçeklerin tadı yok çiçeklerin
neyi var çiçeklerin
and i want to write all the words one bye one.
String[] words = null;
String line = inputStream.nextLine();
while (inputStream.hasNextLine()) {
line = inputStream.nextLine();
words = line.split(" ");
}
for (int i = 0; i < words.length; i++) {
System.out.println(words[i]);
}
}
inputStream.close();
Use ArrayList:
ArrayList<String> words = new ArrayList<String>();
String line = inputStream.nextLine();
while (inputStream.hasNextLine()) {
line = inputStream.nextLine();
words.addAll(Arrays.asList(line.split(" ")));
}
for (int i = 0; i < words.size(); i++) {
System.out.println(words.get(i´));
}
}
inputStream.close();
Since you already seem to be using Scanner
instead of
while (inputStream.hasNextLine()) {
line = inputStream.nextLine();
words = line.split(" ");
}
for (int i = 0; i < words.length; i++) {
System.out.println(words[i]);
}
}
you can use its next() which will read words instead of lines. This way you will be able to print all words without having to
read entire line,
parse this line to split it into words
store all words
Your code can look like:
Scanner inputStream = new Scanner(new File("location/of/your/file.txt"));
List<String> words = new ArrayList<>();
while (inputStream.hasNext()){
words.add(inputStream.next());
}
inputStream.close();
for (String word : words){
//here you can do whatever you want with each word from list
System.out.println(word);
}
I have to read in a text file called test.txt. the first line of the text file are two integers. these integers tell you the rows and columns of the 2D char array. The rest of the file contains characters. the file looks a bit like: 4 4 FILE WITH SOME INFO except vertically on top of one another not horizontally. I must then read each of the rest of the contents of the file into the 2D char[][] array using nested for loops. I am not supposed to copy from one array to another. This is the code I have so far. I'm having trouble reading each character line by line into my 2D char array. Help been working at this for hours.
public static void main(String[] args)throws IOException
{
File inFile = new File("test.txt");
Scanner scanner = new Scanner(inFile);
String[] size = scanner.nextLine().split("\\s");
char[][] array = new char[Integer.parseInt(size[0])][Integer.parseInt(size[1])];
for(int i=0; i < 4; i++) {
array[i] = scanner.nextLine().toCharArray();
}
for(int k = 0; k < array.length; k++){
for(int s = 0; s < array[k].length; s++){
System.out.print(array[k][s] + " ");
}
System.out.println();
}
scanner.close();
}
}
If I have understood it correctly - file format is something like
4 4
FILE
WITH
SOME
INFO
Modify as below
Scanner scanner = new Scanner(inFile);
String[] size = scanner.nextLine().split("\\s");
char[][] array = new char[Integer.parseInt(size[0])][Integer.parseInt(size[1])];
for(int i=0; i < rows; i++) {
array[i] = scanner.nextLine().toCharArray();
}
Above code is for initialization of you char array. In order to print the same you can do something like
Arrays.deepToString(array);
Copying Tirath´s file format:
4 4
FILE
WITH
SOME
INFO
I would pass it into a 2d array as follows:
public static void main(String[] args){
char[][] receptor = null; //receptor 2d array
char[] lineArray = null; //receptor array for a line
FileReader fr = null;
BufferedReader br = null;
String line = " ";
try{
fr = new FileReader("test.txt");
br = new BufferedReader(fr);
line = br.readLine();//initializes line reading the first line with the index
int i = (int) (line.toCharArray()[0]-48); //we convert line to a char array and get the fist index (i) //48 = '0' at ASCII
int j = (int)(line.toCharArray()[1]-48); // ... get the second index(j)
receptor = new char[i][j]; //we can create our 2d receptor array using both index
for(i=0; i<receptor.length;i++){
line = br.readLine(); //1 line = 1 row
lineArray = line.toCharArray(); //pass line (String) to char array
for(j=0; j<receptor[0].length; j++){ //notice that we loop using the length of i=0
receptor[i][j]=lineArray[j]; //we initialize our 2d array after reading each line
}
}
}catch(IOException e){
System.out.println("I/O error");
}finally{
try {
if(fr !=null){
br.close();
fr.close();
}
} catch (IOException e) {
e.printStackTrace();
}
} //end try-catch-finally
}