This question already has answers here:
How to shuffle an ArrayList [duplicate]
(2 answers)
Closed 1 year ago.
i have my quizz game reading a csv file to get the questions but i dont know how to randomize them for every time start the game i dont know if its possible with the code i have and i dont want to change to sql or sqllite because i already did this way and i want to finish like that, thats my code to read the file
import android.content.Context;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
public class CsvFileReader {
public ArrayList<Question> readFile(Context ctx){
ArrayList<Question> questions = new ArrayList<>();
InputStream inputStream = ctx.getResources().openRawResource(R.raw.question);
CSVFile csvFile = new CSVFile(inputStream);
List<String[]> scoreList = csvFile.read();
for (int i=1;i<scoreList.size();i++)
{
String[] strings = scoreList.get(i);
int questionId = 0;
String question = "";
int dificulty = 0;
int correctAnswer = 0;
String answer1 = "";
String answer2 = "";
String answer3 = "";
String answer4 = "";
int length = strings.length;
if (length>0){
try {
questionId = Integer.parseInt(strings[0]);
}catch (Exception ex){
}
}
if (length>1){
question = strings[1];
}
if (length>2){
try {
dificulty = Integer.parseInt(strings[2]);
}catch (Exception ex){
}
}
if (length>3){
try {
correctAnswer = Integer.parseInt(strings[3]);
}catch (Exception ex){
}
}
if (length>4){
answer1 = strings[4];
}
if (length>5){
answer2 = strings[5];
}
if (length>6){
answer3 = strings[6];
}
if (length>7){
answer4 = strings[7];
}
Question questionData = new Question(questionId,question,dificulty,correctAnswer,answer1,answer2,answer3,answer4);
questions.add(questionData);
}
return questions;
}
}
i want every time i start the quizz need to randomize the questions and down there is the code from the file
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class CSVFile {
InputStream inputStream;
public CSVFile(InputStream inputStream){
this.inputStream = inputStream;
}
public List read(){
List resultList = new ArrayList();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
String csvLine;
while ((csvLine = reader.readLine()) != null) {
String[] row = csvLine.split(",");
resultList.add(row);
}
}
catch (IOException ex) {
throw new RuntimeException("Error reading: "+ex);
}
finally {
try {
inputStream.close();
}
catch (IOException e) {
throw new RuntimeException("Error while closing input stream: "+e);
}
}
return resultList;
}
}
if someone need more code to get in or whatever let me know i would appreciate the help.
You can use Collections.shuffle to randomize an arrayList. This function is in java.util.
Something like this:
import java.util.Collections;
...
public ArrayList<Question> readFile(Context ctx){
ArrayList<Question> questions = new ArrayList<>();
...
Collections.shuffle(questions);
return questions;
}
This will return a randomize ArrayList
Related
Every time the user logins.I'm reading till the SECOND LAST LINE OF THE FILE .I want to know what changes i need to make to the code so that i can read only till the second last line of the file.
public static boolean User(String usid) {
try {
String acc = usid;
File file = new File("C:\\Temp\\logs\\bank.log");
Scanner myReader = new Scanner(file);
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
String[] substrings = data.split("[:]");
if (substrings[5].contains(acc) && substrings[4].contains("Login Successful for user")) {
a = true;
} else {
a = false;
}
}
} catch (Exception e) {
e.printStackTrace();
}
Could anyone please guide me what changes i need to make to the above code to read till the second last line of the file.[NOTE:-The contents of this file keeps adding once the user logins or logout.]
Try this, you can modify as per your requirement
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class Test{
public static boolean User(String usid) {
boolean a=false;
String fileName = "c://lines.txt";
List<String> list = new ArrayList<>();
String acc = usid;
try (BufferedReader br = Files.newBufferedReader(Paths.get(fileName))) {
//br returns as stream and convert it into a List
list = br.lines().collect(Collectors.toList());
for(int i=0; i<list.size()-1; i++){
String data = list.get(i);
String[] substrings = data.split("[:]");
if (substrings[5].contains(acc) && substrings[4].contains("Login Successful for user")) {
a = true;
} else {
a = false;
}
}
} catch (IOException e) {
e.printStackTrace();
}
return a;
}
}
This is already answered at Link
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 5 years ago.
I have an exercise where are given a list of 850 basic words in English in the file basicWords.txt. I need to compose a text of 10000 words by randomly selecting words from the basic words list and write it to another file. I generated successfully the words, but I have a problem: I get an exception when the words are generated: ArrayIndexOutOfBoundsException at line 35. Also, how can I print the result into another text file?
I have a final solution for this:
package randomstring;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
*
* #author robi1
*/
public class RandomString {
public static void main(String[] args){
List<String> dictionary = readDictionaryFrom("basicWordsInEnglish.txt");
List<String> monkeyText = generateTextFrom(dictionary);
writeTextToFile(monkeyText, "final.txt");
String letters = "abcdefghijklmnopqrstuvwxyz ";
Object[] wrds = readFile("basicWordsInEnglish.txt");
int x = wrds.length;
String[] words = new String[x];
for(int i =0;i<x;i++){
words[i] = wrds[i].toString();
}
char[] let = letters.toCharArray();
String n ="";
Random r = new Random();
char t;
}
public static Object[] readFile(String name){
ArrayList<String> al = new ArrayList<String>();
FileInputStream fstream;
try {
fstream = new FileInputStream(name);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while((strLine=br.readLine())!=null){
if(strLine.length()>4)
al.add(strLine);
}
fstream.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Object[] array = al.toArray();
return array;
}
public static List<String> readDictionaryFrom(String path) {
try {
return Files.readAllLines(new File(path).toPath());
} catch(IOException e) {
throw new RuntimeException(e);
}
}
public RandomString(List<String> text, String path) {
try(BufferedWriter file = new BufferedWriter(new FileWriter(new File(path)))){
for(String word : text) {
file.write(word+" ");
}
} catch(IOException e) {
throw new RuntimeException(e);
}
}
public static List<String> generateTextFrom(List<String> words) {
Random generator = new Random();
List<String> result = new ArrayList<>();
for(int i = 0; i < 10000; i++) {
int random = generator.nextInt(words.size());
result.add(words.get(random));
}
return result;
}
public static void writeTextToFile(List<String> text, String path) {
try(BufferedWriter file = new BufferedWriter(new FileWriter(new File(path)))){
for(String word : text) {
file.write(word+" ");
}
} catch(IOException e) {
throw new RuntimeException(e);
}
}
}
Why do you not use collections? According to description this task is very easy especially when don't use bunch for, while loops and meaningless variables like n,t,j. etc.
public void main(String... args) {
List<String> dictionary = readDictionaryFrom("path to dictionary");
List<String> monkeyText = generateTextFrom(dictionary);
writeTextToFile(monkeyText, "path to destination file");
}
public List<String> readDictionaryFrom(String path) {
try {
return Files.readAllLines(new File(path).toPath());
} catch(IOException e) {
throw new RuntimeException(e);
}
}
public static void writeTextToFile(List<String> text, String path) {
try(BufferedWriter file = new BufferedWriter(new FileWriter(new File(path)))){
for(String word : text) {
file.write(word);
}
} catch(IOException e) {
throw new RuntimeException(e);
}
}
public static List<String> generateTextFrom(List<String> words) {
Random generator = new Random();
List<String> result = new ArrayList<>();
for(int i = 0; i < 10_000; i++) {
int random = generator.nextInt(words.size());
result.add(words.get(random));
}
return result;
}
Use the debugging feature of your favorite IDE (might be Eclipse), set an exception breakpoint on ArrayIndexOutOfBoundsException, run your program in debug mode.
When it hits the exception, Eclipse will halt your program. Look at your variable values, especially which array you are accessing and what value the index has, and why it got a value outside of the array size.
By the way, your code line if(n.length()>4){ cannot produce an ArrayIndexOutOfBoundsException, as there's no array indexing in that line.
I have 2 class files in my simple project - sorry another newbee here!
But I get a compilation error on the last part where I am trying to print the hopefully stored configuration settings from a file for my project that will be referred to throughout the project.
The file is just rows of values like this 'ButtonConfig,8,V,NULL,bunny,mpg'
I basically want to be able to used the contents of this arraylist to dynamicly set up the configuration of a Raspberry pi GPO pins i.e. for the above values button attached to GPO pin 8 will play video (V) "<..other value...>_bunny.mpg"
Any help greatly appreciated - just telling me why I can't access the getExtension method would be nice!
Contents of first java file is -
package bpunit;
public class ButtonConfig {
private String keyword;
private String gponumber;
private String buttontype;
private String language;
private String filename;
private String extension;
public String getKeyword() {
return keyword;
}
public void setKeyword(String keyword) {
this.keyword = keyword;
}
...............
public String getExtension() {
return extension;
}
public void setExtension(String extension) {
this.extension = extension;
}
}
The second contains this -
package bpunit;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Read_ini {
public void Read_ini_toObject()
{
String csvFileToRead = "configs/BPUnit.properties";
BufferedReader br = null;
String line;
String splitBy = ",";
List buttonList = new ArrayList();
try {
br = new BufferedReader(new FileReader(csvFileToRead));
while ((line = br.readLine()) != null) {
// split on comma(',')
String[] buttonconfig = line.split(splitBy);
// create button object to store values
ButtonConfig buttonObject = new ButtonConfig();
// add values from csv to car object
buttonObject.setKeyword(buttonconfig[0]);
buttonObject.setGponumber(buttonconfig[1]);
buttonObject.setButtontype(buttonconfig[2]);
buttonObject.setLanguage(buttonconfig[3]);
buttonObject.setFilename(buttonconfig[4]);
buttonObject.setExtension(buttonconfig[5]);
// adding button object to a list
buttonList.add(buttonObject);
}
// print values stored in buttonList
printButtonList(buttonList);
} catch (FileNotFoundException e) {
System.out.print(e);
} catch (IOException e) {
System.out.print(e);
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
System.out.print(e);
}
}
}
}
public void printButtonList(List buttonListToPrint) {
for (int i = 0; i < buttonListToPrint.size(); i++) {
// THE LINE BELOW FAILS - getExtension() does not exist
// and all other attempts give me pointer references
//instead of the text //
System.out.println(buttonListToPrint.get(i).getExtension());
}
}
}
You have to add the parameterized type ButtonConfig to your ArrayList. It ends up being List<ButtonConfig> instead of just List.
package bpunit;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Read_ini {
public void Read_ini_toObject()
{
String csvFileToRead = "configs/BPUnit.properties";
BufferedReader br = null;
String line;
String splitBy = ",";
List<ButtonConfig> buttonList = new ArrayList<ButtonConfig>();
try {
br = new BufferedReader(new FileReader(csvFileToRead));
while ((line = br.readLine()) != null) {
// split on comma(',')
String[] buttonconfig = line.split(splitBy);
// create button object to store values
ButtonConfig buttonObject = new ButtonConfig();
// add values from csv to car object
buttonObject.setKeyword(buttonconfig[0]);
buttonObject.setGponumber(buttonconfig[1]);
buttonObject.setButtontype(buttonconfig[2]);
buttonObject.setLanguage(buttonconfig[3]);
buttonObject.setFilename(buttonconfig[4]);
buttonObject.setExtension(buttonconfig[5]);
// adding button object to a list
buttonList.add(buttonObject);
}
// print values stored in buttonList
printButtonList(buttonList);
} catch (FileNotFoundException e) {
System.out.print(e);
} catch (IOException e) {
System.out.print(e);
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
System.out.print(e);
}
}
}
}
public void printButtonList(List<ButtonConfig> buttonListToPrint) {
for (int i = 0; i < buttonListToPrint.size(); i++) {
// THE LINE BELOW FAILS - getExtension() does not exist
// and all other attempts give me pointer references
//instead of the text //
System.out.println(buttonListToPrint.get(i).getExtension());
}
}
}
The reason why the compilation is failing is because when you add an object to the ArrayList it is upcast as an object of the class Object. Now when you extract it you simply have to typecast it back to the original type. so all you have to do is this :
public void printButtonList(List buttonListToPrint) {
for (int i = 0; i < buttonListToPrint.size(); i++) {
// THE LINE BELOW FAILS - getExtension() does not exist
// and all other attempts give me pointer references
//instead of the text
ButtonConfig buttonObject =(ButtonConfig)buttonListToPrint.get(i);
System.out.println(buttonObject.getExtension());
}
}
Or as mentioned in the comments and answers above you could use generics and create an List of type ButtonConfig
public void Read_ini_toObject()
{
String csvFileToRead = "configs/BPUnit.properties";
BufferedReader br = null;
String line;
String splitBy = ",";
List<ButtonConfig> buttonList = new ArrayList<ButtonConfig>();
and pass it in the function printButtonList
public void printButtonList(List<ButtonConfig> buttonListToPrint) {
for (int i = 0; i < buttonListToPrint.size(); i++) {
// THE LINE BELOW FAILS - getExtension() does not exist
// and all other attempts give me pointer references
//instead of the text
System.out.println(buttonListToPrint.get(i).getExtension());
}
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I have a small assignment for uni which I seem to be stuck with. The application is suppose to be a quiz program which reads questions and answers from a text files and stores them like a flash card. My problem is that my buffered reader seems to be returning the nullPointer exception when it tries to read from the file. I'm unsure why this is. I will provide all code and highlight the error in bold. After doing a bit of debugging I found that the readLine method was returning null. Any thoughts? Thanks a lot. Error is at String[] line = getLine().split(":");
text file is in the format question:answer
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class Quiz {
private ArrayList<FlashCard> flashCards;
public static void main(String[] args){
Quiz quiz1 = new Quiz();
}
public Quiz(){
FlashCardReader cardReader = new FlashCardReader();
try {
if(cardReader.isReady()==true){
flashCards = cardReader.getFlashCards();
play();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void play(){
Scanner userInput = new Scanner(System.in);
String answer = userInput.nextLine();
for(FlashCard card: flashCards){
System.out.println(card.getQuestion());
System.out.println("********************");
sleep(10000);
System.out.println("Enter your answer:");
answer = userInput.nextLine();
if(card.getAnswer() == answer){
System.out.println("Correct.");
}else{
System.out.println("Incorrect. The correct answer is " + card.getAnswer() + ".");
}
}
}
private void sleep(int x){
try {
Thread.sleep(x);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
}
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class FlashCardReader {
BufferedReader reader;
public FlashCardReader(){
try {
reader = new BufferedReader(new FileReader("Questions.txt"));
} catch (FileNotFoundException e) {
System.err.println(e.toString());
}
}
public String getLine() throws IOException{
return reader.readLine();
}
public Boolean isReady() throws IOException{
return reader.ready();
}
public ArrayList<FlashCard> getFlashCards(){
ArrayList<FlashCard> flashcards = new ArrayList<FlashCard>();
try {
for(int i = 1; i <= reader.lines().count(); i++){
**String[] line = getLine().split(":");**
System.out.println(line[0]);
flashcards.add(new FlashCard(line[0],line[1]));
}
} catch (IOException e) {
System.err.println(e);
e.printStackTrace();
}
return flashcards;
}
}
public class FlashCard {
private String question;
private String answer;
public FlashCard(String question, String answer){
this.question = question;
this.answer = answer;
}
public String getQuestion(){
return question;
}
public String getAnswer(){
return answer;
}
}
How about changing the for loop to while loop to avoid null condition. As you cannot be sure that your code starts from line one as you expect by assigning i to 1.
String lines ;
while((lines = getLine()) != null){
String[] lineArray = lines.split(":");
System.out.println(lineArray[0]);
flashcards.add(new FlashCard(lineArray[0],lineArray[1]));
}
I have a huge CSV file.I have to read it and store in a database using java.below code only read about 2000 rows from that file and store it into database.why? note the below calculation is to change the seconds to minutes with approximation.dont think a lot about that
import com.opencsv.CSVReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class ReadCSV {
public static void main(String[] args) throws SQLException{
MainController mc = new MainController();
boolean status=false;
String csvFile = "C:/Users/Thanushiya/Desktop/mobios/internship/csvfile/csvfile/Master.csv";
CSVReader reader = null;
List myList = new ArrayList();
String[] row = null;
int duration_m = 0;
try {
reader = new CSVReader (new FileReader(csvFile), ',', '\'', 17);
myList = reader.readAll();
int i=0;
for (Object object : myList) {
row = (String[]) object;
float duration_float = Float.parseFloat(row[12]) / 60 ;
float duration_mod = duration_float % 1 ;
if(Integer.parseInt(row[12]) <= 60){
duration_m = 1;
}
else{
if(duration_mod == 0 ){
duration_m = (int) duration_float;
}
else{
duration_m = ((int) duration_float) + 1;
}
}
String query = "INSERT INTO master(msisdn,serv,start,end,ringwithdurartion,duration_s,status,cid,duration_m) values ('"+row[0]+"','"+row[4]+"','"+row[8]+"','"+row[10]+"','"+row[11]+"','"+row[12]+"','"+row[13]+"','"+row[15]+"','"+duration_m+"')";
status=mc.insertData(query);
}//end for
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Done");
}
}
With readAll() you're loading (or at least trying to load) the entire file into memory at once. That will severely limit the number of lines you can read before running out of memory. As indicated on the OpenCSV homepage, there's also an iterator that reads line per line:
CSVReader reader = new CSVReader(new FileReader("C:/Users/Thanushiya/Desktop/mobios/internship/csvfile/csvfile/Master.csv"), ',', '\'', 17);
String [] nextLine;
while ((nextLine = reader.readNext()) != null) {
// put the code from your for loop here
}