Reading ints from a txt file and storing to an array - java

I am trying to read integers from a text file and store them into an array. The text file reads:
4
-9
-5
4
8
25
10
0
-1
4
3
-2
-1
10
8
5
8
Yet when I run my code I get [I#41616dd6 in the console window...
public static void main(String[] args) throws IOException
{
FileReader file = new FileReader("Integers.txt");
int[] integers = new int [100];
int i=0;
try {
Scanner input = new Scanner(file);
while(input.hasNext())
{
integers[i] = input.nextInt();
i++;
}
input.close();
}
catch(Exception e)
{
e.printStackTrace();
}
System.out.println(integers);
}

You're printing out the virtual memory address of the array instead of the actual array items:
You can print out the actual array items, one by one, like this:
// This construct is called a for-each loop
for(int item: integers) {
System.out.println(item);
}
#akuhn points out correctly that Java has a built in helper for this:
System.out.println(Arrays.toString(integers));
Note that you'll need to add:
import java.util.Arrays
in your imports for this to work.

Unfortunately, Java’s designers missed to add a proper string representations for arrays.
Instead use
System.out.println(Arrays.toString(integers));
You need to import java.util.Arrays; to make this work.

instead of this
System.out.println(integers);
try this
System.out.println(integers[0] + " : " + integers[1]);
you need to print actual values in integers[] array not array itself

If using an int array is not a restriction, then i would suggest use List. You can use it like this :
List<Integer> integers = new ArrayList<Integer>();
Scanner input = new Scanner(file);
while(input.hasNext()){
integers.add(scanner.nextInt());
}
System.out.println(integers);
Output : [1,2,-1,23]

Whenever you pass any object to System.out.println(), it prints the toString() for that object. If its not overridden, it prints the memory address of that object.
System.out.println(integers);
is trying to print toString() representation of integer array which is nothing but the JVM address of this array.
To print the actual numbers in the array, you either need to iterate through the array or convert the array to java.util.ArrayList.(which has the toString() method implemented.)

This should help you to read Integer from a file and store it in array
import java.util.Scanner;
import java.io.File;
import java.util.ArrayList;
public class filetoarray {
public static ArrayList<Integer> read(File f)
{
ArrayList<Integer> array=new ArrayList<Integer>();
try
{
Scanner sc=new Scanner(f);
while(sc.hasNextLine())
{
array.add(sc.nextLine());
}
}
catch(Exception e)
{
System.out.printf("ERROR : %s", e);
}
return array;
}
public static void main(String[] args) {
File file1=new File("file1.txt");//your file path here
ArrayList<Integer> array1;
array1=read(file1);
System.out.println(array1);
}
}

Related

Getting null as an output from array

import java.util.*;
public class a{
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(new File ("master file.txt"));
String[] ids = new String[100];
System.out.println(ids);
while(sc.hasNext()) {
int i = 0;
ids[i] = sc.next();
i++;
}
I tried to put the data from a file to an array. Im always getting a null as an output. I cant figure out why. This has been very stressing.
You are printing an array before you filled it with elements.
Your counter i is reseting to 0 in every iteration of your while loop. Although it's not a good idea to use array with fixed number of elements for reading text of unknown length, so use some dynamic array like ArrayList.
Make sure you have provided the correct path to your .txt file.
So your code could look like this:
Scanner sc = new Scanner(new File ("C:/correct/path/to/file/master_file.txt"));
List<String> listOfStrings = new ArrayList<String>();
while(sc.hasNextLine()) {
listOfStrings.add(sc.nextLine());
}
System.out.println(listOfStrings);
The output is null because you never assigned anything the array before you try to print it. I also moved the i outside of the loop so it doesn't get reinitialized each time. Also since the ids is an array you need to use Arrays.toString(ids) to print it or you just get the object id.
public static void main(String[] args) throws FileNotFoundException {
String[] ids = new String[100]; //array to store lines
int i = 0; // line index
try (Scanner sc = new Scanner(new File ("master file.txt"))) { // try resource
while(sc.hasNextLine()) { // check for next line
ids[i] = sc.nextLine(); // store line to array index
i++; // increment index
}
}
System.out.println(Arrays.toString(ids)); //print output.
}

How to reverse an ArrayList from a file?

This is the original question:
Write a program that reads a set of doubles from a file, stores them in an array or ArrayList, and then prints them back out to the console (using System.out.println statements) in REVERSE order.
For example, if the input file input.txt file contains
27.3
45.6
98.3
10.1
The console output will display
10.1
98.3
45.6
27.3
And this is the code I have so far:
package reverse;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class reversed {
public static void main(String[] args) throws FileNotFoundException {
// TODO Auto-generated method stub
Scanner numFile = new Scanner(new File("input.txt"));
ArrayList<Double> list = new ArrayList<Double>();
while (numFile.hasNextLine()) {
String line = numFile.nextLine();
Scanner sc = new Scanner(line);
sc.useDelimiter(" ");
while(sc.hasNextDouble()) {
list.add(sc.nextDouble());
}
sc.close();
}
numFile.close();
System.out.println(list);
}
}
How would I reverse the ArrayList I created? The code I have works, I just have no idea how to reverse it. And where exactly would I put that code? Thanks!
You don't need to reverse the ArrayList, just iterate it in reverse order. Something like,
for (int i = list.size(); i > 0; i--) {
System.out.println(list.get(i - 1));
}
If you must reverse the List before iteration, you might use Collections.reverse(List) like
Collections.reverse(list);

Java - Read in text file, compute employee hours from most to least

This is for my beginning Java class. There are similar questions asking to sort the values that are given in an array; I know how to do that, but here I need to read in a text file, and then sort the values and display them by employee name and the hours that they worked, while also keeping the order from most to least. This is what the text file looks like:
Jim 4 5 6 1 2 3 4
Harry 6 5 1 3 9 2 0
John 2 3 1 6 7 8 4
Lisa 2 1 5 4 1 2 6
And here is all that I know about reading in text files and my current code for this project.
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class EmployeeWorkHours {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
File file = new File("/Users/ODonnell/Desktop/inputData.txt");
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Parsing
Look at the Javadoc for java.util.Scanner, or use autocomplete in your IDE, you'll see a lot more methods than nextLine() etc, the ones of interest
hasNextInt() returns true when next token is a number
nextInt() the next integer
Storage
Now you need to store your numbers, I'd recommend a List as you won't know how many there are upfront which rules out primitive arrays.
Create a list with List hours = new ArrayList();
Add to it with add()
You'll also need to store your employees names, for simplicity I'd recommend using a Map of String to hours list, i.e. Map>.
Create with Map> employeeHours = new HashMap>()
Add to using employeeHours.put(name, hours)
Sorting
java.util.Collections.sort is all you need. This will sort your list by default in ascending order.
Displaying
Most if not all built in list implementations by default implement toString() so you can simply call System.out.println(hours)
You should save the hours worked and the names of your employees in a HashMap.
http://en.wikipedia.org/wiki/Hash_table For an explation of a HashMap.
After storing your values you can sort the HashMap like it is explained in the following link:
Sort a Map<Key, Value> by values (Java)
You should use next() method on scanner instance to read next token instead of whole line. Then you have to try to parse it to integer to recognize if it is a name of employee or its work hour. In the for loop we are sorting data (using Collections utility class) and printing it.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
public class EmployeeWorkHours {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
File file = new File("inputData.txt");
Map<String, List<Integer>> data = new HashMap<String, List<Integer>>();
try {
Scanner scanner = new Scanner(file);
List<Integer> currentEmployee = null;
while (scanner.hasNextLine()) {
String token = scanner.next();
try {
currentEmployee.add(new Integer(token));
} catch (NumberFormatException e) {
currentEmployee = new ArrayList<Integer>();
data.put(token, currentEmployee);
}
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
for (String name : data.keySet()) {
Collections.sort(data.get(name));
Collections.reverse(data.get(name));
System.out.println(name + " " + data.get(name));
}
}
}

Printing content of an Array in Java

This generates the array.
public word (String file)
{...
public int[] getArray()
{
int[] array = {... } ;
return array;
}
}
And I need to reference that array in another class
public static void main()
{
word numarray = new word("doc.txt");
int [] heightarray = numarray.getArray();
System.out.println(heightarray);
}
I'm not getting any errors but I get things like [I#1a6fa30c as a result.
What you are getting in the output is the hashcode of the array. In order to print the contents of the array you can you either of the below options :
Option 1 : Print the elements one by one using a loop a below :
for(int val : heightarray)
{
System.out.print(val + ",");
}
Option 2 : Use Arrays utility class for printing the array
System.out.println(Arrays.toString(heightarray));
You can print it using the Arrays.toString() method:
System.out.println(Arrays.toString(heightarray));

How to add elements from string added from console to a list in java

How I can add elements to a list from a input in java.
Like if i put:
Scanner reader = new Scanner("a,b,c,d,e);
I want to Have it like String[] a = {a,b,c,d,e];
Using any Scanner Methods with whiles , Really i am little bit lost
Sorry for my English( is not my main language)
If you know how many input items you are going to accept, declare an array before you start the input, then put each input into the array until you run out of array space.
The better way to do this is to use ArrayList:
ArrayList<String> inputList = new ArrayList<String>();
Using a Scanner, you can retrieve the next input (if you want an entire line, use reader.nextLine() to get that string. I'd suggest storing that in a local variable temporarily so you can examine it if you need to (you'll need some sort of termination sentinel or use hasNextLine() to see if there is more to read.
If you then need to return as an array, ArrayList has a toArray() method you can call.
To add inputs to list like this
import java.util.ArrayList;
import java.util.Scanner;
public class StackOverflow {
public static void main(String[] args) {
ArrayList<String> inputList = new ArrayList<String>();
Scanner reader = new Scanner(System.in);
String input = reader.nextLine();
inputList.add(input);
while (!input.equals("null")) {
input = reader.nextLine();
inputList.add(input);
}
}
}
This should work, the default token used by Scanner is whitespace characters.
public String[] getStringArray(String input, int arraySize) {
String[] stringArray = new String[arraySize];
Scanner s = new Scanner(input);
for (int i = 0; s.hasNext(); i++) {
stringArray[i] = s.next();
}
s.close();
return stringArray;
}

Categories

Resources