This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 7 years ago.
problem: i am trying to take string input from files and then store it in an arraylist then trying to search specific words and removing them and the resultant output should go to another text file... this code works fine if there are only 2 elements in a list . but if i put more it showing java.lang.IndexOutOfBoundsException index:12 size 12 . i am not that good in java so pls help and sorry for any silly mistakes ...
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
public class replace{
public static void main(String[] args) throws Exception{
String filen = "C:/Users/Damini/Desktop/hi.txt";
FileReader file = new FileReader("C:/Users/Damini/Desktop/rules.txt");
BufferedReader b = new BufferedReader(file);
PrintWriter pw = new PrintWriter(filen);
List<String> temps = new ArrayList<String>(10);
String line = b.readLine();
while(line!= null)
{
temps.add(line);
line = b.readLine();
}
int size = temps.size()-1;
for(int i=0;i<=size;i++)
{
if(temps.get(i).equals("hello"))
{
temps.remove(i);
}
}
pw.println(temps);
pw.close();
System.out.println("output:"+ temps);
b.close();
}
}
Try to write your arrayList temps without capacity 10 like this:
List<String> temps = new ArrayList<String>();
the capacity is how many elements the list can potentially accommodate without reallocating its internal structures.
In java arrays are 0 based. It means that an array of size 12 has index between 0 and 11.
Modify your code with
for (int i = 0; i <= size; i++)
because size is 12 and last valid index is 11.
Related
This question already has answers here:
Convert list to array in Java [duplicate]
(11 answers)
Closed 28 days ago.
I get the question about choosing a random word from user input using Knuth's shuffling algorithm, but the problem is I have the constraint of using some specific libraries.
(here is the link for more details - my part is to form the random word java file) https://coursera.cs.princeton.edu/algs4/assignments/hello/specification.php
My main problem is, my program accepts the user's input in form of a string list and uses the while-loop to add more detail, but to apply the algorithm I must convert the list into arrays; however, the program doesn't get my data and it always returns an empty array. What should I do, thanks in advance!
Here is my code:
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;
public class RandomWord {
public static void main(String[] args) throws IOException {
StdOut.println("enter your words"); // StdIn.hasNextChar() = !StdIn.isEmpty()
ArrayList<String> mylist = new ArrayList<String>();
String store = new String();
int count = 1;
String[] arr = new String[mylist.size()];
int k = 0;
store = StdIn.readString();
mylist.add(store);
if (StdIn.hasNextChar() == false || mylist.contains(null)) {
StdOut.println("you enter nothing");
}
else {
while (count == mylist.size()) {
while (StdIn.hasNextChar() == true) {
store = StdIn.readString();
mylist.add(store);
count++;
mylist.toArray(arr);
System.out.println(Arrays.toString(arr));
}
}
}
}
}
Here is my test result:
enter your words
hi ho // my input from the terminal
[] // the result: an empty array - not what I want
Notice: If I use System.out.println(mylist) it still prints for me the ArrayList full of input ( [ hi, ho] ) but I think that is the list - not the array, in case if I can shuffle the list entries, can anyone show me how to do that in the simplest ways with Knuth's algorithm!
I try to add more specific constraints, such as the while-loop may end when the list size == the number of words the user adds into the program, but It doesn't work as I think
I expect the data can convert from strings -> a String[] but don't have to go through the list conversion
Your problem is folowing line
mylist.toArray(arr);
The toArray method return the filled array. the parameter is only for init of the new array.
Try the follwowing
arr = mylist.toArray();
I am attempting to write a program for school that counts the frequency of tokens (words in this case) in a given file. The driver program should use a list structure to get each word in the same format from the file. Then, a FreqCount object is created and will eventually use the hashmap to count token frequency. I got the driver to read the file and get it into an ArrayList, but now the issue is either (a) the code to input the list is not working, so it is empty (b) the print function is not working properly (unlikely since I ripped it straight off of w3schools to test). I have thought about this for a while and can't figure out why it won't work.
Driver:
package threetenProg3;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.ArrayList;
import threetenProg3.FreqCount;
public class Driver {
public static void main(String[] args) throws FileNotFoundException{
File in = new File("test.txt");
Scanner scanFile = new Scanner(in);
ArrayList<String> parsed = new ArrayList<String>();
FreqCount fc = new FreqCount(parsed);
while(scanFile.hasNext()) { //if this ends up cutting off bottom line, make it a do while loop
parsed.add(scanFile.next().toLowerCase());
}
System.out.println("ArrayList: \n");
for(int i = parsed.size()-1; i>=0; i--) { //prints arraylist backwards
System.out.println(parsed.get(i));
}
System.out.println("\n Hashmap: \n");
fc.printMap();
scanFile.close();
}
}
FreqCount:
package threetenProg3;
import java.util.HashMap;
import java.util.ArrayList;
public class FreqCount {
HashMap<String, Integer> map = new HashMap<String, Integer>();
FreqCount(ArrayList<String> plist){
for(int i = plist.size()-1; i>=0; i--) { //puts list into hashmap
map.put(plist.get(i), 1);
}
}
//methods
public void printMap() {
for (String i : map.keySet()) {
System.out.println("key: " + i + " value: " + map.get(i));
}
}
}
The only thing I could think of was changing the List to an ArrayList, but that had no effect.
Edit: I realized I forgot a bunch of important stuff here.
Text file:
ONE TWO ThReE FoUR fIve
six seven
EIGHT
NINE
TEN ELEVEN
which outputs:
eleven
ten
nine
eight
seven
six
five
four
three
two
one
When printing the arraylist, it works perfectly. The issue is when it comes to printing the hashmap. Currently, the output for printing the hashmap is blank (as in nothing shows up after "Hashmap: ".
Thanks to anyone who can help, quick feedback is greatly appreciated :)
This line:
FreqCount fc = new FreqCount(parsed);
does not magically "bind" the array list parsed to the map. It just adds what's currently in parsed into fc.map. If you examine your code, you'll see that parsed is empty at the time the above line executes. So you are adding nothing to the map.
You should move that line to after you have added to the array list. For example, just before you print "Hashmap:":
FreqCount fc = new FreqCount(parsed);
System.out.println("\n Hashmap: \n");
fc.printMap();
you have to create a frequency counter after reading the list because you are inserting values into the map in the constructor.
And since the list is still empty when you created the FreqCount you don't see any output.
package threetenProg3;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.ArrayList;
import threetenProg3.FreqCount;
public class Driver {
public static void main(String[] args) throws FileNotFoundException{
File in = new File("test.txt");
Scanner scanFile = new Scanner(in);
ArrayList<String> parsed = new ArrayList<String>();
while(scanFile.hasNext()) { //if this ends up cutting off bottom line, make it a do while loop
parsed.add(scanFile.next().toLowerCase());
}
System.out.println("ArrayList: \n");
for(int i = parsed.size()-1; i>=0; i--) { //prints arraylist backwards
System.out.println(parsed.get(i));
}
System.out.println("\n Hashmap: \n");
FreqCount fc = new FreqCount(parsed); // Moved fc here
fc.printMap();
scanFile.close();
}
}
I was trying to scan a file that has an array of doubles. I'm using the code below but it's only outputting 0.0 for every entry. Why is this and how can I fix it?
Scanner scanner = new Scanner("file.txt");
double[] array = new double[256 * 256];
for (int i = 0; i < array.length; i++) {
if (scanner.hasNextDouble()) {
array[i] = scanner.nextDouble();
}
}
System.out.println(array[0]);
An example of the file I'm scanning is
0.22131145 0.22131145 0.22131145 0.22841525 0.22841525 ...
The main issue is with the instantiation of the Scanner object. In this case you need to pass a File object into it, not just a string, and make sure you specify the correct file path. Refer to the official documentation for advice.
Secondly, you need to use a while-loop. An if-statement will execute only once, but you would want the Scanner to continue looking whilst there is info inside the file.
Thirdly, don't use an array for storing the values. It's too risky because you need to know the size of the array beforehand, meaning that you would need to loop twice, which would be inefficient, or you are hard coding, as you are doing here. If someone were to add or remove values from the file, you will get unexpected results. Rather use a dynamic data structure such as a List.
public static void main(String[] args) throws FileNotFoundException {
String filepath = "file.txt";
Scanner scanner = new Scanner(new File(filepath));
List<Double> list = new ArrayList<>();
while (scanner.hasNextDouble()) {
list.add(Double.valueOf(scanner.next()));
}
scanner.close();
System.out.println(list.get(0));
}
There are four problems with your code:
Blocker: Scanner expects a File object but you haven't used it in this way. You need to use the following syntax:
Scanner scanner = new Scanner(new File("file.txt"));
Performance: You can improve the performance of your program by including scanner.hasNextDouble() in the condition which checks the value of i, as shown below:
for (int i = 0; i < array.length && scanner.hasNextDouble(); i++) {
array[i] = scanner.nextDouble();
}
This will terminate the loop as soon as scanner.hasNextDouble() returns false; otherwise, the loop in your code will continue to run until i < array.length evaluates to false irrespective of the value returned by scanner.hasNextDouble().
Resource leak: You have not closed the Scanner object. Put the following line after the loop finishes:
scanner.close();
Missed functionality: You haven't printed the complete array. Your statement, System.out.println(array[0]) will print only the first element in the array. Change it as follows to print the complete array:
System.out.println(Arrays.toString(array));
Given below the code incorporating all the above-mentioned comments:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner = new Scanner(new File("file.txt"));
double[] array = new double[256 * 256];
for (int i = 0; i < array.length && scanner.hasNextDouble(); i++) {
array[i] = scanner.nextDouble();
}
scanner.close();
System.out.println(Arrays.toString(array));
}
}
Memory utilization: You have used a fixed-sized array which is fine if the number of elements to be stored is equal to the size of the array. However, if it is not the case (i.e. if the number of elements to be stored can be less than or more than the specified size), you should use a Collection e.g. an ArrayList which is a kind of dynamic array. This will help you in many ways: (a) You will save memory if the number of elements to be stored is less than the specified size (b) You do not need to change your code in order to increase the size of the array when you need to store more elements than you have already specified (c) The Collection provides with a rich API to deal with elements. By leveraging this API, your code can be crisp, more performant, maitainable etc.
Given below the code incorporating the 5th point:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner = new Scanner(new File("file.txt"));
List<Double> list = new ArrayList<>();
while (scanner.hasNextDouble()) {
list.add(scanner.nextDouble());
}
scanner.close();
System.out.println(list);
}
}
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 6 years ago.
I have an assignment where I have to read in a file with information about hurricanes from 1980 to 2006. I can not figure out what the error is. I have a section of code like this:
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
public class Hurricanes2
{
public static void main(String[] args)throws IOException
{
//declare and initialize variables
int arrayLength = 59;
int [] year = new int[arrayLength];
String [] month = new String[arrayLength];
File fileName = new File("hurcdata2.txt");
Scanner inFile = new Scanner(fileName);
//INPUT - read data in from the file
int index = 0;
while (inFile.hasNext()) {
year[index] = inFile.nextInt();
month[index] = inFile.next();
}
inFile.close();
That is just the first part. But in the section with the while statement, there is an error with the year[index] = inFile.nextInt(). I have no idea what the error means and I need help. Thanks in advance.
Try adding index++ as the last line of your while loop. As it is now, you never increment it, so you're only filling and replacing the first numbers in your array.
I personally wouldn't use Scanner() but instead Files.readAllLines(). It might be easier to implement if there is some sort of delimiting character to split the hurricaine data on.
For instance, let's say your text file is this:
1996, August, 1998, September, 1997, October, 2001, April...
You can do the following if these assumptions I've made hold true:
Path path = Paths.get("hurcdata2.txt");
String hurricaineData = Files.readAllLines(path);
int yearIndex = 0;
int monthIndex = 0;
// Splits the string on a delimiter defined as: zero or more whitespace,
// a literal comma, zero or more whitespace
for(String value : hurricaineData.split("\\s*,\\s*"))
{
String integerRegex = "^[1-9]\d*$";
if(value.matches(integerRegex))
{
year[yearIndex++] = value;
}
else
{
month[monthIndex++] = value;
}
}
This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 7 years ago.
I'm trying to take numbers (integers) from a website and put them into an array for further manipulation. Here is what I have so far
import java.io.IOException;
import java.net.URL;
import java.util.Scanner;
public class Scores {
public static void main(String[] args) throws IOException{
URL url = new URL("http://cs.armstrong.edu/liang/data/Scores.txt");
Scanner input = new Scanner(url.openStream());
int []score = new int [100];
int i = 0;
while (input.hasNextInt()) {
score[i++] = input.nextInt();
System.out.println(score);
}
}
}
The problem is all of the numbers in the array come back as [I#6bc7c054, any help would be appreciated.
System.out.println(score[i]);
you were printing the array itself