Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have this class who is supposed open a file with a nr of questions in it with a nr of answer.
The problem is when it get's in that for to write in the ArrayList. I have tried all type of ArrayLists,LinkedLists, even vectors.
The first parts of the file, like the question and nr of answer, it takes it without any problem. But when i want to store those answers in a list so i can save that list in an object it won't work.
If anyone could help with this or knows a better method so save an unknown nr of string into an object list it would be epic.
The file format is:
A question,3,yes,no,maybe
Another question,4,yes,maybe,no,why not
my class:
public class GetSurvey {
public static String intrebare;
static int raspunsuri;
public static int i = 1;
static String holder;
//static String[] rasp = new String[250];
static List<String> rasp = new LinkedList<String>();
public static SurveyClass[] obj = new SurveyClass[250];
public static void loadSurvey()
{
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)+File.separator+"Survey.dat");
if(!file.exists()){
try {
file.createNewFile();
}
catch (IOException e) {
e.printStackTrace();
}
}
if(file.exists()){
try {
Scanner read = new Scanner(file);
read.useDelimiter(",");
while (read.hasNext())
{
intrebare = read.next();
String raspunsuri1 = read.next();
//Log.w("Date",String.valueOf(raspunsuri));
//obj[i].setNrRasp(raspunsuri);
for(int j = 0;j < 3;j++)
{
Log.w("Date",String.valueOf(j));
rasp.add(j,read.next());
}
String[] stringArr = rasp.toArray(new String[rasp.size()]);
Log.w("Date",stringArr[i]);
//obj[i].setRaspunsuri(rasp);
rasp.clear();
i++;
}
}
catch (IOException e) {
e.printStackTrace();
}
}
}
You're using read.next() 3 times inside your loop, so that means that you get past the end of the input, hence NoSuchElementException.
Use it only once and assign it to a local variable inside the loop, so you can use that value whenever you need it again later in the loop.
I'd suggest you should perform only one read.next() inside your while(read.hasNext()) Loop . Analyse the read element, perform the neccessary task and rerun the loop until while(read.hasNext()) fails. This way you can be sure you'll never perform a read beyond the size of your List.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
What I am working on is reading in a file and passing it to an ArrayList which I have already done with this:
public ArrayList readInPhrase() {
String fileName = "wholephrase.txt";
ArrayList<String> wholePhrase = new ArrayList<String>();
try {
//creates fileReader object
FileReader inputFile = new FileReader(fileName);
//create an instance of BufferedReader
BufferedReader bufferReader = new BufferedReader(inputFile);
//variable to hold lines in the file
String line;
//read file line by line and add to the wholePhrase array
while ((line = bufferReader.readLine()) != null) {
wholePhrase.add(line);
}//end of while
//close buffer reader
bufferReader.close();
}//end of try
catch(FileNotFoundException ex) {
JOptionPane.showMessageDialog(null, "Unable to open file '" +
fileName + " ' ", "Error",
JOptionPane.INFORMATION_MESSAGE, null);
}//end of file not found catch
catch(Exception ex) {
JOptionPane.showMessageDialog(null, "Error while reading in file '"
+ fileName + " ' ", "Error",
JOptionPane.INFORMATION_MESSAGE, null);
}//end of read in error
return wholePhrase;
}//end of readInPhrase
The problem that I am now having is that I would like to go through this ArrayList and randomly select one phrase from it to eventually append asterisk's
to part of the phrase that is selected. I have tried a variety of different ways to do this.
This is the last attempt that I have tried:
public String getPhrase(ArrayList<String> wholePhrase) {
Random random = new Random();
//get random phrase
int index = random.nextInt(wholePhrase.size());
String phrase = wholePhrase.get(index);
return phrase;
}//end of getPhrase
From the comments on the question, you say you're calling getPhrase like this:
HangmanPhrase.getPhrase()
... which results in the error
method getPhrase in class HangmanPhrase cannot be applied to given types;
required: ArrayList<String> found: no arguments reason:
actual and formal argument lists differ in length
The reason for this is that getPhrase takes an ArrayList<String> as an argument:
public String getPhrase(ArrayList<String> wholePhrase) {
You need to pass an ArrayList to the method getPhrase like so:
ArrayList<String> myListOfStrings = new ArrayList<String>();
// do stuff with myListOfStrings
getPhrase(myListOfStrings);
Also, since getPhrase is an instance method, not a static method, you cannot call it via HangmanPhrase.getPhrase. You need to create an instance of HangmanPhrase and call the method from that instance.
two issues as far as I can see.
Return statements in Java follow 'return variable name;' rather than a method type call.
You should be getting the array list using your random number subtract one, as indexes start at zero.
Then just do getPhrase(readInPhrase()). The compiler will call getPhrase(), and then evaulate readInPhrase() with the stack trace return point at getPhrase(...). This will return the ArrayList (which, by the way, needs to be type-parameterized with <String>). Then, getPhrase() is called with the ArrayList as the parameter, and then you get the phrase, and then there was much rejoicing.
Also, readInPhrase() needs to be returning an ArrayList<String> (in Java 1.5+)
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 7 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
I am trying to create a vector method called readfromfile which would potentially read the input from a different text file. Why does it give an error?
Edit: Thanks for the help, I have edited the code and it works!
Looks like I was confusing parameters and methods! :P
Thanks guys :D
package cas.lab1.firsteclipsePackage;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.Vector;
public class FirstEclipseClass {
public static void main(String[] args) {
Vector input = new Vector();
input.add("A");
input.add("B");
input.add("C");
input.add("D");
printVectorElements(input, 3);
Vector<String> results = readFromFile();
}
public static void printVectorElements(Vector input, int count) {
for (int i = 0; i < count; i++) {
System.out.println(input.get(i));
}
}
public static Vector<String> readFromFile(){ //yeah I did confuse methods and parameters
Vector<String> result = new Vector<String>();
try{
File f = new File("input.txt");
Scanner s = new Scanner(f);
while(s.hasNextLine()) {
int i = s.nextInt();
if(i % 2 == 0)
result.add("Even");
else
result.add("Odd");
System.out.println(i);
}
s.close();
}
catch(FileNotFoundException e){
e.printStackTrace();
}
return result;
}
}
I guess that you are confused here. From your method call, I see that you don't need to pass any parameters, and instead want a Vector back. So I suggest you to change this line:
public static readFromFile(Vector<String> results){
To this line:
public static Vector<String> readFromFile(){
First thing: you didn't specified the return type. You should have :
public static Vector<String> readFromFile()
if you do not need any parameters in the function.
Second, for future, you cannot have this same name in the function and as a function parameter
I am reading in data from a text file into an ArrayList and then trying to search for a particular string in that ArrayList (the second method).
I believe that I am correctly reading in the data however am struggling to write methods to implement on the ArrayList once it has been filled. For instance, in the checking method below, it is returning a false when I am certain the input String is in the data structure.
I recognize this is likely a problem with my variable scope or how my methods are interacting with each other (i.e, the arraylist is not actually filled with the data when I am checking it).
Any help would be much appreciated - thanks
import java.util.*;
import java.io.*;
public class Word {
ArrayList<String> diclist = new ArrayList<String>();
private void readIn() throws FileNotFoundException {
File file = new File("filepath");
Scanner s = new Scanner(file);
s.useDelimiter("\n");
while (s.hasNextLine()) {
diclist.add(s.nextLine());
}
s.close();
}
public boolean checkIn(String z) {//Check if input string z is in diclist
for (int i = 0; i < diclist.size(); i++) {
if (diclist.get(i).equals(z)) {return true;}
}
return false;
}
}
There are no obvious problems in the code you posted so far. After calling readIn, if the file exists, readable and not empty, the list should get populated. I suggest running it through a debugger.
Note that the checkIn method can be vastly simplified to this:
return diclist.contains(z);
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
My code compiles, but I get this error at runtime:
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 5
at staffstore.writestaff(staffstore.java:16)
at addStaffGUI$2.actionPerformed(addStaffGUI.java:89)
This is the part of code I believe to be causing the problem:
JButton submit = new JButton("Submit");
submit.setBounds(145,470,100,20);
panel2.add(submit);
submit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
stfname =(stfnametb.getText());
stlname =(stlnametb.getText());
staddress2 =(staddresstb.getText());
stphone2 =(stphonetb.getText());
try {
staffstore.writestaff();
} catch (IOException e1) {
e1.printStackTrace();
}
third.dispose();
}
});
This is line 9-19 of StaffStore.java
String[] stlist = new String[5];
/*stlist[0] = addStudentGUI.fname;
stlist[1] = addStudentGUI.lname;
stlist[2] = addStudentGUI.sgrade;
stlist[3] = addStudentGUI.saddress;
stlist[4] = addStudentGUI.sphone;*/
stlist[5] = addStaffGUI.stfname;
stlist[6] = addStaffGUI.stlname;
stlist[7] = addStaffGUI.staddress2;
stlist[8] = addStaffGUI.stphone2;
An array of size n can only have an index position up to size n-1. The highest such index for an array of size 5 is 4.
That said, these four declarations are illegal:
stlist[5] = addStaffGUI.stfname;
stlist[6] = addStaffGUI.stlname;
stlist[7] = addStaffGUI.staddress2;
stlist[8] = addStaffGUI.stphone2;
I'm not entirely sure what your motiviation is here, but you need to get those four values in bounds.
stlist[0] = addStaffGUI.stfname;
stlist[1] = addStaffGUI.stlname;
stlist[2] = addStaffGUI.staddress2;
stlist[3] = addStaffGUI.stphone2;
Since you've also got other values commented out, it could be a simple matter of increasing the size of your array, too:
String[] stlist = new String[9];
...but then you have to be sure that you don't try to invoke any methods on any of the first five entries in the array.
You've got an array that holds 5 items and you're trying to get the value in the 6th spot. Don't do that.
String[] stlist = new String[5];
stlist[5] = addStaffGUI.stfname;
Also you're trying to hold different information in a single array, something that is a poor and brittle design. Instead create an array or better, an ArrayList of Staff items.
// declared as a field of the class:
private List<Staff> staffList = new ArrayList<>();
// elsewhere
submit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String stfname = stfnametb.getText();
String stlname = stlnametb.getText();
String staddress2 = staddresstb.getText();
String stphone2 = stphonetb.getText();
// use information obtained to create a Staff object
Staff staff = new Staff(stfname, stlname, staddress2, stphone2);
// maybe done here, maybe in staffStore
staffList.add(staff);
try {
// pass the Staff object into this method
staffstore.writestaff(staff);
} catch (IOException e1) {
e1.printStackTrace();
}
third.dispose();
}
});
The most important lessons to gain from this experience are:
Just because code compiles does not mean that it is correct.
The Exception stacktrace often contains key information that will tell you exactly what is wrong and where. Read it critically and look carefully at the lines it indicates to you.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I need to write a method that reads the supplied filename and returns an array of doubles read from the file.
It can be assumed that the file only contains numbers in a single column, one number per line. If the file cannot be read or is not in the proper format it is OK to just return null.
How would one go about attempting this?
This is my attempt:
public static double[] fileRead(String filename) {
double[] array = new double();
// get some sort of reader here
return array;
}
I dont know how to go on from here
Create an ArrayList and go on reading the file line by line. Convert the line into Double value and add it in to the ArrayList. If you couldn't read the file for any reason, return null from catch block.
public static Double[] fileRead(String filename) {
List<Double> list= new ArrayList<Double>();
BufferedReader br = new BufferedReader(new FileReader(fileName));
try {
String line = br.readLine();
while (line != null) {
list.add(Double.parseDouble(line));
line = br.readLine();
}
return list.toArray(new double[list.size()]);
} catch(Exception e){
return null;
}finally {
br.close();
}
}