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.
}
Related
This question already has answers here:
How do I determine whether an array contains a particular value in Java?
(30 answers)
Closed 7 years ago.
I am looking for a way to compare a string (which in this case will be a line from a text file) to every element in an array and see if there is a match. At a high level overview, I have a string array (about 100 elements) full of strings that are all contained somewhere in the file that need to be deleted. So I am reading a file into a StringBuffer and writing each line, except skipping over all lines that match an element in the array. This is what I have so far:
//Main Class calling the method
public class TestApp {
public static void main(String[] args) {
CompareAndDelete.RemoveDuplicateLines("C:/somelocation", 2Darray);
}
}
public class CompareAndDelete {
static string Line_of_Text;
static StringBuffer localBuff = new StringBuffer();
static FileReader Buffer;
static BufferedReader User_File;
public static void RemoveDuplicateLines(String local, String[][] duplicates) throws IOException
{
//Converting 2D array to one-dimensional array
final String[] finalDups = new String[duplicates.length];
for(int i = 0; i < duplicates.length; i++)
{
finalDups[i] = duplicates[i][0]+" "+duplicates[i][1];
}
int count = 0;
User_File = new BufferedReader(Buffer);
Set<String> Values = new HashSet<String>(Arrays.asList(finalDups));
while((Line_of_Text = User_File.readLine()) != null){
if(!(Values.contains(Line_of_Text))){
localBuff.append(Line_of_Text+"\n");
}else{
count++;
}
}
System.out.println(count);
//Printing StringBuffer to file
BufferedWriter testOutFile = new BufferedWriter(new FileWriter("C:/test.txt"));
testOutFile.write(localBuff.toString());
testOutFile.flush();
testOutFile.close();
}
So I am unsure of the IF statment, I know that it does not work properly, it currently is only removing the first few elements in the new StringBuffer because those lines happen to be towards the end of the file, and it does not recheck every line for a match with each element. I know there has to be a better way to do this... Thanks in advance for any help/suggestions.
**Updated: with code above, it is now throwing the following error on this line:
while((Line_of_Text = User_File.readLine()) != null){
Error:
Exception in thread "main" java.io.IOException: Stream closed
at sun.nio.cs.StreamDecoder.ensureOpen(StreamDecoder.java:51)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:204)
at java.io.InputStreamReader.read(InputStreamReader.java:188)
at java.io.BufferedReader.fill(BufferedReader.java:147)
at java.io.BufferedReader.readLine(BufferedReader.java:310)
at java.io.BufferedReader.readLine(BufferedReader.java:373)
at compare.CompareAndDelete.RemoveDuplicateLines(CompareAndDelete.java:48)
at mainPackage.TestApp.main(TestApp.java:326)
This can be accomplished quite efficiently by adding your String array members to a Set, and then checking whether the set contains() the current line. Example:
Set<String> ignoredStrings = new HashSet<String>(Arrays.asList(arr));
String line;
while ((line = file.readLine()) != null) {
if (!ignoredStrings.contains(line)) {
buffer.append(line);
buffer.append("\n");
}
}
Here is a method:
public boolean isStringInArray(String str, String[] strarr){
for(String s: strarr){
if(str.equals(s)) return true;
}
return false
}
isStringInArray("Hello", new String[]{"Hello", "World"}); // True
isStringInArray("Hello", new String[]{"hello", "World"}); // False
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;
}
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);
}
}
More details of the issue:I need to create an iterator for a Stack of Strings that uses an ArrayList that returns only the words that are different after making the words all lowercase in the file and uses the Scanner for this. I must sort the array in the end. I have to create two separate classes for this problem.
This is what I have so far:
import java.io.*;
import java.util.*;
public class StackClass
{
static StringSet stringStack;
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
stringStack = new StringSet();
System.out.println("Please input the filename: ");
String fileName = console.next();
try {
FileReader file = new FileReader(fileName);
Scanner input = new Scanner(file);
while (input.hasNext())
{
input.useDelimiter("\\W");
//lcString.toLowerCase();
(I commented this out^ until I figure it out)
stringStack.add(input.next());
}
}
catch (FileNotFoundException e) {e.printStackTrace();}
}
}
And here is my other class:
import java.util.*;
public class StringSet implements Iterable<String>
{
static Stack<String> stringStack;
private ArrayList<String> stackList = new ArrayList<String>();
//for loop goes through all the words in stack
//if the word is found then ignore it, if not add it to the stack
public String add(String s)
{
for(int i=0;i>0;i++)
{
stringStack.push(s);
}
return s;
}
public int size( int i)
{
return stringStack.size();
}
public Iterator<String> iterator()
{return new WordIterator();}
class WordIterator implements Iterator<String>
{
private int i=0;
public boolean hasNext(){return i>0;}
public String next(){return stackList<String>;}
}
}
If the problem is "how to iterate only through unique words", I would simply use a HashSet for the words, and as you push words onto the stack
1) If the word is in the HashSet, don't push it on.
2) If the word is not in the HashSet, push it on and add it to the HashSet.
If you need to keep track of the number of occurrences, you can use a HashMap instead of a HashSet, where you increase the number of duplicate strings you encounter.
If you need to preserve the ordering & number of occurrences for something, I would keep a separate non-unique Stack where I'd just push everything.
I hope I understood your problem correctly.
i have this code:
public class Test{
arrayList<String> list = new ArrayList<String>();
String[][] temp_list;
public static void main(String[] args)
{
String temp = list.get(0);
temp_list[0] = temp.split(" ");
}
}
i want to transfer the first item in 'list' into temp_list[0].compiling is success but i got error when i run it.this is the error:
Exception in thread "main" java.lang.NullPointerException
at Test.main(Test.java:this line=>temp_list[0] = temp.split(" ");)
anyone can help me?
This is because you haven't allocated any 2D-array for temp_list. (Which array should the result of split be stored in?)
Here's a working version of your snippet.
import java.util.ArrayList;
public class Test {
static ArrayList<String> list = new ArrayList<String>();
static String[][] temp_list;
public static void main(String[] args) {
list.add("hello wold");
// allocate memory for 10 string-arrays.
temp_list = new String[10][]; <-----------
String temp = list.get(0);
temp_list[0] = temp.split(" ");
}
}
This code would will not compile since list is declared as a member variable of the class but main is a static method.
As written, list has nothing added too so the call to list.get(0) will throw an Exception (not null pointer though).
The array temp_list is not allocated (no new) in the code given so trying assign into it will throw a null pointer exception.
You need to initialize temp_list before you use it. You need to specify the size of the array. For example:
int sizeOfArray = 5;
String[][] temp_list = new String[sizeOfArray][];