Index 1 out of bounds for length 1 [duplicate] - java

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed last year.
im trying to read a csv with dummy data into java arraylists. I don't know what happened, but I get the described error message above the next day I started the program again.
Here's my Code. I hope you don't get irritated by the german variables. I think the structure is important.
package Aufgabe2;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import Aufgabe2.Models.Einlagekonto;
import Aufgabe2.Models.Girokonto;
import Aufgabe2.Models.Kunde;
public class Kundenreport {
public static void main(String[] args) throws ParseException, FileNotFoundException {
Scanner scanner = new Scanner(System.in);
List<Kunde> kunde = new ArrayList<Kunde>();
String pathKunden = "/Users/testuser/OneDrive/03_Privat/05_Code/01_Java/university/project8/src/Aufgabe2/Data/Kunden.csv";
String line = null;
try {
BufferedReader kundenReader = new BufferedReader(new FileReader(pathKunden));
kundenReader.readLine();
while ((line = kundenReader.readLine()) != null) {
String[] valuesKunden = line.split(";");
kunde.add(new Kunde(valuesKunden[0], valuesKunden[1], valuesKunden[2], valuesKunden[3]));
}
kundenReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Here is the "Kunde" (engl. Customer) Class which inherits from the abstract class "Konto"
package Aufgabe2.Models;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;
import Aufgabe2.Abstract.Konto;
public class Kunde extends Konto {
public Kunde() {
}
// Kunde ohne Konten
public Kunde(String kundenNr, String name, String vorname, String kundeSeit) {
super(kundenNr, name, vorname, kundeSeit);
}
And the "Konto" (engl. account) class possesses the attributes, abstract methods and getters/setter methods.
package Aufgabe2.Abstract;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Scanner;
import Aufgabe2.Models.Kunde;
public abstract class Konto {
public final static Date today = new Date();
public Scanner scanner = new Scanner(System.in);
public static SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy", Locale.GERMAN);
private String kundenNr, name, vorname, kundeSeit;
private double kontoStdGiro, kontoStdEinlage;
private String anlagedatum, faelligkeitsdatum;
public Konto() {
}
// Nur Kunde ohne Konten
public Konto(String kundenNr, String name, String vorname, String kundeSeit) {
this.kundenNr = kundenNr;
this.name = name;
this.vorname = vorname;
this.kundeSeit = kundeSeit;
}
I was searching for a while and thankful for every advise from you.
Thanks!
By the way, here is the folder structure of the project:
Screenshot of repository

Most languages - such as Java or Python are zero-indexed, meaning they start from 0 instead of 1 like we normally do when counting. So when accessing a particular index we have to go one less than its number, for example, if we want the second element in array arr, we would do arr[1]. So in this case an array of length one only has one index, meaning arr[0]. For further reading on zero index here's a link: https://softwareengineering.stackexchange.com/questions/110804/why-are-zero-based-arrays-the-norm

Related

ReadAllLines not working and it won't tell me why

I've finally gotten around to learning Java and I'm trying to write an interpreter for an esolang. I looked up a few tutorials and wrote this code.
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
public class NDBall {
public static Scanner scanner = new Scanner(System.in);
public static void main(String args[]) {
String input = scanner.nextLine();
Path path = Paths.get(input);
List<String> code = new ArrayList<String>();
code = Files.readAllLines(path);
}
}
However, the readAllLines function keeps giving me an error, and I don't know why. It won't tell me what the error is, and everything else seems fine. I'm doing it exactly as the tutorials I looked up told me.
Is there some mistake I made?
The below code will work for you. have hard coded the path so escape characters are taken care of:
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class Solution {
public static Scanner scanner = new Scanner(System.in);
public static void main(String args[]) {
String input = scanner.nextLine();
Path path = Paths.get("C:\\Users\\xyz\\Desktop\\imp.txt");
List<String> code = new ArrayList<String>();
try {
code = Files.readAllLines(path, StandardCharsets.UTF_8);
code.stream().forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
}
}

save single string to array separate by multi space in file text java

I'm a java beginner and I'm doing a small project about dictionary, now I want to save word and translate mean in file, because my native language often have space like chicken will be con gà so, I must use other way, not by space, but I really don't know how to do that, a word and it translation in one line, separate by "tab", mean multi space like chicken con gà now I want to get 2 words and store it in my array of Words which I created before, so I want to do something like
w1=word1inline;
w2=word2inline;
Word(word1inline,word2inline);(this is a member of array);
please help me, thanks a lot, I just know how to read line from file text, and use split to get word but I am not sure how to read by multi space.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class docfile {
public static void main(String[] args)
{
String readLine;
ArrayList<String>str=new ArrayList<>(String);
try {
File file = new File("text.txt");
BufferedReader b = new BufferedReader(new FileReader(file));
while ((readLine = b.readLine()) != null) {
str.add()=readLine.split(" ");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
If you stick to using tabs as a separator, this should work:
package Application;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class Application {
public static void main(String[] args) {
String line;
ArrayList<String> str = new ArrayList<>();
try {
File file = new File("text.txt");
BufferedReader b = new BufferedReader(new FileReader(file));
while ((line = b.readLine()) != null) {
for (String s : line.split("\t")) {
str.add(s);
}
}
str.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Why not just use a properties file?
dict.properties:
chicken=con gá
Dict.java:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Properties;
public class Dict {
public static void main(String[] args) throws IOException {
Properties dict = new Properties();
dict.load(Files.newBufferedReader(Paths.get("dict.properties")));
System.out.println(dict.getProperty("chicken"));
}
}
Output:
con gá
If your line is like this chicken con gà you can use indexof() method to find the first space in the string.
Then you can substring each word by using substring() method.
readLine = b.readLine();
ArrayList<String>str=new ArrayList<>();
int i = readLine.indexOf(' ');
String firstWord = readLine.substring(0, i);
String secondWord = readLine.substring(i+1, readLine.length());
str.add(firstWord);
str.add(secondWord);

"InputMismatchException" error, counting lines in a file

How can I count the number of lines in a file?
Below is the code I have written, but with an exception.
import java.io.File;
import java.net.URI;
import java.util.Scanner;
import java.io.FileNotFoundException;
import java.util.InputMismatchException;
public class Main {
public static void main(String[] args)throws Exception {
String[] MovieList = new String[25];
File MovieFile= new File("TheMovieList.txt");
Scanner ms = new Scanner(MovieFile);
while(true){
int i= ms.nextInt();
System.out.println();
}
}
}
And I had
Exception in thread "main" java.util.InputMismatchException
What's wrong, and how can I fix this?
You can check, that the input can be interpreted as an int value:
...
if (ms.hasNextInt()) {
int i= ms.nextInt();
...
}
To count the lines in the file you can do this.
import java.io.File;
import java.net.URI;
import java.util.Scanner;
import java.io.FileNotFoundException;
import java.util.InputMismatchException;
public class Main {
public static void main(String[] args)throws Exception {
File MovieFile= new File("TheMovieList.txt");
Scanner ms = new Scanner(MovieFile);
int count = 0;
while (ms.hasNextLine()) {
count++;
ms.nextLine();
}
System.out.println("Number of lines in the file is " + count);
}
}

How Do I Fix My Super Statements?

I put my super statements in the correct format, yet my only error is that it states that the constructor object in class java.lang.object can't be applied to given types for this part of the code:
super (openFile (filename));
Here is my current code now:
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Vector;import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
public class Buffin
{
private static boolean temp;
/////////////////////////////////
private boolean isKeyboard;
/** Connect to the disk file with the given name. If this
* cannot be done, connect to the keyboard instead. */
public Buffin (String filename)
{ super (openFile (filename));
isKeyboard = temp;
} //======================
private static Reader openFile (String filename)
{ try
{ temp = false;
return new FileReader (filename); // IOException here
}catch (IOException e)
{ temp = true;
return new InputStreamReader (System.in);
}
} //======================
/** Read one line from the file and return it.
* Return null if at the end of the file. */
public String readLine()
{ if (isKeyboard)
{ System.out.print (" input> ");
System.out.flush(); // flush the output buffer
}
try
{ return super.readLine(); // in BufferedReader
}catch (IOException e)
{ System.out.println ("Cannot read from the file");
return null;
}
} //============
}[/code]
Your class extends only the Object class, and it doesn't have a method or constructor called openFile. You would be fine if you remove the super call altogether.
At the moment, your class Buffin does not specify a super class; that means it has one super class, and that is java.lang.Object. There is no constructor that takes a Reader in java.lang.Object.
You could store a Reader as a field in your Buffin class, or you might extend a super class that accepts one in the constructor.
Super involves the constructor of the superclass, I see that the Class Buffin inherits no class. As #Sotirios Delimanolis said, no constructor accepting Reader in Object class.

Set textfile content as a array

Hi, I am totally new in java.
This is my java code:
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.BufferedReader;
public class readw {
public static void main(String[] args) throws IOException {
List<String> lines = new ArrayList<String>();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("C:\\run\\input.txt"));
String line = null;
while ((line = reader.readLine()) != null) {
lines.add(line);
}
} finally {
reader.close();
}
String[] array = lines.toArray();
}
}
When I am trying to compile it I got this type of error:
line 8: can not find symbol List (L)and ArrayList(A)
I am trying to get content of my text file and want to set in to as a array.
Add
import java.util.ArrayList;
import java.util.List;
yes its work now i want to see the array result. how?
With
System.out.println(lines);
You need to import all the classes you use.
import java.util.ArrayList;
import java.util.List;

Categories

Resources