This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 6 years ago.
I am trying to read into a file, make it into an array and print it.
I'm not sure what I'm doing wrong with this code. I've been trying to get a solution but all the solutions I can find are more advanced than what we should be using...I wrote a previous program using the same method but as a Double array. I can't seem to make it work for a String?
I keep getting [Ljava.lang.String;#3d4eac6 when I run it.
I just want it to print boysNames. boyNames.txt is just a list of 200 names in a text file.
Someone please help me, or let me know if this is possible?
this is my code so far
public static void main(String[] args) throws FileNotFoundException {
String[] boyNames = loadArray("boyNames.txt");
System.out.println(boyNames);
}
public static String[] loadArray(String filename) throws FileNotFoundException{
//create new array
Scanner inputFile = new Scanner(new File (filename));
int count = 0;
//read from input file (open file)
while (inputFile.hasNextLine()) {
inputFile.nextLine();
count++;
}
//close the file
inputFile.close();
String[] array = new String[count];
//reopen the file for input
inputFile = new Scanner(new File (filename));
for (int i = 0; i < count; i++){
array[i] = inputFile.nextLine();
}
//close the file again
inputFile.close();
return array;
}
`
Java arrays don't override Object.toString(), so you get a generic [Ljava.lang.String;#3d4eac6 (or similar) when you try to print it out using System.out.println(). Instead loop over the array and print each value.
for (String boyName : boyNames) {
System.out.println(boyName);
}
Alternatively, you could use Arrays.toString():
System.out.println(Arrays.toString(boyNames));
Another alternative would be to use String.join() (new for Java 8)
System.out.println(String.join("\n", boyNames));
Related
This question already has answers here:
What's the difference between next() and nextLine() methods from Scanner class?
(16 answers)
Closed 1 year ago.
I am trying to split a .txt file into an array so I can access individual elements from it. However I get the following error, Index 1 out of bounds for length 1 at babySort.main(babySort.java:21).
I am unsure where I am going wrong because I used the same code on a test string earlier and it splits into the appropriate amount of elements.
I suspect it has something to do with the while loop, but I can't seem to wrap my mind around it, any help would be appreciated.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
public class babySort {
public static void main(String[] args) throws FileNotFoundException {
File inputFile = new File("src/babynames.txt");
Scanner in = new Scanner(inputFile);
String test = "Why wont this work?";
String[] test2 = test.split("\\s+");
System.out.println(test2[2]);
while (in.hasNext()) {
String input = in.next();
String[] inputSplit = input.split("\\s+");
//System.out.println(Arrays.toString(inputSplit));
System.out.println(inputSplit[1]);
}
}
}
From the documentation:
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.
My understanding is that you want to read the input line-by-line. You can use FileReader instead of Scanner to read the file line-by-line. You can also use BufferedReader like so:
try (BufferedReader br = new BufferedReader(new FileReader(inputFile, StandardCharsets.UTF_8))) {
String input;
while ((input = br.readLine()) != null) {
// process the line
String[] inputSplit = input.split("\\s+");
//System.out.println(Arrays.toString(inputSplit));
System.out.println(inputSplit[1]);
}
}
This question already has answers here:
What is a debugger and how can it help me diagnose problems?
(2 answers)
Closed 4 years ago.
I am reading a string from a file, and parse the string and the different elements into an array for later manipulation.
Every thing works fine, however when printing elements inside the WHILE loop it works, however, when I try to print the array out of the while loop I get an array Null pointer.
Here is the code :
public PointsEX2(){
String temp = new String();
String[] parse =null;
File file = new File("C:/Users/DjKidoo/Desktop/IA/mof.txt");
Scanner sc = null;
for(int t=0;t<pt_tab1.length;t++){
pt_tab1[t]=new PointEX2();
}
try {
sc = new Scanner(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
int j=0;
while ((sc.hasNextLine())&& (j<= pt_tab1.length)) {
temp = sc.next();
parse = temp.split(",",0);
pt_tab1[j]= new
PointEX2(Float.parseFloat(parse[0]),Float.parseFloat(parse[1]),Float.parseFloat(parse[2]),Float.parseFloat(parse[3]),parse[4]);
System.out.println(toString(pt_tab1[j])); // perfectly works
}
for (int i=0;i<pt_tab1.length;i++)
System.out.println(pt_tab1[i].x); // Array Null Pointer
}
You never increment j within your while loop, so it remains 0 and so you continually assign a new PointEX2 into the same array item, pt_tab1[0]. All the others are null.
pt_tab1 shouldn't even be an array but rather an ArrayList<PointEX2>, and then you wouldn't have this problem.
I'm trying to wrap my head around a problem I have in a programming set.
We're supposed to write code that reads from a file and prints it out. I get that, I can do it.
What he wants us to do is have it print out in reverse.
the file reads:
abc
123
987
He wants:
987
123
abc
The code, as it is, is as follows:
{
FileReader n=new FileReader("F:\\Java\\Set 8\\output1.txt");
Scanner in=new Scanner(n);
int l;
while (in.hasNext())
{
l=in.nextInt();
System.out.println(l);
}
in.close();
}
}
Yes, I am using java.io.*; and Scanner.
What would be the simplest way to do this?
EDIT EDIT EDIT
Here's the improved code, where I try to put it into an array.
The data in the array isn't printing out.
public static void main(String[] args) throws IOException
{
int[]Num=new int[20];
Scanner in=new Scanner(new FileReader("F:\\Java\\Set 8\\output1.txt"));
int k;
for (k=0;k<20;k++)
{
Num[k]=in.nextInt();
}
//in.close();
for (k=20;k<20;k--)
{
System.out.print(+Num[k]);
}
//in.close();
}
The most simplest way is to construct a List and add each line to the list while reading from the file. Once done, print the list items in reverse.
Here is my version of code for your problem.
public static void main(String[] args) throws FileNotFoundException {
FileReader n = new FileReader("/Users/sharish/Data/abc.xml");
Scanner in = new Scanner(n);
ArrayList<String> lines = new ArrayList<String>();
while (in.hasNext()) {
lines.add(in.nextLine());
}
in.close();
for (int i = lines.size() - 1; i >= 0; i--) {
System.out.println(lines.get(i));
}
}
Use Stack.
public static void displayReverse() throws FileNotFoundException {
FileReader n=new FileReader("C:\\Users\\User\\Documents\\file.txt");
Scanner in=new Scanner(n);
Stack<String> st = new Stack<String>();
while (in.hasNext()) {
st.push(in.nextLine());
}
in.close();
while(!st.isEmpty()) {
System.out.println(st.pop());
}
}
If you are permitted the use of third party APIs, Apache Commons IO contains a class, ReversedLinesFileReader, that reads files similar to a BufferedReader (except last line first). Here is the API documentation: http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/input/ReversedLinesFileReader.html
Another (less efficient) solution is hinted at in the comments. You can read your entire file into an ArrayList, reverse that list (e.g. by pushing its contents onto a stack and then popping it off), and then iterate through your reversed list to print.
EDIT:
Here is a crude example:
ArrayList<String> lines = new ArrayList<String>();
Scanner in = new Scanner(new FileReader("input.txt"));
while (in.hasNextLine())
{
lines.add(in.nextLine());
}
Use an ArrayList instead of a static array. We don't necessarily know the length of the file in advance so a static array doesn't make sense here. http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
Your example input 123, abc, etc, contains characters as well as ints, so your calls to hasNextInt and nextInt will eventually throw an Exception. To read lines use hasNextLine and nextLine instead. These methods return String and so our ArrayList also needs to store String. http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#hasNextLine()
Once the file is in a list (not a good solution if the file is large - we've read the entire file into memory) we can either reverse the list (if keeping a reversed form around makes sense), or just iterate through it backwards.
for (int i=lines.size()-1; i>=0; i--) // from n-1 downTo 0
{
String line = lines.get(i);
System.out.println( line );
}
public static void main(String[] args) throws Exception{
String fileName = "F:\\Java\\Set 8\\output1.txt";
RandomAccessFile raf = new RandomAccessFile(fileName,"r");
int len = (int) raf.length();
raf.seek(len);
while(len >= 0){
if(len == 0){
raf.seek(0);
System.out.println(raf.readLine());
break;
}
raf.seek(len--);
char ch = (char)raf.read();
if(ch == '\n'){
String str = raf.readLine();
System.out.println(str);
}
}
}
try using org.apache.commons.io.input.ReversedLinesFileReader, it should do what you want.
You could read the lines like you are already doing, but instead of printing them (because that would print them in order and you need it the other way around), add them to some memory structure like a List or a Stack, and then, in a second loop, iterate this structure to print the lines in the needed order.
Using your code and the answers in the comments, here's an example of how you would store the strings into the arraylist and then print them out in reverse (building off of your own code)
{
FileReader n=new FileReader("F:\\Java\\Set 8\\output1.txt");
Scanner in=new Scanner(n);
int l;
ArrayList<String> reversed = new ArrayList<String>(); // creating a new String arraylist
while (in.hasNext())
{
l=in.nextInt();
System.out.println(l);
reversed.add(l); // storing the strings into the reversed arraylist
}
in.close();
// for loop to print out the arraylist in reversed order
for (int i = reversed.size() - 1; i >= 0; i--) {
System.out.println(reversed.get(i));
}
}
}
Using Java 8:
try(PrintWriter out =
new PrintWriter(Files.newBufferedWriter(Paths.get("out.txt")))) {
Files.lines(Paths.get("in.txt"))
.collect(Collectors.toCollection(LinkedList::new))
.descendingIterator()
.forEachRemaining(out::println);
}
I'm just starting to learn Java and I'm trying to complete this exercise.
I've understood how to extract the information from the txt file (I think) using scanner (we're only supposed to change the method body). However I'm not sure of the correct syntax to transfer the information to an array.
I realise it must be very simple, but I can't seem to figure it out. Could someone please point me in the right direction in terms of syntax and elements needed? Thank you in advance!
import java.util.Scanner;
import java.io.FileReader;
import java.io.IOException;
public class Lab02Task2 {
/**
* Loads the game records from a text file.
* A GameRecord array is constructed to store all the game records.
* The size of the GameRecord array should be the same as the number of non-empty records in the text file.
* The GameRecord array contains no null/empty entries.
*
* #param reader The java.io.Reader object that points to the text file to be read.
* #return A GameRecord array containing all the game records read from the text file.
*/
public GameRecord[] loadGameRecord(java.io.Reader reader) {
// write your code after this line
Scanner input = new Scanner(reader);
for (int i=0; input.hasNextLine(); i++) {
String inputRecord = input.nextLine();
input = new Scanner(inputRecord);
// array?
}
return null; // this line should be modified/removed after finishing the implementation of this method.
}
}
In case you already have a String of the file content, you can say:
String[] words = content.split("\\s");
You can parse your String like this:
private ArrayList<String> parse(BufferedReader input) throws CsvException {
ArrayList<String> data = new ArrayList<>();
final String recordDelimiter = "\\r?\\n|\\r";
final String fieldDelimiter = "\\t";
Scanner scanner = new Scanner(input);
scanner.useDelimiter(recordDelimiter);
while( scanner.hasNext() ) {
String line = scanner.next();
data.add(line);
}
return data;
}
The input text will be scanned line by line.
You can use an ArrayList<String>, like this:
Scanner s = new Scanner(new File(//Here the path of your file));
ArrayList<String> list = new ArrayList<String>();
while (s.hasNext())
{
list.add(s.nextLine());
}
And if you want to get the value of some item of the ArrayList you just have to make reference with get function, like this:
list.get(//Here the position of the value in the ArrayList);
So, if you want to get all the values of the ArrayList you can use a loop to do it:
for (int i = 0; i < list.size(); i++)
{
System.out.println(list.get(i));
}
And finally close your Scanner:
s.close();
I expect it will be helpful for you!
Assuming your one row in file contains one game only
for (int i=0; input.hasNextLine(); i++) {
String inputRecord = input.nextLine();
input = new Scanner(inputRecord);
String line=input.nextLine();
arr[i]=line;
}
return arr;
I am trying to read a file with 8 columns of data and store each string of data into an array, but I keep getting cannot find symbol error for employee.length. I put 8 elements for each string within the row. Please help me by explaining what I am doing wrong. Code:
Scanner scan = new Scanner(new FileReader ("payrollData.dat"));
String employee[] = new String[8];
while(scan.hasNext())
{
for(int i = 0; i < employee.length(); i++)
{
employee[i] = scan.next();
}
}
System.out.println(employee);8
Its employee.length and not employee.length(). In case of arrays, length is a final variable, not a method.
And use Arrays.toString(employee) to print employees properly.
System.out.println(employee) will just print the reference address.