How to store numbers from a file into an array - java

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);
}

Related

How to create a 2d array from values provided in specific lines of a text file

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();
}
}
}

extract integers from file and print it using array in Java

package foundations;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class gnfmd {
public static void main(String[] args) throws IOException
{
int[] array = new int[40];
int i = 0;
File file = new File("hello.txt");
if (file.exists())
{
Scanner hello = new Scanner(file);
System.out.println("file found");
while (hello.hasNext() && i < args.length)
{
array [i] = hello.nextInt();
i++;
}
hello.close();
for (int l : array)
{
System.out.println(array[l]);
}
}
else
{
System.out.println("file not found");
}
}
}
I came across this problem during the java course. the exercise requires to extract all the integers from a .txt file and print them using arrays but it kept printing zeros even when I copy it from the model answer. can anyone please tell me where I have mistaken
You are printing System.out.println(array[l]);. You should be printing System.out.println(l);, because l already holds a different integer from array on each iteration of the for (int l : array) loop. So on the first iteration, l will hold the value of array[0], on the second iteration it will hold array[1], etc. That and the fact that you only initialize the first args.length positions of the array are the reasons why it prints zeros, since the default values for all positions of an array of int are zeros, and you aren't assigning any other value to most, if not all, of those positions.
Example:
public class MyClass {
public static void main(String args[]) {
int[] array = {1,25,46,97};
for (int i : array) {
System.out.println(i);
}
}
}
Output:
1
25
46
97

How to Merge N sort two text files

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.

Java 7: An array as input

Alright, so I'm supposed to work with this as the beginning of my code:
public static int addOdds(int[] input){}
That would return the sum.
I have the add odds part finished with pre loaded arrays.
That was simple enough, but what is flustering my person is how to get this to take an array as input from user.
I know of Scanner from java.utils, but I'm not sure how to get it to run with my code to make it take an array (if it can).
I considered using:
public string void main(String [] args){}
And call Scanner with it, and use Integer.parseint(), but I don't think that could parse an array.
Then call the input the array from scanner to be handed off to the addOdds method.
An example would be {2,3,7,8,4,1} would be what the code must take as input.
Thanks in advance, I'm a bit stumped.
If it helps, here is an example query; inputTwo isn't relevant to the question:
public class Proj2Tester {
public static void main(String[] args){
int[] inputOne = {4,8,9,12,7};
int[] inputTwo = {41,38,19,112,705};
System.out.println("Problem 1 is correct on test input = " + (16 == Problem1.addOdds(inputOne)));
System.out.println("Problem 2 is correct on test input = " + (686== Problem2.getRange(inputTwo)));
}
Following T.J.'s advice I tried the following:
public class Problem1 {
public static void main(String args[]){
System.out.println("Your array is: "+input);
}
}
public static int addOdds(int[] input){
int[] input = new int[args.length]; //Begin T.J.'s segment
int n = 0;
for (String arg : args) {
input[n++] = Integer.parseInt(arg);
int sum =0; //Initializing sum as 0;
for(int i =0; i < inputOne.length; i++){
if(inputOne[i] % 2 !=0){
;
sum = sum + inputOne[i];
break;
}
if(inputOne[i] % 2 == 0){
i++;
break;
}
}
return sum; // placeholder for my answer, not zero should be returned
}
At least two options:
Have the user specify the array entries as individual command line arguments, e.g.:
java YourClass 2 3 7 8 4 1
...and then parse the entries in args into an int array:
int[] input = new int[args.length];
int n = 0;
for (String arg : args) {
input[n++] = Integer.parseInt(arg);
}
Have the user specify the array as a single command-line argument with commas:
java YourClass "2,3,7,8,4,1"
...and then split args[0] on comma and parse the entries in the resulting string array into an int array.
#1 seems simpler to me, as you start out with a string array.
You might want to consider splitting one String on a comma? See here : How to split a string in Java

How Do I Store Integers from File of Mixed Types into an Array? Java

I have a text file (Scanner file) with some integers and strings. I want to go through the file, take the integers and store them to an integer array (array1).
Here is the method I am using:
public void printIntArray(Scanner file){
int x = 0;
while(file.hasNext()){
array1[x] = file.nextInt();
x++;
}
System.out.println("The list size is: " + (x+1));
System.out.print("The list is:");
for(int z=0; z <= x ; z++)
System.out.println(array1[z]);
}
And here is my output:
Enter the name of the file: input.txt
The contents of the file are: 12 dsafa 14 daf 11 10 afa 3.5
The list size is: 1
The list is:0
array1[] is declared here:
import java.io.*;
import java.util.Scanner;
public class Lab2_2Menu {
private static int LENGTH = 100;
private int[] array1;
private String fileName;
public Lab2_2Menu(){
array1 = new int [LENGTH];
}
I would recommend using List<Integer> instead of an []. Just iterate through the file and remove all non number characters with a comma, replace all duplicate commas then split on a comma.
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner = new Scanner(new FileInputStream("input.txt"));
printIntArray(scanner);
}
public static void printIntArray(Scanner file) {
List<Integer> list = new ArrayList<Integer>();
while (file.hasNext()) {
String[] tokens = file.nextLine().replaceAll("\\D", ",").replaceAll(",+", ",").split(",");
for (String token : tokens) {
if(!token.equalsIgnoreCase("")){
list.add(Integer.parseInt(token));
}
}
}
for (Integer num : list) {
System.out.println(num);
}
}

Categories