I’m trying to read a CSV file and then shuffle the characters of the strings in the array. The CSV file contains a dictionary from english to german. This is how it looks like:
eat,essen
play,spiel
sleep,schlafen
the desired output should look something like this:
eat sesen
play lpsie
sleep fenlahsc
This is my code so far (I keep getting the error "non-static method shuffle(String) cannot be referenced from a static context"):
import java.io.FileReader;
import java.io.IOException;
import java.util.Random;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.util.*;
import java.util.ArrayList;
public class Shuffle {
public static void main(String[] args) {
String path = "/Users/SaberKlai/Documents/vokabeln.csv";
String line = "";
try {
BufferedReader br = new BufferedReader(new FileReader(path));
Shuffle s = new Shuffle();
while ((line = br.readLine()) != null) {
String[] values = line.split(",");
System.out.println(values[0] + " " + shuffle(values[1]));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void shuffle(String input){
List<Character> characters = new ArrayList<Character>();
for(char c:input.toCharArray()){
characters.add(c);
}
StringBuilder output = new StringBuilder(input.length());
while(characters.size()!=0){
int randPicker = (int)(Math.random()*characters.size());
output.append(characters.remove(randPicker));
}
System.out.println(output.toString());
}
}
>Solution :
The issue is that you are trying to call an instance method (shuffle()) from a static method (main()). You need to make shuffle() a static method.
In addition to this, you can’t do System.out.println(values[0] + " " + shuffle(values[1])), because shuffle() method returns no String, in fact it returns nothing. Hence you also need to change this piece of code as follows:
public class Shuffle {
public static void main(String[] args) {
String path = "/Users/SaberKlai/Documents/vokabeln.csv";
String line = "";
try {
BufferedReader br = new BufferedReader(new FileReader(path));
while ((line = br.readLine()) != null) {
String[] values = line.split(",");
System.out.print(values[0] + " ");
shuffle(values[1]);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void shuffle(String input){
List<Character> characters = new ArrayList<Character>();
for(char c:input.toCharArray()){
characters.add(c);
}
StringBuilder output = new StringBuilder(input.length());
while(characters.size()!=0){
int randPicker = (int)(Math.random()*characters.size());
output.append(characters.remove(randPicker));
}
System.out.println(output.toString());
}
}