I have to read in two texts files that look something like this....
FileOne: 10 1 2 3 4 5 67 75 47 18
FileTwo: 5 65 74 57 68 28 38
The first number represents the count of how many of these integers I should use to populate my array.
I need to read the first line of the file then use that number to populate the two arrays with however many elements specified.
I have figured out how to read in both text files and concatenate them together, however I can't figure out how to only get the first number from the file and use it to determine how many numbers I should use after that.
import java.io.File;
import java.util.Arrays;
import java.util.Scanner;
public class ReadData {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Please enter the first file name: ");
String input = s.nextLine();
System.out.println("Please enter the second file name: ");
String input2 = s.nextLine();
int[] data = readFiles(input);
int[] data2 = readFiles(input2);
//System.out.println(Arrays.toString(data));
//System.out.println(Arrays.toString(data2));
System.out.println(Arrays.toString(concat(data, data2)));
}
public static int[] readFiles(String file) {
try {
File f = new File(file);
Scanner s = new Scanner(f);
int counter = 0;
while(s.hasNextInt()) {
counter++;
s.nextInt();
}
int[] arr = new int[counter];
Scanner s1 = new Scanner(f);
for(int i = 0; i < arr.length; i++)
arr[i] = s1.nextInt();
return arr;
}
catch(Exception e) {
return null;
}
}
static int[] concat(int[]... arrays) {
int length = 0;
for (int[] array : arrays) {
length += array.length;
}
int[] result = new int[length];
int pos = 0;
for (int[] array : arrays) {
for (int element : array) {
result[pos] = element;
pos++;
}
}
return result;
}
}
For starters, I'd suggest reading the entire line as a single string, then parse it using a parser which will use space as a delimiter. You will get a DS containing all of your numbers in a more elegant solution.
(Java parsing simple solution : http://pages.cs.wisc.edu/~hasti/cs302/examples/Parsing/parseString.html)
Once you have the DS containing the numbers, you can iterate on it at your pleasure, remembering that the first value determines the amount of future iterations on the DS.
Assuming you use java 8, I'd suggest using the stream functionalities in order to do so : http://winterbe.com/posts/2014/07/31/java8-stream-tutorial-examples/
Comment if you require any furthor elaborations and good luck.
Related
I'm working on an assignment which is to read in only integers from a text file (that contains strings and doubles as well) and put them into an array, sort that array, then print each element within it.
I'm getting a NoSuchElementException in my console here's a screenshot NoSuchElementException
I believe the issue comes from fileInput.next(); in my while loop maybe because I've reached the end of the .txt file but I'm not sure how to fix this - any help is much appreciated.
Also here's the .txt file .txt file along w/ my code below:
package Main;
import java.io.*;
import java.util.*;
public class FilterSort {
public static int[] doubleArrayAndCopy(int[] arr) {
//use the length method to get the size of arr
int SIZE = arr.length;
//create a temp array that is double the size of arr
int [] tempArr = new int[2*SIZE];
//store the elements of the arr into temp array using for-loop
for (int i = 0; i < SIZE; i++){
tempArr[i] = arr[i];
}
return tempArr;
// return the temp array
}
public static void main(String[] args){
int[] data = new int[8];
int index = 0;
try {
// create a Scanner and open a file called "data.txt"
//initialize index = 0
Scanner fileInput = new Scanner(new File("src/main/data.txt"));
// while there are lines in the file
// read the line from the file (get tokens)
// check if the token is integer or not.
while (fileInput.hasNextLine()) {
if(fileInput.hasNextInt()){
data[index] = fileInput.nextInt();
index++;
}
else{
fileInput.next();
}
if (index >= data.length){
data = doubleArrayAndCopy(data);
}
}
/* A note : For checking integers : You can use hasNextInt() method of Scanner. If it will be Integer(true), then you can use that token by using nextInt() method of Scanner to read it, if false, then use next() method of Scanner and throw away this token*/
// store the integer token into the answers array
// increment the index
// use the length method of arrays to check if the index is equal or greater
// than the length of array, if it is true, call here doubleArrayAndCopy.
if(index==0){
System.out.println("There is no data in file");
}
else
{
// Sort the array
Arrays.sort(data);
System.out.println("Elements of array sorted in ascending order: ");
// and Print the elements using loop
for (int i = 0; i < data.length; i++)
System.out.println(data[i]);
}
}
catch(FileNotFoundException e){
System.out.println("Error: Data file not found");
}
}
}
I've tried catching the error and throwing it but that doesn't seem to solve the problem, to be honest I'm lost on what else to do.
I'm working on an assignment which is to read in only integers from a
text file (that contains strings and doubles as well) and put them
into an array, sort that array, then print each element within it.
I solved this program in a different way, where I read all the lines in the text file and try to parse each element (separated by space) into integer.
import java.io.*;
import java.util.*;
public class FilterSort {
public static void main(String[] args) {
int[] data = new int[100];
int index = 0;
try {
// create a Scanner and open a file called "data.txt"
//initialize index = 0
Scanner fileInput = new Scanner(new File("data.txt"));
// while there are lines in the file
// read the line from the file (get tokens)
// check if the token is integer or not.
while (fileInput.hasNextLine()) {
String temporary = fileInput.nextLine();
// split the entire line using space delimiter
String[] temporary_array = temporary.split(" ");
for (String s : temporary_array) {
// Use Integer.parseInt to parse an integer
try {
int number = Integer.parseInt(s);
data[index] = number;
index++;
} catch (NumberFormatException e) {
// This is not an integer, do nothing
}
}
}
if (index == 0) {
System.out.println("There is no data in file");
} else {
// Copy the number out from the data array to output array
int[] output = new int[index];
System.arraycopy(data, 0, output, 0, index);
// Sort the output array
Arrays.sort(output);
System.out.println("Elements of array sorted in ascending order: ");
// and Print the elements using loop
for (int i = 0; i < index; i++) {
System.out.println(output[i]);
}
}
} catch (FileNotFoundException e) {
System.out.println("Error: Data file not found");
}
}
}
Output using your text file:
Elements of array sorted in ascending order:
-8
-3
0
1
1
2
2
3
3
4
4
4
9
22
44
90
92
98
99
99
99
100
162
However, this solution has its own limitation (i.e. When the number of integer is greater than 100 or unknown), but can be solved using more sophisticated technique (i.e. ArrayList).
Good luck in your assignment.
I'm working a project that requires me to create 2d arrays from an image data file and then sort said arrays into different formats based on values.
The sorting will come easy enough, but I'm running into an issue determining the size of an array from scanning the file.
The data of the file is formatted like so:
5 5
201 159 87 63 240
231 32 222 76 5
10 5 248 139 47
167 76 138 177 107
188 122 154 165 205
I need to use the first line to set the rows and columns of the array, but I can't figure out how to do so without scanning the rest of the data. Another thing, I need to be able to loop my code so that a file with multiple data sets in the displayed format can be read an placed into arrays.
Here's what I've come up with so far:
public static void main(String[] args) throws IOException {
File file = new File("imagedata.txt");
Scanner sc = new Scanner(file);
int i = 0;
int j = 0;
int[][] array = new int[i][j];
while (sc.hasNextInt()) {
i = sc.nextInt();
j = sc.nextInt();
array = array[i][j];
sc.nextline();
}
}
It's not much, but I've scrapped a lot of other drafts that got me nowhere. Any helpful advice is welcome.
Okay. So the problem here results from a certain index of the 2D array being replaced over and over again by a new value. What I mean by that is: you have a while loop. You have set variables j and i to 0. But every iteration of the while loop, you are changing the same position in the 2D array; therefore, nothing gets changed. To fix this, we can make use of the first 2 numbers which detail the dimensions of the 2D array (in this case 5x5). We can then use those dimensions in a nested for-loop, and loop through the file and store each value into the 2D array.
The code could look something like this:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(new File("imagedata.txt"));
int r = scanner.nextInt();
int c = scanner.nextInt();
int [][] array = new int[r][c];
for(int row=0; row<array.length; row++) {
for(int col=0; col<array[row].length; col++) {
array[row][col] = scanner.nextInt();
}
}
for(int[] row : array) {
for(int num : row) {
System.out.print(num+" ");
}
System.out.println();
}
}
}
Alternatively, if you don't mind using a 2d String array:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(new File("imagedata.txt"));
int r = scanner.nextInt();
int c = scanner.nextInt();
scanner.nextLine();
String [][] array = new String[r][c];
for(int row=0; row<array.length; row++) {
array[row] = scanner.nextLine().split(" ");
}
for(String[] row : array) {
for(String str : row) {
System.out.print(str+" ");
}
System.out.println();
}
}
}
I am trying to read a .txt file into two different arrays one 1d string array and one 2d int array. The code reads the names into the NamesArray just fine. However, the code seems to either only read the first column of numbers in or only outputs the first column. I'm not sure where I'm going wrong with the code. Any help is greatly appreciated!
The data below is how it is formatted in the file.
Jason 10 15 20 25 18 20 26
Samantha 15 18 29 16 26 20 23
Ravi 20 26 18 29 10 12 20
Sheila 17 20 15 26 18 25 12
Ankit 16 8 28 20 11 25 21
Here is the code that I have so far.
import java.io.*;
import java.util.*;
public class Page636Exercise12
{
// static Scanner console = new Scanner(System.in);
public static void main(String[] args) throws FileNotFoundException, IOException
{
int Count = 0;
String[] NamesArray = new String[5];
int [][] MileageArray = new int [5][7];
int Mileage = 0;
String Names = "";
//Open the input file.
Scanner inFile = new Scanner(new FileReader("Ch9_Ex12Data.txt"));
//Reads from file into NamesArray and MileageArray.
while (inFile.hasNext())
{
Names = inFile.next();
NamesArray[Count] = Names;
Mileage = inFile.nextInt();
MileageArray[Count][Count] = Mileage;
Names = inFile.nextLine();
System.out.println(NamesArray[Count] + " " + MileageArray[Count][Count]);
Count++;
inFile.close();
}
}
Here is what I get for the output.
Jason 10
Samantha 15
Ravi 20
Sheila 17
Ankit 16
The problem is that you are only storing one number in the MileageArray at index [count][count]. You will need to populate the array with a loop that loops for the total number of integer tokens expected like so:
for(int j = 0; j < 7; j++){
Mileage = inFile.nextInt();
MileageArray[Count][j] = Mileage;
}
Names = inFile.nextLine();
I'd also suggest that you specify the MileageArray column and row size as constants. i.e.:
final int ROWS = 5;
final int COLS = 7;
This will allow you to update your parsing code in a more configurable way if the input file format changes.
You are reading only the first int number
Mileage = inFile.nextInt();
You need an inner loop to run 7 times to read all integers and add them in 2D array.
The answer is simple, what you do by invoking Mileage = inFile.nextInt() you get the next token of the input line you are currently at and parse it to an int but since the numbers are delimited by something (assumed a whitespace) only the first number is read and parsed.You have multiple options to fix this. You can either:
Solution 1
Sparkplug were quicker than me.
Solution 2
try (BufferedReader br = new BufferedReader(
new FileReader( new File( "Performance_Results_310_13.dat" ) ) ))
{
String line;
while ( (line = br.readLine()) != null )
{
// split everything in a temporary array
String[] temp = line.split( "\\s" );
// the name will always at the first position rest of the line are the numbers
name = temp[ 0 ];
nameArray[ count ] = name;
// or just simply nameArray[count] = temp[0]
// start at 1 since 0 is the name
for ( int i = 1; i < temp.length - 1; i++ )
{
// create a new array which is big enough for all numbers following
mileageArray[count] = new int[temp.length - 1];
mileageArray[ count ][ i - 1 ] = Integer.parseInt( temp[ i ] );
}
count++;
}
}
catch ( IOException e )
{
e.printStackTrace();
}
This solution reads the entire line and then parses it into the desired format. It is a bit more flexible in my opinion but you must assure that the arrays are big enough to store the data. Also note that this solution does only work if every token after a whitespace is parsable to an int except for the first one.
You need to take two variable to travel a two dimensional array and at the same time print it. You can use below code it works as expected.
public static void main(String[] args) throws FileNotFoundException, IOException{
int count = 0;
int j = 0;
String[] NamesArray = new String[5];
int[][] MileageArray = new int[5][7];
int Mileage = 0;
String Names = "";
// Open the input file.
Scanner inFile = new Scanner(new FileReader("Ch9_Ex12Data.txt"));
// Reads from file into NamesArray and MileageArray.
while (inFile.hasNext()) {
Names = inFile.next();
NamesArray[count] = Names;
j = 0;
System.out.print(NamesArray[count]);
while (inFile.hasNextInt())
{
Mileage = inFile.nextInt();
MileageArray[count][j] = Mileage;
System.out.print(" "+MileageArray[i][j]);
j++;
}
Names = inFile.nextLine();
count++;
System.out.println("");
}
inFile.close();
}
So basically i am trying to read a .txt file that contains these following in it:
3 5
2 3 4 5 10
4 5 2 3 7
-3 -1 0 1 5
and store them into 2D array and print it on console, what i got from the console is fine but only missing the first row 3 5, which i do not know what is wrong with my code made it ignored the first line.
what i got as output now:
2 3 4 5 10
4 5 2 3 7
-3 -1 0 1 5
import java.io.*;
import java.util.*;
public class Driver0 {
public static int[][] array;
public static int dimension1, dimension2;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Welcome to Project 0.");
System.out.println("What is the name of the data file? ");
String file = input.nextLine();
readFile(file);
}
public static void readFile(String file) {
try {
Scanner sc = new Scanner(new File(file));
dimension1 = sc.nextInt();
dimension2 = sc.nextInt();
array = new int[dimension1][dimension2];
while (sc.hasNext()) {
for (int row = 0; row < dimension1; row++) {
for (int column = 0; column < dimension2; column++) {
array[row][column] = sc.nextInt();
System.out.printf("%2d ", array[row][column]);
}
System.out.println();
}
}
sc.close();
}
catch (Exception e) {
System.out
.println("Error: file not found or insufficient requirements.");
}
}
}
You're reading those numbers in this part of your code:
dimension1 = sc.nextInt();
dimension2 = sc.nextInt();
So dimension1 gets the value of 3 and dimension2gets the value of 5, but you're not saving them into the array.
Try this code....
import java.io.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;
public class Proj4 {
public static int rows, cols;
public static int[][] cells;
/**
* main reads the file and starts
* the graphical display
*/
public static void main(String[] args) throws IOException {
Scanner s = new Scanner(System.in);
String file = JOptionPane.showInputDialog(null, "Enter the input file name: ");
Scanner inFile = new Scanner(new File(file));
rows = Integer.parseInt(inFile.nextLine());
cols = Integer.parseInt(inFile.nextLine());
cells = new int[rows][cols];
//this is were I need help
for(int i=0; i < rows; i++)
{
String line = inFile.nextLine();
line = line.substring(0);
}
inFile.close();
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
System.out.print(cells[i][j]);
}
System.out.print();
}
You can use Stream API to do it easily
public static Integer[][] readFile(String path) throws IOException {
return Files.lines(Paths.get(path)) // 1
.filter(line -> !line.trim().isEmpty()) // 2
.map(line -> Arrays.stream(line.split("[\\s]+")) // 3
.map(Integer::parseInt) // 4
.toArray(Integer[]::new)) // 5
.toArray(Integer[][]::new); // 6
}
Read the file as Stream of Lines
Ignore empty lines
Split each line by spaces
Parse splitted String values to get Integer values
Create an array of Integer values
Collect it in 2D-Array
The first two values are being saved into dimension1 and dimension2 variables, so when sc.nextInt gets called later, it's already read the first two numbers and moves on to the next line. So those first ints don't make it into the array.
A few things to consider:
You're wanting to use the entire file, so I would read the whole thing in at once with Files.readAllLines(). This function returns a List<String> which will have all the lines to your file. If there are any blank lines, remove them and now you have the number of rows to declare for your 2d array.
Each line is space delimited, so a simple String.split() on each line in your List<String> will give you the number of columns each row should have.
Splitting each line and converting them to integers can be done with a nested for loops which is normal for processing 2d arrays.
For Example:
public static void main(String[] args) throws Exception {
// Read the entire file in
List<String> myFileLines = Files.readAllLines(Paths.get("MyFile.txt"));
// Remove any blank lines
for (int i = myFileLines.size() - 1; i >= 0; i--) {
if (myFileLines.get(i).isEmpty()) {
myFileLines.remove(i);
}
}
// Declare you 2d array with the amount of lines that were read from the file
int[][] intArray = new int[myFileLines.size()][];
// Iterate through each row to determine the number of columns
for (int i = 0; i < myFileLines.size(); i++) {
// Split the line by spaces
String[] splitLine = myFileLines.get(i).split("\\s");
// Declare the number of columns in the row from the split
intArray[i] = new int[splitLine.length];
for (int j = 0; j < splitLine.length; j++) {
// Convert each String element to an integer
intArray[i][j] = Integer.parseInt(splitLine[j]);
}
}
// Print the integer array
for (int[] row : intArray) {
for (int col : row) {
System.out.printf("%5d ", col);
}
System.out.println();
}
}
Results:
3 5
2 3 4 5 10
4 5 2 3 7
-3 -1 0 1 5
I cannot figure out what is wrong with this.
I have to read in a file (the file has numbers) and store the numbers into an array.
Here is the file:
http://dl.dropboxusercontent.com/u/31878359/courses/15/scores1.txt
I understand the first number is a zero and I cannot change the numbers or the order of the numbers in the file.
File
0
10
20
30
40
50
60
70
80
90
Here is my code:
import java.util.*;
import java.io.*;
public class Check {
public static void main(String[] args)
throws FileNotFoundException {
Scanner input = new Scanner(new File("scores1.txt"));
process(input);
}
public static void process(Scanner input) {
int[] numbers = new int [input.nextInt()];
for (int i = 0; i < numbers.length; i++) {
numbers[i] = input.nextInt();
}
Arrays.sort(numbers);
System.out.print("numbers: "+Arrays.toString(numbers));
}
}
This is the output:
numbers: []
I'm assuming it's a problem with declaring the array.
The problem is that, your first value of file is 0. So array size is 0. Change your first value so that, you can get rest of values into array.
The first value in the file is 0.
int[] numbers = new int [input.nextInt()]; // this input.nextInt() gets the first line
You're making an array of size 0
Since there are 10 numbers in the file. initialize with size 10;
int[] numbers = new int [10];
public static void process(Scanner input) {
List<Integer> number = new ArrayList<Integer>();
while(input.hasNext()) {
number.add(input.nextInt());//i hope all ints are there in the file
}
int[] numbers = number.toArray(new int[number.size])
//then do sort and all
}
hope this will help
My suggestion would be use ArrayList
public static void process(Scanner input) {
List list = new ArrayList();
while(input.hasNextInt()){
list.add(input.nextInt());
}
Collections.sort(list);
System.out.print("numbers: " + list);
}