Hey guys I'm trying to read in a file which I have done many times before, but It keeps outputting "null" for however many lines of code exist in the .
public static void main(String[] args) {
// TODO code application logic here
Scanner kbd = new Scanner(System.in);
String[] item = new String[25];
Scanner fileInput;
File inFile = new File("dictionary.txt");
try {
fileInput = new Scanner(inFile);
int newItem = 0;
while (fileInput.hasNext())
{
item[newItem++] = fileInput.nextLine();
System.out.println(item[newItem]);
}
}
catch(FileNotFoundException e){System.out.println(e); }
txt file. please help.
You increment newItem and then you print item[newItem]. It always return null because you have not written anything yet in item for the new index.
Try:
while (fileInput.hasNext()) {
item[newItem] = fileInput.nextLine();
System.out.println(item[newItem]);
newItem++;
}
It's because of newItem++, which returns the value and then increments it.
So, you start by setting item[x] = ...; - but then print out item[x+1];
Related
Now I am trying to read txt files and make an array in arraylist with that data.
I want to read two txt files and compare them, but I can't understand why the inside while loop is not working.
(I used 'count' variable to test inside while loop, but when I printed count variable, it printed only 0.)
(Also I know that try~ catch~ is not good solution for
NullPointerException error.. but I couldn't find other solution instead of try~ catch~)
import java.io.*;
import java.util.*;
public class Warehouse {
static private String[] eachStockElem = new String[5];
static private String[] eachInputElem = new String[5];
public static void main(String[] args) throws Exception {
Scanner str = new Scanner(new File("a.txt"));
Scanner ip = new Scanner(new File("b.txt"));
PrintStream st_w = new PrintStream("a.txt");
PrintStream tx = new PrintStream("c.txt");
ArrayList<String[]> stockArrayList = new ArrayList<>();
ArrayList<String[]> inputArrayList = new ArrayList<>();
ArrayList<String[]> txArrayList = new ArrayList<>();
String eachTxElem[] = new String[6];
int tx_id=0;
int temp_quantity=0;
int count=0;
try {
while (ip.hasNextLine()) {
eachInputElem = ip.nextLine().split(",");
inputArrayList.add(eachInputElem);
while (str.hasNextLine()) { //this while not working!
eachStockElem = str.nextLine().split(",");
stockArrayList.add(eachStockElem);
count++;
//do comparing operation
break;
}
}
}
catch(NullPointerException e){
System.out.print("");
}
System.out.println(count);
str.close();
ip.close();
tx.close();
}
}
By guessing what "this loop does not work" words mean, i am taking the risk to post of what i think is the problem in your case.
PrintStream in documents:
The name of the file to use as the destination of this print stream.
If the file exists, then it will be truncated to zero size; otherwise,
a new file will be created. The output will be written to the file and
is buffered.
The problem (and the answer, "why it is not working"):
Scanner str = new Scanner(new File("a.txt"));
PrintStream st_w = new PrintStream("a.txt"); //Cleans the text file,
// so scanner has no lines to read.
At this line,
PrintStream st_w = new PrintStream("a.txt");
the program is writing the output in the same input file. Change the name of this output file and execute your test case.
I'm supposed to be coding an app that can read names from a hardcoded text file, save them as a string array, then write those names in a different text file but sorted. I believe I have the first two parts down but I'm confused on how to sort the names then write them into a new file.
These is the actual problem I'm working on:
"Take an input file with 10 names in it (hard coded). Write a program to read the file, save the names in a String array and write into a different file names in sorted order. Use Methods appropriately."
BTW I'm a rookie coder, this is what I have so far.
public static void main(String[] args) throws FileNotFoundException {
// TODO code application logic here
readFile();
saveStringArray();
}
public static void readFile() {
File file = new File("/Users/nicoladaaboul/Desktop/Programming/C++, "
+ "HTML5, Java, PHP/Java/Question2/names.txt");
try {
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
String i = sc.next();
}
sc.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static void saveStringArray() throws FileNotFoundException {
String token1 = "";
Scanner inFile1 = new Scanner(new File("names.txt")).useDelimiter(",\\s*");
List<String> temps = new ArrayList<String>();
while (inFile1.hasNext()) {
token1 = inFile1.next();
temps.add(token1);
}
inFile1.close();
String[] tempsArray = temps.toArray(new String[0]);
Arrays.sort(tempsArray);
for (String s : tempsArray) {
System.out.println(s);
}
}
public static void sortingNames() {
}
public static void writingFile() throws FileNotFoundException {
PrintWriter writer = new PrintWriter("sortedNames.txt");
writer.close();
}
Its important that you break your problem down into instructions.
1. You need to read the file you can use bufferedReader(code below).
2. Create an array(or arraylist) to store your string values.
3. Then as you read each line, store these values in the array.
4. When finished reading the file you then would pass this array to a function that would sort it(Why does my sorting loop seem to append an element where it shouldn't?).
5. Once sorted you simply write this array, to a file.
BufferedReader br = new BufferReader(new FileReader("name.txt"));
int count = 0;
String line;
String[] names = new String[100];
while((line = br.nextLine()) != null){
names[count] = line;
count++;
}
I want to separate the elements of a text file into different arrays based of whether or not the line contains a question mark. Here is as far as I got.
Scanner inScan = new Scanner(System.in);
String file_name;
System.out.print("What is the full file path name?\n>>");
file_name = inScan.next();
Scanner fScan = new Scanner(new File(file_name));
ArrayList<String> Questions = new ArrayList();
ArrayList<String> Other = new ArrayList();
while (fScan.hasNextLine())
{
if(fScan.nextLine.indexOf("?"))
{
Questions.add(fScan.nextLine());
}
Other.add(fScan.nextLine());
}
Quite a few issues there
nextLine() actually returns the next line and moves on the scanner, so you'll need to read once instead
indexOf returns an int, not a boolean, I'm guessing you're more use to C++? You can use any of the following instead:
indexOf("?") >=0
contains("?")
matches("\?") etc.
please follow the java ways and use camelCase for vars...
Code
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner = new Scanner(new File("foo.txt"));
List<String> questions = new ArrayList<String>();
List<String> other = new ArrayList<String>();
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (line.contains("?")) {
questions.add(line);
} else {
other.add(line);
}
}
System.out.println(questions);
System.out.println(other);
}
foo.txt
line without question mark
line with question mark?
another line
We have
public class UKWacSentenceIterator implements SentenceIterator
which is obviously an Tterator but I don't have any information on what's in SentenceIterator. This class has this property: Scanner fileScanner.
The idea is that the constructor takes an array of files:
public UKWacSentenceIterator() throws IOException {
Properties p = new Properties();
p.load(prop.class.getClassLoader()
.getResourceAsStream("sources/ukwacdump.properties"));
Enumeration<Object> keys = p.elements();
while (keys.hasMoreElements()) {
source.add(keys.nextElement());
}
fileScanner = new Scanner(new File((String) source.get(0)));
}
And in the main method we can use a for loop:
public static void main(String[] args) throws IOException {
for(String line : new UKWacSentenceIterator()) {
System.out.println(line);
}
}
He has currently having a problem with this for loop because once the first file is EOF the for just stops. So he thought would be a good idea to override
#Override
public boolean hasNext() {
if(tmp != null) {
return true;
}
if (this.fileScanner.hasNext()) {
try {
this.skipToSequenceStart();
String sent = this.scanSentence();
this.tmp = sent;
return true;
} catch (Exception e) {
return false;
}
} else {
return advanceFileScanner();
}
}
But he doesn't know how to build advanceFileScanner().
My idea is to just to assign the variable fileScanner to a new Scanner with the next file name and then just copy
this.skipToSequenceStart();
String sent = this.scanSentence();
this.tmp = sent;
return true;
I don't know if he tried yet. I was wondering if you think is a good idea and if you can suggest me a good tutorial on how to create an iterable object. Because right now I'm just guessing, I don't know what the for loop use other than hasNext().
I am not sure but isn't your problem simply that your
fileScanner = new Scanner(new File((String) source.get(0)));
only contains 1 file
I explain. I use to read in many file given a string array of all the files I have to read. Me, I do it that way, I simply declare as an []. I give you an exemple of my code.
BufferedReader[] reader = new BufferedReader[myArrayFiles.length];
for (int i = 0; i < myArrayFiles.length; i++) {
reader[i] = new BufferedReader(new FileReader(myArrayFile[i]));
//do my reading
reader.close();
}
It is with buffered reader but I think you could apply it to your code. Could you do something like that (is source an array ? i assume yes so i use length. Perhaps it's "size()" in your case).
Scanner[] fileScanner = new Scanner[source.length()];
for (i = 0; i < source.length(); i++) {
fileScanner[i] = new Scanner(new File((String) source.get(i)));
}
Then of course you have to refactor the rest of the code to handel the filescanner array
Hope it helps
I was trying to take the input of the filename from the user and then proceed to doing all the calculations. but it keeps returning me an error. the file exists in the same directory.
import java.io.*;
import java.util.*;
public class test{
public static void main(String args[]) throws FileNotFoundException {
//File fin = new File ("matrix1.txt");
Scanner scanner = new Scanner(System.in);
scanner.nextLine(); // removes the first line in the input file
String rowLine = scanner.nextLine();
String[] arr = rowLine.split("=");
int rows = Integer.parseInt(arr[1].trim());
String colLine = scanner.nextLine();
String[] arr2 = colLine.split("=");
int cols = Integer.parseInt(arr2[1].trim());
double [][]matrix = new double [rows][cols];
for (int i=0; i<rows;i++){
for (int j=0; j<cols;j++) {
matrix[i][j]= scanner.nextDouble();
}
}
System.out.println(rows);
System.out.println(cols);
for (int i=0; i<rows; i++)
{ for (int j=0;j<cols;j++) {
System.out.println(matrix[i][j]);
}
}
}
}
There is one issue with the code. The scanner will just give you the name of the file as string from command line. So, you need to first get the command line argument and then create one more scanner using the constructor which takes file object. e.g.
Scanner scanner = new Scanner(System.in);
Scanner fileScanner = new Scanner(new File(scanner.nextLine()));
String rowLine = fileScanner.nextLine();
System.out.println(rowLine);
String[] arr = rowLine.split("=");
int rows = Integer.parseInt(arr[1].trim())
You realize that you are only using a Scanner of type System.in, right? This means that you aren't even looking at a file, you are looking at user input only. This is regardless of whether you have the first line commented out or not. To use a file, you could use a FileInputStream or a couple other File handling classes.
FileInputStream fs = new FileInputStream(new File("matrix1.txt"));
//do stuff with the stream
Heres the java docs for FileInputStream: http://download.oracle.com/javase/1.4.2/docs/api/java/io/FileInputStream.html
Edit: After seeing your comment on what the actual error was, I realize there are more problems with the code than just the way you are handling input. Your error is almost certainly happening at one of the first 2 array accessors, the arr1.trim() calls. That means the user input has nothing on the right side of the "=" sign, or there is no "=" sign in the user input.