I'm trying to create a list from a file, and then use that list in my main class.
Here's my error:
Exception in thread "main" java.lang.NullPointerException
at Read.ReadFile(Read.java:18)
at Main.main(Main.java:6)
Here's my code:
import java.util.*;
public class Main {
public static void main(String args[]){
List<Integer> a = (new Read()).ReadFile();
Read z = new Read();
z.OpenFile();
z.ReadFile();
z.CloseFile();
System.out.println(a);
}
}
And the other class:
import java.util.*;
import java.io.*;
public class Read {
private Scanner x;
public void OpenFile(){
try{
x = new Scanner(new File("numbers.txt"));
}
catch(Exception e){
System.out.println("ERROR");
}
}
public List<Integer> ReadFile(){
List<Integer> a = new ArrayList<Integer>();
while(x.hasNextInt()){
a.add(x.nextInt());
}
return a;
}
public void CloseFile(){
x.close();
}
}
And here's my text file:
1 2 3 4 5 6 7 8 9
I hope someone can help me.
ps. I'm learning to program on my own and English isn't my first language so I'm sorry if there are beginner mistakes.
List<Integer> a = (new Read()).ReadFile();
You are calling ReadFile(); here before opening a file. So, x will be null and results in NullPointerException.
One way to solve this issue would be:
move ArrayList<> inside Read class and add get method.
Your sequence of statements should be like this:
Read z = new Read();// instantiate the reader
z.OpenFile(); //open the file
List<Integer> a = z.ReadFile(); //read and hold the values in array
z.CloseFile(); //close the file
System.out.println(a); //print the values
No need of first statement. Get the reader, open the file, read the values, close the file and then print the values.
In the following line, you create a new instance of Read and immediately call ReadFile() instead of first creating the Scanner object with OpenFile():
List<Integer> a = (new Read()).ReadFile();
Related
The Numbers are not on the same line, there are 1000 lines each with a number.
This is the code I have but I receive an error when I run it, it points to the int part of the array list and says unexpected type.
import java.util.ArrayList;
import java.io.*;
import java.util.Scanner;
public class Homework4
{
public static void main(String[] args) throws IOException
{
//Variables
int num;
int temp;
Scanner kb = new Scanner(new File("number.txt"));
ArrayList<int> list = new ArrayList<int>();
while (kb.hasNextLine())
{
list.add(kb.nextLine());
}
//Close File
inputFile.close();
}
}
You have to use the wrapper class Integer.
Change ArrayList<int> to ArrayList<Integer>
Similarly,
long-> Long
double-> Double
char-> Character
float-> Float
you can read more about primitive type collections here and here
Also, when you read the data from file, using kb.nextLine() it returns String type. You can convert it to Integer type using Integer.parseInt() in the following way.
list.add( Integer.parstInt( kb.nextLine() ) );
The next part is, closing the resource.
you have not declared a variable by name inputFile. it must be kb instead.
kb.close();
The complete code is as follows
public static void main(String[] args) throws IOException {
Scanner kb = new Scanner(new File("number.txt"));
ArrayList<Integer> list = new ArrayList<>();
while (kb.hasNextLine()) {
list.add(Integer.parseInt(kb.nextLine()));
}
kb.close();
}
Hope this helps.
Since you claim to be reading from a text file, you can use class java.nio.file.Files to read it and then use java's stream API to map each line of the text file to an Integer and collect all those Integers to a java.util.List, as shown in the following code:
Path path = Paths.get("path-to-your-file");
try {
List<Integer> integers = Files.lines(path) // throws java.io.IOException
.map(Integer::parseInt)
.collect(Collectors.toList());
System.out.println(integers);
}
catch (IOException x) {
x.printStackTrace();
}
You have several errors in that code. Firstly, use Integer object wrapper for int primitive type. Next, you need to parse the read String to integer type with the Integer.parseInt() method. And close the Scanner instance instead of undefined file variable.
Try following code:
import java.util.ArrayList;
import java.io.*;
import java.util.Scanner;
public class Homework4{
public static void main(String[] args) throws IOException
{
//Variables
int num;
int temp;
Scanner kb = new Scanner(new File("number.txt"));
ArrayList<Integer> list = new ArrayList<>();
while (kb.hasNextLine())
{
list.add(Integer.parseInt(kb.nextLine()));
}
//Close File
kb.close();
}
}
I made a class that reads a text file into an integer array, which I believe I've done correctly. Then I wanted to make a method (getInt();) within that to get the the first index of the array, and then each time it gets called get the following index element.
I had the idea to increment it every time it gets called to get the following index element, but the main problem I am having is that I cannot access my list outside of the try statement and I am therefore unable to make a method for it.
Can anyone suggest a piece of code or any advice on how to create this method?
import java.io.*;
import java.util.*;
public class ScannerIntegerList {
public static void main(String[] args) {
try {
FileReader file = new FileReader("file.txt");
BufferedReader input = new BufferedReader(file);
List<Integer> list = new ArrayList<Integer>();
String temp = "";
while ((temp = input.readLine()) != null)
if (!temp.trim().equals("0"))
list.add(new Integer(temp));
input.close();
int i = 0;
System.out.println(list.get(i));
i++;
} catch (IOException ie) {
System.out.println(ie);
}
}
}
Also as a side note I am using eclipse and whenever I try and remove public static void main( String [] args) it tells me I need it, can anyone explain why this happens and how I can get around it, specifically with this bit of code?
When this class is finished the filename will also come from the command line so any advice on this would be greatly appreciated.
Many thanks in advance
If you want to use list outside the try block, declare and initialize it outside.
Also, use try-with-resources when working with closeable resources, like this:
List<Integer> list = new ArrayList<>();
try (BufferedReader input = new BufferedReader(new FileReader("file.txt"))) {
String temp = "";
while ((temp = input.readLine()) != null) {
if (!temp.trim().equals("0")) {
list.add(new Integer(temp));
}
}
} catch (IOException e) {
e.printStackTrace();
}
// you can use list here, knock yourself out
If the filename will come from the command line,
then you really need the public static void main(String[] args) method.
Your program will receive command line arguments in the args array.
If the filename is the first command line argument,
you can use it via args[0].
I'm pretty new to programming feel free to be harsh in your replies. Anything helps.
Basically I'm trying to call in a method LineCount() but when I try to compile the command prompt complains about .class being expected at String[A] (line 8 I believe)
*Thank you guys for all your help! My code works now! I really appreciate all the input
import java.util.Scanner;
import java.io.*;
public class FileCount{
public static void main(String[] args) throws IOException{
String[] in = new Scanner(new File(args[0]));
System.out.println(lineCount(String[] in);
}
public static void lineCount(String[] A){
// check number of command line arguments
if(args.length != 1){
System.err.println("Usage: LineCount file");
System.exit(1);
}
// count lines, words, and chars in file
int lineCount = 0;
while( in.hasNextLine() ){
in.nextLine();
lineCount++;
}
in.close();
System.out.println( args[0]+" contains "+lineCount+" lines" );
}
}
First of all
System.out.println(lineCount(String[] in); // this is incomplete need to close)
Assuming you did mistake while you putting the question here, Change
System.out.println(lineCount(String[] in));
To
System.out.println(lineCount(in));
-> There are many mistakes in your code, Besides other answers want to add that, Since you are passing lineCount(in) as an argument to the linecount() method , then refer to the parameter in lineCount(String[] A) now via A variable and not in.
-> Also you cannot refer to args inside linecount() method since it is a parameter of main() method and hence is limited to it in its scope.
-> You cannot do this String[] in = new Scanner(new File(args[0])); , you are assigning a Scanner instance to an String Array, you have to do it like this
Scanner in = new Scanner(new File(args[0]));
-> You are calling linecount() inside a System.out.println() method , although your method linecount() has a return type of void, Dont put your method inside print() function , because anyways it has got print() statements inside it.
-> Maybe last , there could be more , Since your in variable is of type Scanner , change your method declaration to
public static void lineCount(Scanner in){
and now call it like lineCount(in) from main().
Edit :- Since you are a beginner i will give you working code for your question:-
import java.util.Scanner;
import java.io.*;
public class FileCount{
public static void main(String[] args) throws IOException{
// check number of command line arguments, and check it in main()
if(args.length != 1){
System.err.println("Usage: LineCount file");
System.exit(1);
}
Scanner in = new Scanner(new File(args[0]));
System.out.println( args[0]+" contains "+lineCount(in)+" lines" ); //call this line in main() and not in linecount() as you refer to both args and need the linecount.
}
public static int lineCount(Scanner in){
// count lines, words, and chars in file
int lineCount = 0;
while( in.hasNextLine() ){
in.nextLine();
lineCount++;
}
in.close();
return lineCount; //return the linecount from method
}
}
Your first problem String[] in = new Scanner(new File(args[0])); creating a Scanner object and asigning it to an array it does not work like this. Change your code to read the file and store it in some arraylist like
List<String> list= new ArrayList<String>();
Scanner in = new Scanner(new File(args[0]));
while (in.hasNextLine()) {
// find next line
String line = in.nextLine();
list.add(line);
}
Then if you want can convert to list to String array which is not really necessary like this
String[] strArr = list.toArray(new String[0]);
System.out.println(java.util.Arrays.toString(strArr));
lineCount(strArr);
Then call the lineCount() method which counts the lines in the files.
public static void lineCount(String[] A){
System.out.println("File contains "+A.length+" lines" );
}
I have created a method called fileWriter which outputs an array of random ints into a txt file. This works correctly, but than when I try to use my other method of fileReader which is supposed to read that file and add it to another array it will give me a NoSuchElementException even though the file has been created(I have checked). The second time I run the program it does work like it is supposed to but the file now has twice as many numbers as it did before. I have tried to create a blank file before importing the array into it but the first time I run the program it still gives me the same error message. If anyone could give a hint on why this is happening it would be greatly appreciated.
Here is my code:
/*******************************************************************************/
import java.util.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class randomNum {
public static void main(String[] args) {
FileWriter f;
try {
//here i create a blank file to try and fix the NoSuchElements exception
PrintWriter x=new PrintWriter(f=new FileWriter("C:\\LOG\\a3Unsorted.txt"));
} catch (IOException e) {
e.printStackTrace();
}
Random gen = new Random();
//This creates the original array
int[] array=new int[10];
for(int i=0;i<array.length;i++){
int rdm=gen.nextInt(100);
array[i]= rdm;
}
//call the other class
Sort num = new Sort(array);
//call method fileWrite from class Sort to send the array to the file
Sort.fileWrite(array);
//call method fileRead from class Sort to read the file thats been created (this is where i think could be the issue)
Sort.fileRead(array);
for(int i=0;i<array.length;i++){
System.out.println(array[i]);
}//prints out the array from the file in default output
}
}
/***************************************************************************/
import java.io.*;
import java.util.NoSuchElementException;
import java.util.Scanner;
public class Sort {
private static PrintWriter out;
private static FileWriter file;
public Sort(int[] array) {
}
/***************************************************************************/
public static void fileRead(int[] array){
Scanner s = null;
try {
s = new Scanner(new File("C:\\LOG\\a3Unsorted.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
array = new int[s.nextInt()];
for (int i = 0; i < array.length; i++)
array[i] = s.nextInt();
}
/**************************************************************************/
public static void fileWrite(int[]array){
try {
out = new PrintWriter(file = new FileWriter("C:\\LOG\\a3Unsorted.txt",true));
for (int i=0; i<array.length; i++)
{
out.println(array[i]);
}
out.close();
} catch (IOException ex) {
}
}
}//class
At this line
array = new int[s.nextInt()];
there's something very wrong. What you actually do is to read the first number from the file and then instantiate an array with the length given by this number. I don't think this is what you want to. If this number is larger than the amount of remaining numbers to be read, you will get the exception when you'll try to read beyond the end of the file.
But what's the point in passing the array parameter to this method
public static void fileRead(int[] array)
, if you assign a new array instance to the array variable? The original reference will be lost.
Anyway, your code is a little messy with lots of statics and unused variables, e.g. the constructor of Sort.
I'm having troubles reading a file and then placing its contents into an array. The console says my error is here:
Exception in thread "main" java.lang.NullPointerException
at readFile.readFile(readFile.java:23)
at apples.main(apples.java:6)
However I do not now how to fix it.
import java.util.*;
import java.lang.*;
import java.io.*;
public class readFile {
private Scanner x;
public void openfile(){
try{
x = new Scanner( new File("/Users/Zachary/Desktop/chinese.txt"));
}
catch (IOException e){
System.out.println("you failed foo");
}
}
public void readFile(){
int y = 0;
int[] nums = null;
while(x.hasNext()){
for(y=0; y<10;y++) {
nums[y] = x.nextInt();
}
System.out.println(nums[y]);
}
}
public void closeFile(){
x.close();
}
}
public class apples {
public static void main (String[]args){
readFile r = new readFile();
r.openfile();
r.readFile();
r.closeFile();
}
}
You seem to have a NullPointerException at:
nums[y] = x.nextInt();
That is because of this line:
int[] nums = null;
It is null, so you can't put stuff in it. Here's a simple fix:
int[] nums = new int[10];
The above code will initialize nums so that it is an empty (not really - it's actually filled with 0) array like this:
---------------------
|0|0|0|0|0|0|0|0|0|0|
---------------------
If you want to be able to add as many numbers to it as you want, you will need an ArrayList (link).
Also, this code will throw an error:
for(y=0; y<10;y++) {
nums[y] = x.nextInt();
}
System.out.println(nums[y]);
That is because your System.out.println doesn't know what y is. Just move the System.out.println into the for loop so it can "see" y. (This is called scope)
The compiler error states that the error occurs at "readFile.java:23". This is line 23 of the file readFile.java. I believe that is this line:
nums[y] = x.nextInt();
The problem is that you declared nums as:
int[] nums = null;
When you try to access an array that is initialized to null, you should not be surprised to get a NullPointerException.
To fix the problem, you need to create an array object:
int[] nums = new int[SOME_SIZE];
You will need to provide the size yourself as you have not provided enough information for me to guess the value.
is the inner loop really necessary? you are looping x * 10 times which is really not a good way to assigned data.