Limiting an Array - java

This is my code below, I get an java.lang.IndexOutOfBoundsException & I can't fix it? I am supposed to STOP the error from coming up because I have over 100 names in the file!
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ArrayPractice1 {
public static void main(String[] args) throws FileNotFoundException
{
String[] names = new String[100];
Scanner scan = new Scanner(new File("names.txt"));
int index = 0;
while (scan.hasNext()){
names[index]=(scan.nextLine());
index++;
}
for(int i = 0; i <index -1; i++){
System.out.println(names[i]);
}
}
}

youre not working with an ArrayList of Strings, you're working with a plain array of Strings.
seems like youre getting more than 100 items from scan.hasNext() and so you eventually try to access names[100] and get the exception you describe
instead, you could use this:
ArrayList<String> names = new ArrayList<String>();
and then
while (scan.hasNext()){
names.add(scan.nextLine());
}
and you wont have to worry about knowing the exact size beforehand

If the size of the input is not known at compile time, consider using an ArrayList instead of an array.
Just add the elements to the ArrayList using names.add(scan.nextLine()):
ArrayList<String> names = new ArrayList<String>();
while (scan.hasNext()) {
names.add(scan.nextLine())
}

You are giving 100 as the size of array.If your file have more than 100 lines, definitely it will throw exception

change the condition in your while loop to
while (scan.hasNext() && index < 100)
this will stop the read loop after you fill up the array

Why not making it independent from any upper limit? Use an ArrayList:
ArrayList<String> names = new ArrayList<String>();
Scanner scan = new Scanner(new File("names.txt"));
while (scan.hasNext()){
names.add(scan.nextLine());
}
for(String name : names){
System.out.println(name);
}

Related

How to add as many elements as i want to an array list by an input?

How to add as many elements as I want to an array list - with only one insert operation?
I want to add 5 Items to a buy list with one input. And then I want to print the 5 items out.
This is what I have done now:
package paket1;
import java.util.ArrayList;
import java.util.HashMap;
import javax.swing.JOptionPane;
public class Class2 {
public static void main(String[] args) {
int i = 0;
while (i != 5) {
String Eingabe = JOptionPane.showInputDialog("Add Einkaufsliste");
ArrayList<String> einkaufsListe = new ArrayList<>();
einkaufsListe.add(Eingabe);
}
}
}
Each time your iteration runs, you are creating a new, empty list, and adding one element to it. But this loop will never finish, because i is never incremented, and will always be 0. The correct code would look like this:
int i = 0;
List<String> einkaufsListe = new ArrayList<>();
while (i <= 5) {
String eingabe = JOptionPane.showInputDialog("Add Einkaufsliste");
einkaufsListe.add(eingabe);
i++;
}
And then you will have to print it as well.
I think it is better to extract this logic into separate method, that retrieves required list. If you want to use ArrayList, do not forget to set initial size.
public static List<String> gibAlleEinkaufe(int insgesamt) {
List<String> einkaufsListe = new ArrayList<>(insgesamt);
for(int i = 0; i < insgesamt; i++)
einkaufsListe.add(JOptionPane.showInputDialog("Add Einkaufsliste"));
return einkaufsListe;
}

Java scanner read from csv using delimeter and ignore endline

The code:
public static void main(String[] args) throws Exception{
Scanner scn = new Scanner(new File ("kektura.csv"));
int kezd = 0;
List <String> indul = new ArrayList<>();
List <String> veg = new ArrayList<>();
List <Double> hossz = new ArrayList<>();
List <Integer> emel = new ArrayList<>();
List <Integer> lejt = new ArrayList<>();
List <Boolean> pecset = new ArrayList<>();
kezd=scn.nextInt();
scn.nextLine();
while(scn.hasNextLine())
{
scn.useDelimiter(";");
indul.add(scn.next());
veg.add(scn.next());
hossz.add(scn.nextDouble());
emel.add(scn.nextInt());
lejt.add(scn.nextInt());
if(scn.next()=="n")
{
pecset.add(Boolean.TRUE);
}
else
{
pecset.add(Boolean.FALSE);
}
scn.nextLine();
}
for(Object x : pecset)
{
System.out.println(x);
}
scn.close();
}
And the file (It's a csv file, it has more lines, but they are the same pattern):
192
Sumeg, vasutallomas;Sumeg, buszpalyaudvar;1,208;16;6;n
Sumeg, buszpalyaudvar;Mogyorosi-domb, geologiai bemutatohely;1,512;24;8;n
Mogyorosi-domb, geologiai bemutatohely;Sumegi bazaltbanya vasutallomas;1,576;13;43;n
Sumegi bazaltbanya vasutallomas;Sarvaly erdeszhaz, pecsetelohely;2,101;69;18;i
I have a problem with reading this.
Read the first line, it's okay.
But the second line isn't good, because (i think) the delimeter reads until the ( ; ) character, but in the end of the line, there's not a ( ; ) .
The last line of the while, I wrote scn.nextLine to read the \n character, but it doesn't work.
I know thats a possible way, to read the line, and split it, but it's a school project, and the teacher told us to find out another solution.
Is there a way, to solve this?
As your teacher wants you to find another solution, I propose to use a BufferedReader to read the file in single lines. For each line you can then use String#split() and finally convert the respective parts to the required type (Integer#parseInt() etc).
However, as this is stated as a homework question, I will not provide a full example.

How do I add / delete a line from a text file?

I am unsure on how to give the user an option to add / delete a name from the existing text file. The current code works fine and reads in names from the text file. Could someone give me a hand on this?
import java.io.File;
import java.util.Scanner;
public class AddOrDeleteNames {
public static void main(String[] args) throws Exception {
String[] names = new String[100];
Scanner scan = new Scanner(new File("names.txt"));
int index = 0;
while (scan.hasNext()){
names[index]=(scan.nextLine());
index++;
}
for(int i = 0; i < index; i++){
System.out.println(names[i]);
}
scan.close();
}
}
It is possible, almost everything is, but you'll find it very difficult to do using arrays.
I would instead use an ArrayList which is similar, but much, much better than just regular ol' arrays.
A String ArrayList is defined like so:
ArrayList<String> names = new ArrayList<String>();
You can add using the add function of the ArrayList:
while (scan.hasNext())
names.add(scan.nextLine());
Then, to remove a name from the text file, just remove it from the names ArrayList using the remove function, and write the modified ArrayList to the file:
names.remove("Some Name Here");
PrintWriter writer = new PrintWriter("names.txt", "UTF-8");
for (int i = 0; i < names.size(); i++)
writer.println(names.get(i));
writer.close();
Likewise, to add a new name to the file, just add the new name to the ArrayList before you write it to the file, using the add function

How create an array in run time in java?

**I want to know how to create an array in run time in java? For an instance say that i want to check the numbers which divides 498 ,and i want to put them into an array ?
for(i=1;i<=498/2;i++){
int z=498%i;
if(z==o)// put the i into the array if not continue
you can create an ArrayList while iterating for loop and later you can convert it to Array like below if you need an array at the end of process
integer [] myNumbers = list.toArray(new Integer[list.size()]);
this will help you not worrying about re sizing of Array at runtime
so finally your code should look like following
List<Integer> numbers = new ArrayList<Integer>();
for(i=1;i<=498/2;i++){
int z=498%i;
if(z==o){
numbers.add(i);
}
}
int [] myNumbers = numbers.toArray(new Integer[numbers.size()]);
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner scan= new Scanner(System.in);
int size=scan.nextInt(); //Enter size of array
int[] array = new int[size]; //create array at runtime
}
}
int[] numbers = new int[SIZE_OF_ARRAY_HERE];
Or if you want to be able to resize it use an ArrayList instead.
I understand that by "at runtime", you mean that you don't know the size of an array at the beginning, and want the array to grow if needed (correct me if I'm wrong). You can use ArrayList for this:
Declare your list first:
List<Integer> myList = new ArrayList<Integer>();
Use it in your loop:
for (int i=1; i<=498/2; i++) {
int z = 498 % i;
if (z == 0) {
//add i to the list
myList.add(i);
}
}
You can then print the list with:
System.out.println(myList.toString());
Please read about ArrayLists here, or just google it, there's plenty tutorials on ArrayLists.

Java Arraylist got java.lang.IndexOutOfBoundsException?

I'm a general 3D artist, switched from my career and started to learn programming.
I've got a problem with c106a handout #5.
The code works, but I've still got some error log here.
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 4, Size: 4
at java.util.ArrayList.RangeCheck(ArrayList.java:547)
at java.util.ArrayList.get(ArrayList.java:322)
at UniqueNames.showUnique(UniqueNames.java:23)
at UniqueNames.main(UniqueNames.java:39)
Why does Arraylist, which can stretch its capacity on its own, still get an OutOfBoundsException?
Here's my full code:
import acm.io.*;
import acm.program.ConsoleProgram;
import acm.util.*;
import java.io.*;
import java.util.ArrayList;
import java.lang.*;
public class UniqueNames extends ConsoleProgram{
static ArrayList<String> meString = new ArrayList<String>();
static String input ;
public static void storeUnique(String input){
if (!meString.contains(input))
{
meString.add(input);
}
}
public static void showUnique(ArrayList<String> meString){
System.out.println("Unique name list contains:");
for(int i=0 ;i<= meString.size() ;i++){
System.out.println(meString.get(i));
}
}
public static void main(String[] args){
try{
InputStreamReader stream = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(stream);
while (true){
System.out.println("Enter name:");
String input = br.readLine();
if (input.equals("")) break;
storeUnique(input);
}
{showUnique(meString);}
}
catch(IOException e){
}
}
}
The following lines:
for (int i = 0; i <= meString.size(); i++) {
System.out.println(meString.get(i));
}
should be:
for (int i = 0; i < meString.size(); i++) {
System.out.println(meString.get(i));
}
This is because the index of the list starts from zero.
Index: 4, Size: 4 explains a little more. When you call get(4), an exception occurs because your list only has a size of 4. get(4) would attempt to access the 5th element in the list.
Valid elements you can access would be get(0), get(1), get(2), get(3).
You asked, "Why does Arraylist, which can stretch its capacity by its own still get an OutOfBoundsException ???"
The answer is: an ArrayList only stretches its capacity when:
You add an object to it ( .add(Object o) ).
You add the contents of another collection to it ( .addAll(Collection c) ).
You ensure its size ( .ensureCapacity(int minCapacity) ).
The trouble you're having is that you are trying to access an object in an index of the list that doesn't exist. While an ArrayList will dynamically resize when you change the contents, it won't do it when you are simply trying to access the contents.
That is the difference.
To avoid accessing an index that doesn't exist:
Take Surresh Atta's suggestion: Use i < meString.size() instead of i <= meString.size() because the index starts with 0 instead of 1.
Take Ankit's suggestion and just use the enhanced for loop: for(String str : meString).
Use the above answer, or you can use a foreach loop:
for (String str: meString) {
System.out.println(str);
}
If you are using a 2D ArrayList ,make sure you instantiate every row and every element of the corresponding row using the following code:
for(int i=0;i<n;i++)
{
p.add(new ArrayList<Integer>());
for(int j=0;j<n;j++)
{
p.get(i).add(new Integer(0));
}
}
This creates an ArrayList with i (=n) rows and each row contains an ArrayList with j (=n) number of elements.
If instantiation is not done properly it might result in an IndexOutOfBoundsException

Categories