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.
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 am creating a Java program that reads two text files, selects 10 words at random from each file and stores them in an array of two string lists. I have created the following code so far, however this only reads the words, it doesn't store them. I also need to serialize the array of 2 lists in a binary file. How can this be done? Some help with this would be greatly appreciated!
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
import static java.nio.file.StandardOpenOption.CREATE;
public class RandomWordGenerator {
public static void main(String[] args) throws IOException {
Path outputFile = Paths.get("output.txt");
ArrayList<String> randomWords1 = randomWordsFromFile("input1.txt", 10);
ArrayList<String> randomWords2 = randomWordsFromFile("input2.txt", 10);
OutputStream outputStream = new BufferedOutputStream(Files.newOutputStream(outputFile, CREATE));
System.out.println(randomWords1);
System.out.println(randomWords2);
outputStream.flush();
for (int i = 0; i < randomWords1.size(); i++) {
outputStream.write(randomWords1.get(i).getBytes());
}
for (int i = 0; i < randomWords2.size(); i++) {
outputStream.write(randomWords2.get(i).getBytes());
}
outputStream.close();
}
private static ArrayList<String> randomWordsFromFile(String fileName, int count) throws FileNotFoundException {
Scanner scanner = new Scanner(new File(fileName));
ArrayList<String> words = new ArrayList<>();
while (scanner.hasNext()) {
words.add(scanner.next());
}
return randomFromWords(words, count);
}
static private ArrayList<String> randomFromWords(ArrayList<String> words, int count) {
ArrayList<String> randomWords = new ArrayList<>();
for (int i = 0; i < count; ) {
int random = new Random().nextInt(words.size());
if (randomWords.add(words.get(random))) {
i++;
}
}
return randomWords;
}
}
Your code should read two files, select ten random words from each file and store the ten words from each file into two lists. Does it do this correctly? If it does not then fix all the errors before proceeding further. You can ask here with specific errors you cannot fix. Be sure to explain what your code is meant to do, and the error it makes to prevent it doing that.
Once everything is working correctly, go on to the next stage. Is the binary Serialization part of your requirement? If not, then I would use a simple CSV file in UTF-8, which is also a binary file (as are all files at heart). If actual Serialization is required, then read the Javadocs and tutorials on Serialization. Write some code and come back here if you cannot get it to work.
I have a program that opens a .txt file in my project folder and reads the line/s in it. I know the file reading works so it isn't an I/O problem (or swing, since I am using that also) but when I set nim (my variable) = anArray[num] (also a variable) it doesn't work. Note: When I run the program it reaches the println("First Declaration") so its just the setting to array that doesn't work. Thanks :)
import java.io.File;
import java.util.Scanner;
import javax.swing.JFrame;
public class SpanishSetOne extends JFrame {
private static Scanner s;
public String[] anArray;
public String nim;
public SpanishSetOne() {
super("Spanish Set 1");
initFile("spanish");
setSize(500,500);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void initFile(String name) {
try{
s = new Scanner(new File(name + ".txt"));
System.out.println("setScanner");
}catch(Exception e) {
System.out.println("ERROR - Could not read file");
}
int num = 0;
while(s.hasNext()) {
System.out.println(("Made it into the loop"));
nim = s.nextLine();
System.out.println("First declaration");
anArray[num] = nim;
System.out.println(anArray[num]);
num++;
}
}
}
you need to initialize your array something like this:
String[] array = new String[10];
I would also consider using an ArrayList so you don't have to worry about the size of your array
You must initialize an array before you can use it.
anArray = new String[count];
//count being the number of elements you want to store in the array
You have not initialized the array.
public String[] anArray; Its an String array with zero memory locations allocated to store any String.
Use String[] anArray = new String[numberOfElements];
// Here anArray will be a String Array with 'numberOfElements' memory location.
Highly recommend to use
List<String> anArrayList = new ArrayList<String>();
Hope this helps.
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();
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.