Why is my ArrayList Empty? - java

I am working on Project Euler problem 13. ( https://projecteuler.net/problem=13 ) The file "Large_Num_List.txt" is the list provided by the project Euler with each number on its own line with a quote mark at the beginning and end of each line. The statement bial.isEmpty() returns true. Why is this happening? (I suspect because this is my first time using Scanner to read a text file.)
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.ArrayList;
import java.math.BigInteger;
import java.util.Iterator;
public class LargeSumTwo
{
public static void main(String[] args)
{
ArrayList<BigInteger> bial = new ArrayList<BigInteger>();
File file = new File("Large_Num_List.txt");
try
{
Scanner scan = new Scanner(file);
while(scan.hasNextBigInteger())
{
bial.add((BigInteger) scan.nextBigInteger());
}
scan.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
System.out.println(bial.isEmpty());
BigInteger answer = new BigInteger("0");
Iterator<BigInteger> iter = bial.iterator();
while(iter.hasNext())
{
answer.add(iter.next());
}
System.out.println(answer);
}
}

You need to strip the quotes first. hasNextBigInteger() will only return true if Scanner can parse a BigInteger. The quotes around the numbers will cause hasNextBigInteger() to return false.
JavaDoc: http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#hasNextBigInteger%28%29

Should you add BigInteger in this way:
while(iter.hasNext())
{
answer = answer.add(iter.next());
}
as BigDecimal numbers are immutable?

Related

Read comma separated values from a text file in Java and find the maximum number from each line

I used the following code to read all the lines. Now as I understand it I should somehow parse the numbers from each line and apply a function to get the maximum value. The problem is I do not know how to go about it and I do not know what to search for in google. The problem is one of unknown unknowns. Some pointers would be helpful.
import java.io.IOException;
import java.util.List;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.util.ArrayList;
public class KnowNotTest1 {
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
System.out.println("Using Path.readAllLines()");
try{
List<String> fileData = Files.readAllLines(Paths.get("files\\b.txt"));
fileData.forEach(System.out::println);
}
catch (IOException e){
System.out.println(e);
}
}
}
The text file I am reading is as below:
10,11,12
2,13
33,22,1,1
1
And the expected output is:
12
13
33
1
Without checking the input file is correct
readAllLines(Paths.get("/tmp/lines.txt")).stream()
.mapToInt(s -> Arrays.stream(s.split(","))
.mapToInt(Integer::parseInt).max().getAsInt())
.forEach(System.out::println);
the previous one is the best one to do, not directly (there are three important and decoupled parts: read, compute and report) also, it open te door to process in a efficient, online, streaming way (readAllLines break it).
An imperative way is
for(String line: readAllLines(Paths.get("/tmp/lines.txt"))) {
int max = Integer.MIN_VALUE;
for (String word : line.split(","))
max = Math.max(max, Integer.parseInt(word));
System.out.println(max);
}
but is coupled and not compose.
Use mapToXX method of stream api :
public class KnowNotTest1 {
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
System.out.println("Using Path.readAllLines()");
try{
List<String> fileData = Files.readAllLines(Paths.get("files\\b.txt"));
System.out.println("Input: ");
fileData.forEach(System.out::println);
System.out.println("Output: ");
fileData.stream()
.mapToLong(
s -> Arrays.stream(s.split(","))
.mapToLong(Long::parseLong).max()
.getAsLong()).forEach(System.out::println);
}
catch (IOException e){
System.out.println(e);
}
}

I need to create an array list from a list of 1000 numbers on a txt file. Java

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();
}
}

How to serialise an array of 2 lists in a binary file?

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.

java compiler, finding the follow producing duplicates

ive been working on a java compiler assignment that is asking to find the First of a grammar. I have it all ready and done. all the work has been done , but i have one problem. my first is producing duplicates. for example part of my output is this
NonTerminal First
P int void
L int void
D int void
Vd int void
Ts int void
Fn int void
Ps int void void
Ps int void void , the 2nd void is a duplicate. how would i go about removing these duplicates? ill paste my main compiler code were everything happens below.
i suspect i would have to make a change somewere in the findFirst method, since thats were all the action happens , but im not sure what to do.
package compilerproject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.security.KeyStore.Entry;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Compiler {
public static void main(String[] args) {
List<Grammar> gList = getGrammar();
Map<String, List<String>> fList = firstList(gList);
//firstlist returns a hash map LHS and RHS
//save it into fList which is a map of Strings and List so u can use it in findFirst method
printFirstList(fList, gList);
ParserLibrary idList = new ParserLibrary();
}
public static List<String> findFirst(String v, List<Grammar> l)
{
List<String> First = new ArrayList<String>();
for(int i = 0; i < l.size(); i++)
{
if(v.equals(l.get(i).term))
{
String [] s = l.get(i).prod.split(" ");
if(!isNonTerm(s[0]))// is a terminal
{
First.add(s[0]);
}
// if the rhs is a terminal
It would save some troubles using a Set instead of a List.
I kept List as return type, but changed the rest.
public static List<String> findFirst(String v, List<Grammar> l) {
Set<String> first = new TreeSet<>();
Set<String> done = new HashSet<>();
done.add(v);
Grammer previous = null;
for (Grammar gr : l) {
if (v.equals(gr.term)) {
String s = gr.prod.split(" ")[0];
if (!isNonTerm(s)) { // is a terminal
first.add(s);
}
// if the rhs is a terminal
if (s.equalsIgnoreCase("empty") && previous != null) {
String[] stemp = previous.prod.split(" ");
if (v.equalsIgnoreCase(stemp[0]) && stemp.length > 1
&& done.add(stemp[1])) {
first.addAll(findFirst(stemp[1], l)); // <--------- Here it happened
}
//if the rhs is empty , then get the previous grammar
//split it.
//find the first of it and ad it to the first list
}
if (!v.equals(s) && isNonTerm(s) && done.add(s)) {
first.addAll(findFirst(s, l));
}
}
previous = gr;
}
return new ArrayList<String>(first);
}
I still do not find the code entirely clear. So maybe with Set at your disposal, you may find a simpler formulation. To remove the scroll bar I place the open brace on the same line.
To prevent endless recursion I added the set done which "evidently" is not needed.

First time running filereader creates nosuchelement exception

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.

Categories

Resources