Reading a text file using Java throws IOException - java
I have compiled my Java with no error , However, when I want to use the java to read the text , it shows the following error :
java countwords Chp_0001.txt <-- this is my action
Exception in thread "main" java.io.IOException: Stream closed
at java.io.BufferedReader.ensureOpen(BufferedReader.java:122)
at java.io.BufferedReader.read(BufferedReader.java:179)
at countwords.readFile_BSB(assignment.java:164)
at countwords.main(assignment.java:53)
The following is my input of Java :
import java.util.*;
import java.io.*;
class countwords {
public static String [] MWTs ={ "Hong Kong","New York",
"United Kingdom","Basic Law","People's Republic of China",
};
public static void bubble_sort_length(String [] strs){
while (true) {
int swaps = 0;
for (int i = 0 ; i<strs.length -1; i++) {
if (strs[i].length() >= strs[i+1].length())
continue ;
String tmp = strs[i];
strs[i] = strs[i+1];
strs [i+1] = tmp;
swaps++;
}
if (swaps ==0) break ;
}
}
public static void main(String[] args) throws IOException {
String txt=readFile_BSB(args [0]);
bubble_sort_length(MWTs);
txt= underscoreMWTs(txt);
for (int i = 0 ; i < MWTs.length;i++)
System.out.println(i + "-->" + MWTs[i]) ;
System.out.print (txt);
String [] words = txt.split("\\s+");
StringBuilder txt_p = new StringBuilder();
for (String w : words){
txt_p.append(sep_punct(w));
}
words = txt_p.toString().split("\\s+");
Arrays.sort (words);
String w ="";
int cnt =0;
StringBuilder all_lines = new StringBuilder();
for(int i = 0;i < words.length;i++){
if (w.equals(words[i])){
cnt++ ;
} else {
if(!w.equals("")) {
if (w.contains("_")) {
String u = de_underscore (w) ;
if(isMWT (u)) w = u ;
}
all_lines.append (addSpaces(cnt) + " " + w + "\r\n");
}
w=words[i];
cnt=1;
}
}
String [] lines = all_lines.toString().split ("\r\n");
Arrays.sort(lines);
for (int i= lines.length-1;i>= 0 ; i--) {
System.out.println(lines[i]);
}
}
public static boolean isPunct(char c){
return ",.':;\"!)?_#(#".contains(""+c);
}
public static String sep_punct( String w ) {
StringBuilder W= new StringBuilder(w);
String init_puncts = "",end_puncts="";
char c;
while (W.length() > 0) {
c =W.charAt(0);
if (!isPunct(c)) break;
W.deleteCharAt(0);
init_puncts +="" + c + " ";
}
while (W.length() > 0) {
c= W.charAt(W.length () -1);
if (!isPunct(c)) break;
W.deleteCharAt (W.length()-1);
end_puncts += "" +c+"";
}
return "" + init_puncts + W.toString() + end_puncts +"";
}
public static String underscoreMWTs(String txt){
StringBuilder TXT = new StringBuilder(txt);
for(String mwt : MWTs ) {
int pos =0 ;
while ((pos =TXT.indexOf(mwt,pos)) !=-1) {
pos += mwt.length();
}
}
return TXT.toString();
}
public static void space2underscore (StringBuilder sb, int pos, int lgth){
for (int p = pos; p < pos+lgth; p++ ){
if (sb.charAt(p) ==' ')
sb.setCharAt(p,'_');
}
}
public static String de_underscore(String w) {
StringBuilder W = new StringBuilder (w);
for (int i= 0 ; i < W.length(); i++ ) {
if ( W.charAt (i) == '_')
W.setCharAt (i ,' ');
}
return W.toString ();
}
public static boolean isMWT (String w) {
for (String t : MWTs) {
if (w.equals(t)) return true;
}
return false;
}
public static String addSpaces (int cnt) {
String s ="" + cnt;
while (s.length () <10 ) {
s=" " + s;
}
return s;
}
public static String readFile_BSB(String fn) throws IOException{
FileReader fr= new FileReader(fn);
BufferedReader r= new BufferedReader (fr);
StringBuilder s= new StringBuilder();
int c;
while ((c = r.read()) != -1) {
s.append ((char)c);
r.close();
}
return s.toString();
}
}
Please help me with the errors as I am quite hopeless at this point .
Thank You so much !
Check your loop in readFile_BSB():
BAD
while ((c = r.read()) != -1) {
s.append ((char)c);
r.close(); // Close while reading?
}
BETTER
while ((c = r.read()) != -1) {
s.append ((char)c);
}
r.close(); // Close after reading.
Why not good? Reading byte by byte is very slow, in case of Exception your streams are not closed...
Related
How do i change method from using HashMap to a normal String method
Someone, please assist to change the method 'getBabyNameFrequencies' in class 'Result' from using HarshMap to a normal String method as is in the main/feeder class 'Solution' /* * The function is expected to return a STRING. * The function accepts the following parameters: * 1. STRING names * 2. STRING synonyms */ class Solution { private Map<String, Integer> mp = new HashMap<>(); private Map<String, String> p = new HashMap<>(); public String[] getBabyNameFrequencies(String[] names, String[] synonyms) { for (String e : names) { int idx = e.indexOf("("); String name = e.substring(0, idx); int w = Integer.parseInt(e.substring(idx + 1, e.length() - 1)); mp.put(name, w); p.put(name, name); } for (String e : synonyms) { int idx = e.indexOf(","); String name1 = e.substring(1, idx); String name2 = e.substring(idx + 1, e.length() - 1); if (!mp.containsKey(name1)) { mp.put(name1, 0); } if (!mp.containsKey(name2)) { mp.put(name2, 0); } p.put(name1, name1); p.put(name2, name2); } for (String e : synonyms) { int idx = e.indexOf(","); String name1 = e.substring(1, idx); String name2 = e.substring(idx + 1, e.length() - 1); union(name1, name2); } List<String> t = new ArrayList<>(); for (Map.Entry<String, Integer> e : mp.entrySet()) { String name = e.getKey(); if (Objects.equals(name, find(name))) { t.add(name + "(" + e.getValue() + ")"); } } String[] res = new String[t.size()]; for (int i = 0; i < res.length; ++i) { res[i] = t.get(i); } return res; } private String find(String x) { if (!Objects.equals(p.get(x), x)) { p.put(x, find(p.get(x))); } return p.get(x); } private void union(String a, String b) { String pa = find(a), pb = find(b); if (Objects.equals(pa, pb)) { return; } if (pa.compareTo(pb) > 0) { mp.put(pb, mp.getOrDefault(pb, 0) + mp.getOrDefault(pa, 0)); p.put(pa, pb); } else { mp.put(pa, mp.getOrDefault(pa, 0) + mp.getOrDefault(pb, 0)); p.put(pb, pa); } } } The Solution Class/ Feeder Class with the Main method. public class Solution { public static void main(String[] args) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH"))); String names = bufferedReader.readLine(); String synonyms = bufferedReader.readLine(); String result = Result.getBabyNameFrequencies(names, synonyms); bufferedWriter.write(result); bufferedWriter.newLine(); bufferedReader.close(); bufferedWriter.close(); } }
How to input Strings into a 2D array
I have this code and I need to export the strings 'Name','Testav','HWav','Lows','grade' into a 2D array with the columns being the following respectively. I then need to export the 2D array into a csv file. Any help would be greatly appreciated. import java.util.*; import java.io.*; import java.io.PrintWriter; import java.text.*; public class ComputeGrades { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.printf("Please enter the name of the input file: "); String input_name = in.next(); System.out.printf("Please enter the name of the output CSV file: "); String csv_name = in.next(); System.out.printf("Please enter the name of the output pretty-print file: "); String pretty_name = in.next(); processGrades(input_name, csv_name, pretty_name); System.out.printf("\nExiting...\n"); } public static void processGrades (String input_name, String csv_name, String pretty_name) { PrintWriter csv = null; PrintWriter pretty = null; String[][] data = readSpreadsheet(input_name); boolean resultb = sanityCheck(data); int length = data.length; ArrayList<String> test_avg = new ArrayList<String>(); ArrayList<String> HW_avg = new ArrayList<String>(); ArrayList<String> NAME = new ArrayList<String>(); ArrayList<String> ColN = new ArrayList<String>(); ArrayList<String> Hell = new ArrayList<String>(); String[][] kill_me = new String[length][]; for(int row = 1; row<length; row++) { String name = data[row][0]; String name2 = data[row][1]; String Name = name+" "+name2; int test1 = Integer.parseInt(data[row][2]); int test2 = Integer.parseInt(data[row][3]); int test3 = Integer.parseInt(data[row][4]); int Test = (test1+test2+test3)/3; String Testav = Integer.toString(Test); int hw1 = Integer.parseInt(data[row][5]); int hw2 = Integer.parseInt(data[row][6]); int hw3 = Integer.parseInt(data[row][7]); int hw4 = Integer.parseInt(data[row][8]); int hw5 = Integer.parseInt(data[row][9]); int hw6 = Integer.parseInt(data[row][10]); int hw7 = Integer.parseInt(data[row][11]); int HW = (hw1+hw2+hw3+hw4+hw5+hw6+hw7)/7; String HWav = Integer.toString(HW); int[] trying = {Test, HW}; int low = find_min(trying); String Lows = Integer.toString(low); String grade = null; if(low>=90) { grade ="A"; } if(low < 90 && low>= 80) { grade = "B"; } if(low <80 && low>=70) { grade ="C"; } if(low<70 && low>=60) { grade="D"; } if(low<60) { grade = "F"; } test_avg.add(Testav); HW_avg.add(HWav); NAME.add(Name); Hell.add(Name); Hell.add(Testav); Hell.add(HWav); Hell.add(Lows); Hell.add(grade); } System.out.println(Hell); System.out.printf("\n"); File csvFile = new File(csv_name); try (PrintWriter csvWriter = new PrintWriter(new FileWriter(csvFile));){ Hell.stream().forEach(csvWriter::println); } catch (IOException e) { } } public static int find_min(int[] values) { int result = values[0]; for(int i = 0; i<values.length; i++) { if(values[i]<result) { result = values[i]; } } return result; } public static boolean sanityCheck(String[][] data) { if (data == null) { System.out.printf("Sanity check: nul data\n"); return false; } if(data.length<3) { System.out.printf("Sanity check: %d rows\n",data.length); return false; } int cols= data[0].length; for(int row = 0; row<data.length; row++) { int current_cols = data[row].length; if(current_cols!=cols) { System.out.printf("Sanity Check: %d columns at rows%d\n", current_cols, row); return false; } } return true; } public static String[][] readSpreadsheet(String filename) { ArrayList<String> lines = readFile(filename); if (lines == null) { return null; } int rows = lines.size(); String[][] result = new String[rows][]; for (int i = 0; i < rows; i++) { String line = lines.get(i); String[] values = line.split(","); result[i] = values; } return result; } public static ArrayList<String> readFile(String filename) { File temp = new File(filename); Scanner input_file; try { input_file = new Scanner(temp); } catch (Exception e) { System.out.printf("Failed to open file %s\n", filename); return null; } ArrayList<String> result = new ArrayList<String>(); while (input_file.hasNextLine()) { String line = input_file.nextLine(); result.add(line); } input_file.close(); return result; } } input file: First,Last,Exam1,Exam2,Final,H1,H2,H3,H4,H5,H6,H7 Ping,Milledge,43,59,68,69,62,43,60,38,37,40 Elisa,Oltz,76,94,73,100,99,100,90,97,100,92 Leonard,Havers,67,95,57,69,95,71,68,61,93,61 Setsuko,Lovera,78,100,84,89,88,92,65,85,66,97 Franklyn,Degnim,54,74,50,63,78,42,42,41,67,64 Gwyneth,Marsico,61,89,81,59,59,62,88,60,66,66 Abigail,Greep,69,99,93,94,91,85,78,91,69,71 Majorie,Granvold,78,100,100,82,96,100,89,100,100,94 Daphine,Polaco,62,82,88,81,68,89,62,73,90,62 An,Corvera,44,71,37,46,57,42,59,66,54,60 Ayanna,Pensiero,64,42,56,37,53,66,69,52,43,58 Era,Deming,98,81,100,69,65,73,77,78,73,89 Michal,Slentz,73,85,81,82,74,93,81,76,69,81 Corie,Brazen,86,99,66,100,69,97,96,100,70,84 Dona,Tufte,63,54,70,71,55,68,86,66,75,63 Juan,Rohdenburg,78,89,100,91,80,97,92,100,98,100 Orville,Samit,88,63,60,88,81,56,91,76,77,80 Ricky,Knoechel,100,100,93,81,100,90,100,92,100,84 Blythe,Threet,38,68,35,61,63,51,48,72,49,51 Sammie,Wachs,46,53,52,76,50,52,56,68,46,75 Estelle,Veazey,72,87,69,98,96,77,95,91,100,91 Agatha,Keckler,100,92,90,95,85,100,94,85,92,100 Novella,Oros,85,76,100,92,84,77,77,90,86,98 Tanya,Quinlisk,47,78,71,50,79,52,69,66,51,45 Marion,Coltrin,68,68,54,39,61,44,66,58,47,74 Helene,Karow,100,100,75,79,100,100,100,92,89,96 Shonta,Bourek,100,96,90,81,97,84,91,100,100,100 Hyon,Anglemyer,81,76,43,43,47,53,44,60,57,65 Ervin,Kenison,78,53,54,75,55,46,61,75,56,69 Renato,Urch,71,64,64,84,49,57,63,69,81,64 Mikel,Burleigh,88,100,90,100,90,91,90,80,74,74 Val,Royal,100,80,100,99,100,100,76,86,100,96 Jodie,Adolfo,94,77,59,83,67,79,87,82,82,75 Roselee,Lienhard,68,75,58,82,96,62,60,94,68,58 Austin,Holznecht,76,49,79,48,58,68,67,71,70,61 Emelia,Toney,70,95,74,90,99,68,100,66,98,98 Lucy,Rhodd,71,91,100,82,100,93,100,100,71,81 Sacha,Chee,78,71,90,82,74,64,62,87,69,84 Julio,Lackner,56,86,53,88,88,73,57,59,80,85 Salvador,Gretzner,54,83,91,66,78,67,61,84,82,6 export file(csv_name) name,exam_score,hw_score,min_score,grade Ping Milledge,56.666667,49.857143,49.857143,F Elisa Oltz,81.000000,96.857143,81.000000,B Leonard Havers,73.000000,74.000000,73.000000,C Setsuko Lovera,87.333333,83.142857,83.142857,B Franklyn Degnim,59.333333,56.714286,56.714286,F Gwyneth Marsico,77.000000,65.714286,65.714286,D Abigail Greep,87.000000,82.714286,82.714286,B Majorie Granvold,92.666667,94.428571,92.666667,A Daphine Polaco,77.333333,75.000000,75.000000,C An Corvera,50.666667,54.857143,50.666667,F Ayanna Pensiero,54.000000,54.000000,54.000000,F Era Deming,93.000000,74.857143,74.857143,C Michal Slentz,79.666667,79.428571,79.428571,C Corie Brazen,83.666667,88.000000,83.666667,B Dona Tufte,62.333333,69.142857,62.333333,D Juan Rohdenburg,89.000000,94.000000,89.000000,B Orville Samit,70.333333,78.428571,70.333333,C Ricky Knoechel,97.666667,92.428571,92.428571,A Blythe Threet,47.000000,56.428571,47.000000,F Sammie Wachs,50.333333,60.428571,50.333333,F Estelle Veazey,76.000000,92.571429,76.000000,C Agatha Keckler,94.000000,93.000000,93.000000,A Novella Oros,87.000000,86.285714,86.285714,B Tanya Quinlisk,65.333333,58.857143,58.857143,F Marion Coltrin,63.333333,55.571429,55.571429,F Helene Karow,91.666667,93.714286,91.666667,A Shonta Bourek,95.333333,93.285714,93.285714,A Hyon Anglemyer,66.666667,52.714286,52.714286,F Ervin Kenison,61.666667,62.428571,61.666667,D Renato Urch,66.333333,66.714286,66.333333,D Mikel Burleigh,92.666667,85.571429,85.571429,B Val Royal,93.333333,93.857143,93.333333,A Jodie Adolfo,76.666667,79.285714,76.666667,C Roselee Lienhard,67.000000,74.285714,67.000000,D Austin Holznecht,68.000000,63.285714,63.285714,D Emelia Toney,79.666667,88.428571,79.666667,C Lucy Rhodd,87.333333,89.571429,87.333333,B Sacha Chee,79.666667,74.571429,74.571429,C Julio Lackner,65.000000,75.714286,65.000000,D Salvador Gretzner,76.000000,71.714286,71.714286,C export file 2(pretty_name) name: exam score, hw score, min score, grade Ping Milledge: 56.67, 49.86, 49.86, F Elisa Oltz: 81.00, 96.86, 81.00, B Leonard Havers: 73.00, 74.00, 73.00, C Setsuko Lovera: 87.33, 83.14, 83.14, B Franklyn Degnim: 59.33, 56.71, 56.71, F Gwyneth Marsico: 77.00, 65.71, 65.71, D Abigail Greep: 87.00, 82.71, 82.71, B Majorie Granvold: 92.67, 94.43, 92.67, A Daphine Polaco: 77.33, 75.00, 75.00, C An Corvera: 50.67, 54.86, 50.67, F Ayanna Pensiero: 54.00, 54.00, 54.00, F Era Deming: 93.00, 74.86, 74.86, C Michal Slentz: 79.67, 79.43, 79.43, C Corie Brazen: 83.67, 88.00, 83.67, B Dona Tufte: 62.33, 69.14, 62.33, D Juan Rohdenburg: 89.00, 94.00, 89.00, B Orville Samit: 70.33, 78.43, 70.33, C Ricky Knoechel: 97.67, 92.43, 92.43, A Blythe Threet: 47.00, 56.43, 47.00, F Sammie Wachs: 50.33, 60.43, 50.33, F Estelle Veazey: 76.00, 92.57, 76.00, C Agatha Keckler: 94.00, 93.00, 93.00, A Novella Oros: 87.00, 86.29, 86.29, B Tanya Quinlisk: 65.33, 58.86, 58.86, F Marion Coltrin: 63.33, 55.57, 55.57, F Helene Karow: 91.67, 93.71, 91.67, A Shonta Bourek: 95.33, 93.29, 93.29, A Hyon Anglemyer: 66.67, 52.71, 52.71, F Ervin Kenison: 61.67, 62.43, 61.67, D Renato Urch: 66.33, 66.71, 66.33, D Mikel Burleigh: 92.67, 85.57, 85.57, B Val Royal: 93.33, 93.86, 93.33, A Jodie Adolfo: 76.67, 79.29, 76.67, C Roselee Lienhard: 67.00, 74.29, 67.00, D Austin Holznecht: 68.00, 63.29, 63.29, D Emelia Toney: 79.67, 88.43, 79.67, C Lucy Rhodd: 87.33, 89.57, 87.33, B Sacha Chee: 79.67, 74.57, 74.57, C Julio Lackner: 65.00, 75.71, 65.00, D Salvador Gretzner: 76.00, 71.71, 71.71, C
This should do it, if you have question about the code, just ask. public static void processGrades (String input_name, String csv_name, String pretty_name) { DecimalFormat decimalFormat = new DecimalFormat(".000000"); String[][] data = readSpreadsheet(input_name); String[][] result = new String[data.length][]; result[0] = new String[]{"name", "exam_score", "hw_score", "min_score", "grade"}; // Export to 2D String array for(int row = 1; row < data.length; row++) { String name = data[row][0] + " " + data[row][1]; double testAverage = average(data[row], 2, 5); double homeworkAverage = average(data[row], 5, 12); double min = Math.min(testAverage, homeworkAverage); char grade = (char) (74 - ((int) min / 10)); grade = grade > 'D' ? 'F' : grade; result[row] = new String[]{ name, decimalFormat.format(testAverage), decimalFormat.format(homeworkAverage), decimalFormat.format(min), Character.toString(grade) }; } // Export 2D array into a csv String String csv = ""; for (int y = 0; y < result.length; y++) { for (int x = 0; x < result[y].length - 1; x++) { csv += result[y][x] + ","; } csv += result[y][result[y].length - 1] + "\n"; } // Save String in file File file = new File(csv_name); try { BufferedWriter bw = new BufferedWriter(new FileWriter(file.getAbsoluteFile())); bw.write(csv); bw.close(); } catch (IOException e) { e.printStackTrace(); } } private static double average(String[] row, int fromIndex, int toIndex) { double total = 0; for (int i = fromIndex; i < toIndex; i++) { total += Integer.parseInt(row[i]); } return total / (toIndex - fromIndex); }
How to write main method for this code?
Okay following is my Simmulation.java file and I am supposed to write main method for it to work. But I have no idea how to do it. I have tried like following, but it didn't work! public static void main(String args[]) { new Simmulation(args[0]); } Any help is much appreciated. Thank you in advance This is my Simmulation.java file import java.io.File; import java.util.LinkedList; import java.util.Queue; import java.util.*; import java.util.Scanner; import java.io.*; public class Simmulation implements Operation { Queue < CashewPallet > inputQueue = new LinkedList < CashewPallet > (); Stack < CashewPallet > stBay1 = new Stack < CashewPallet > (); Stack < CashewPallet > stBay2 = new Stack < CashewPallet > (); FileOutputStream fout4; PrintWriter pw; static int tick = 0; CashewPallet c1; String temp; Scanner sc; public Simmulation(String fn) { int index = 0; String nutType = ""; int id = 0; Scanner s2; try { sc = new Scanner(new File(fn)); fout4 = new FileOutputStream("nuts.txt"); pw = new PrintWriter(fout4, true); String eol = System.getProperty("line.separator"); // Reading string line by line while (sc.hasNextLine()) { tick++; s2 = new Scanner(sc.nextLine()); if (s2.hasNext()) { while (s2.hasNext()) { String s = s2.next(); if (index == 0) { nutType = s; } else { id = Integer.parseInt(s); } index++; } System.out.println("Nuttype " + nutType + " Id is " + id + "tick " + tick); if ((nutType.equalsIgnoreCase("A") || nutType.equalsIgnoreCase("P") || nutType.equalsIgnoreCase("C") || nutType.equalsIgnoreCase("W")) && id != 0) inputQueue.add(new CashewPallet(nutType.toUpperCase(), id)); System.out.println("Size of Queue " + inputQueue.size()); int k = 0; if (!inputQueue.isEmpty()) { while (inputQueue.size() > k) { // stBay1.push(inputQueue.poll()); process(inputQueue.poll()); k++; } // System.out.println("Size of input "+inputQueue.size() +" Size of stay "+stBay1.size()); } } else { fout4.write(" ".getBytes()); } index = 0; if (!stBay2.isEmpty()) { while (!stBay2.isEmpty()) { c1 = stBay2.pop(); temp = tick + " " + c1.getNutType() + " " + c1.getId() + eol; fout4.write(temp.getBytes()); } // System.out.println("Nut final "+ stBay2.peek().getNutType()); } else { temp = tick + eol; fout4.write(temp.getBytes()); } } } catch (Exception e) { System.out.println("Exception " + e); } closeStream(); } public CashewPallet process(CashewPallet c) { // CashewPallet c=new CashewPallet(); int k = 0; // while(stBay.size()>k) // { // c=stBay.pop(); String operation = c.getNutType(); if (c.getPriority() == 1) { shelling(c); washing(c); packing(c); //stBay2.push(c); } else { switch (operation) { case "A": shelling(c); washing(c); packing(c); break; case "C": washing(c); packing(c); break; case "W": washing(c); shelling(c); packing(c); break; } } return c; } public void closeStream() { try { fout4.close(); } catch (Exception e) { } } public boolean shelling(CashewPallet c) { // for(int i=0;i<20; i++) { System.out.println("Performing Shelling for " + c.getNutType()); } return true; } public boolean washing(CashewPallet c) { // for(int i=0;i<20; i++) { System.out.println("Performing Washing for " + c.getNutType()); } return true; } public boolean packing(CashewPallet c) { // for(int i=0;i<20; i++) { System.out.println("Performing Packing for " + c.getNutType()); } stBay2.push(c); return true; }
The problem is that you are not passing any parameters to the program. So the length of the args is 0. What you can try is to check for the length of the args passed before using it. if (args.length > 0) new Simulation(args[0]); else new Simulation("Default value"); That should solve your problem.
Compile time error on online compilation?
import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; import java.io.FileNotFoundException; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.ArrayList; import java.util.StringTokenizer; public class database { String fileName; Scanner input; String[][] data; List<String> useful_list; List<String> records; ArrayList<Object> handles; public database(String fileName) { this.fileName = fileName; } public void openFile() { try { input = new Scanner(new File(fileName)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block return; } } public void readRecords() { // Read all lines (records) from the file into an ArrayList records = new ArrayList<String>(); try { while (input.hasNext()) records.add(input.nextLine()); } catch (Exception e) { // TODO: handle exception } } public void parseFields() { String delimiter = ",\n"; // Create two-dimensional array to hold data (see Deitel, p 313-315) int rows = records.size(); // #rows for array = #lines in file data = new String[rows][]; // create the rows for the array int row = 0; for (String record : records) { StringTokenizer tokens = new StringTokenizer(record, delimiter); int cols = tokens.countTokens(); data[row] = new String[cols]; // create columns for current row int col = 0; while (tokens.hasMoreTokens()) { data[row][col] = tokens.nextToken().trim(); col++; } row++; } } public static void main(String[] args) { String filename = null; String[] values = new String[4]; String input = null; BufferedReader reader = new BufferedReader(new InputStreamReader( System.in)); try { filename = reader.readLine(); input = reader.readLine(); values = input.split(","); } catch (IOException e) { // TODO Auto-generated catch block System.out.println("Invalid Input"); return; } int[] input1; input1 = new int[4]; try { for (int j = 0; j < values.length; j++) { input1[j] = Integer.parseInt(values[j]); } } catch (Exception e) { // TODO Auto-generated catch block System.out.println("Invalid Input"); return; } if (input1[0] >= 4 || input1[0] <= 0) { System.out.println("Invalid Input"); return; } database file1 = new database(filename); file1.openFile(); file1.readRecords(); file1.parseFields(); file1.search(input1[1]); if (file1.useful_list.size() == 0) { System.out.println("Data Unavailable"); return; } file1.sortarray(input1[0] - 1); int width = input1[2]; int skip = (input1[3] - 1) * width; Iterator<Object> it = file1.handles.iterator(); for (int i = 1; i <= skip; i++) { if (it.hasNext()) { it.next(); } else { System.out.println("Data Unavailable"); return; } } for (int j = 1; j <= width && it.hasNext(); j++) { String[] a = (String[]) it.next(); for (int i = 0; i < a.length; i++) if(i<a.length-1) System.out.print(a[i] + ","); else System.out.print(a[i]); System.out.println(); } } void sortarray(final int index) { handles = new ArrayList<Object>(); for (int i = 0; i < data.length; i++) handles.add(data[i]); Collections.sort(handles, new Comparator<Object>() { public int compare(Object o1, Object o2) { String[] a = (String[]) o1; String[] b = (String[]) o2; if (index == 1 || index == 0) { int left = Integer.parseInt(a[index]); int right = Integer.parseInt(b[index]); return Integer.compare(left, right); //Line 165 } else { if (a.length == 0 && b.length == 0) return 0; if (a.length == 0 && b.length != 0) return 1; if (a.length != 0 && b.length == 0) return -1; return a[index].compareTo(b[index]); } } public boolean equals(Object o) { return this == o; } }); } void search(int searchs) { useful_list = new ArrayList<String>(); for (int row = 0; row < data.length; row++) { if (Integer.parseInt(data[row][0]) == searchs) { // store in array list useful_list.add(data[row][0] + "," + data[row][1] + "," + data[row][2] + "," + data[row][3]); } } if (useful_list.size() == 0) { return; } String delimiter = ",\n"; // Create two-dimensional array to hold data (see Deitel, p 313-315) int rows = useful_list.size(); // #rows for array = #lines in file data = new String[rows][]; // create the rows for the array int row1 = 0; for (String record : useful_list) { StringTokenizer tokens = new StringTokenizer(record, delimiter); int cols = tokens.countTokens(); data[row1] = new String[cols]; // create columns for current row int col1 = 0; while (tokens.hasMoreTokens()) { data[row1][col1] = tokens.nextToken().trim(); col1++; } row1++; } } } this code is working fine on eclipse . but if i submit it for my online compilation .. it shows compile time error. error message *database.java 163 cannotfindsymbolsymbol methodcompare int int location class java.lang.Integer return Integer.compare left right ;^1error*
Integer.compare was introduced to Java in version 1.7. Chances are that the online compiler has an earlier version of the compiler
Integer.compare(int,int) was introduced in Java 1.7. I expect you are seeing that error because Java 6 or earlier is used to compile the code. The docs. themselves (linked above) show how to do it for earlier Java (you should consult them at times like this). Integer.valueOf(x).compareTo(Integer.valueOf(y))
Some error in Hangman program
I have to build a hangman program for java for a class. the problem i'm having is having the letter change once you guess a letter. all it's doing is getting an error when i guess. any help would be appreciated, thank you import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Random; public class test2 { public static void main( String[] args ) { HangmanSession hangmanSession = new HangmanSession(); hangmanSession.play(); } } class HangmanSession { private Player player; private Words secretWord; private LetterBox letterBox; private int triesNumber = 6; public HangmanSession() { player = new Player(); player.askName(); secretWord = new Words(); letterBox = new LetterBox(); } private void printState() { letterBox.print(); System.out.print( "Hidden word : " ); secretWord.print(); System.out.print( "Tries left: " + triesNumber + "<guess letter:>" ); } public void play() { boolean bool = true; while( true ) { bool = true; printState(); char ch = player.takeGuess(); if( letterBox.contains( ch ) ) { System.out.println( "Try again, you've already used the letter " + ch ); bool = false; } if( bool ) { if( secretWord.guess( ch ) ) { System.out.println( "You have found the letter " + ch ); } else { triesNumber--; } if( triesNumber < 1 ) gameOver(); if( secretWord.found() ) congratulations(); } } } public void congratulations() { System.out.println( "Congratulations " + player + ", you win!" ); System.exit( 0 ); } public void gameOver() { System.out.println( "Sorry " + player + ", this time you lose!" ); System.exit( 0 ); } } class Words { private String fv; private StringBuffer pValue; private int found = 0; { String Words[] = new String[23]; Words[0] = "carbon"; Words[1] = "dictionary"; Words[2] = "restaurant"; Words[3] = "televison"; Words[4] = "responsible"; Words[5] = "technology"; Words[6] = "computer"; Words[7] = "communicate"; Words[8] = "automobile"; Words[9] = "coffee"; Words[10] = "federation"; Words[11] = "exaggerate"; Words[12] = "cappuccino"; Words[13] = "macintosh"; Words[14] = "apple"; Words[15] = "microsoft"; Words[16] = "lighter"; Words[17] = "shark"; Words[18] = "bunker"; Words[19] = "argument"; Words[20] = "playstation"; Words[21] = "parrot"; Words[22] = "canine"; Random random = new Random(); int randomWord = random.nextInt(22); for (int i = 0; i < Words.length; i++); String[] displayLetters = new String[Words[randomWord].length()]; for (int i=0; i<displayLetters.length; i++) { displayLetters[i] = "_"; } for (int i=0; i<displayLetters.length; i++) { System.out.print(displayLetters[i]+" "); } } { } public boolean found() { System.out.println( "Letters found:" + found + "/" + fv.length() ); return ( found == fv.length() ); } public boolean guess( char c ) { int index = fv.indexOf( c ); if( index == -1 ) return false; else { found = found + findOccurances( c ); return true; } } private int findOccurances( char c ) { int idx = fv.indexOf( c ); pValue.setCharAt( idx, fv.charAt( idx ) ); int counter = 1; while( idx != -1 ) { int index = fv.indexOf( c, idx + 1 ); idx = index; if( idx != -1 ) { counter++; pValue.setCharAt( idx, fv.charAt( idx ) ); } } return counter; } public void print() { System.out.println( pValue ); } } class Player { private String name = ""; public void askName() {System.out.print( "Player, enter your name:" ); name = receiveInput(); } public char takeGuess() { return receiveInput().charAt( 0 ); } private String receiveInput() { String str = " "; BufferedReader br = new BufferedReader( new InputStreamReader( System.in ) ); try { str = br.readLine(); } catch( IOException ex ) { ex.printStackTrace(); } return str; } public String toString() { return name; } } class LetterBox { private char[] lbox = new char[24]; private int counter = 0; public boolean contains( char c ) { for( int i = 0; i < counter; i++ ) { if( lbox[i] == c ) return true; } lbox[counter] = c; counter++; return false; } public void print() { System.out.print( "\nLetterBox:" ); for( int i = 0; i < counter; i++ ) { System.out.print( lbox[i] ); } System.out.println( "" ); } } Im getting null for the hidden word: and i'm getting these errors when i try to guess a letter Exception in thread "main" java.lang.NullPointerException at Words.guess(Hangman2.java:141) at HangmanSession.play(Hangman2.java:53) at Hangman2.main(Hangman2.java:11)
Both your fv and pValue are not initialized, change your initialization block to this fv = Words[randomWord]; // assign the answer to fv pValue = new StringBuffer(fv.length()); // init the user result for (int i = 0; i < displayLetters.length; i++) { displayLetters[i] = "_"; pValue.append('_'); // Init the user result to ____ } And, get yourself a decent IDE like eclipse and try to learn how to set break point and catch exception in debugging.
I don't see where you are initializing private String fv; and the NullPointerException is caused because of that in this line int index = fv.indexOf(c); in public boolean guess(char c) of class Words. Besides that, there is a lot of stuff to be cleaned up like empty blocks { } and for (int i = 0; i < Words.length; i++) ; do nothing and could be removed.