Some error in Hangman program - java

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.

Related

Trouble receiving images from an 8 modem server

I have implemented this java app communicating with a remote 8 modem server and when I request for an image from a security camera (error free or not) the outcome is a 1 byte image (basically a small white square). Can you help me find the error?
Here is my code:
import java.io.*;
import java.util.Scanner;
import ithakimodem.Modem;
public class g {
private static Scanner scanner = new Scanner(System.in);
private static String EchoCode = "E3369";
private static String noImageErrorscode = "M2269";
private static String imageErrorsCode = "G6637";
private static String GPS_Code = "P7302";
private static String ACK_Code = "Q2591";
private static String NACK_Code = "R4510";
public static void main(String[] args) throws IOException, InterruptedException {
int timeout = 2000;
int speed = 80000;
Modem modem = new Modem(speed);
modem.setTimeout(timeout);
modem.write("ATD2310ITHAKI\r".getBytes());
getConsole(modem);
modem.write(("test\r").getBytes());
getConsole(modem);
while (true) {
System.out.println("\nChoose one of the options below :");
System.out.print("Option 0: Exit\n" + "Option 1: Echo packages\n" + "Option 2: Image with no errors\n" + "Option 3: Image with errors\n" + "Option 4: Tracks of GPS\n"
+ "Option 5: ARQ\n" );
System.out.print("Insert option : ");
int option = scanner.nextInt();
System.out.println("");
switch (option) {
case 0: {
// Exit
System.out.println("\nExiting...Goodbye stranger");
modem.close();
scanner.close();
return;
}
case 1: {
// Echo
getEcho(modem, EchoCode);
break;
}
case 2: {
// Image with no errors
getImage(modem, noImageErrorscode, "no_error_image.jpg");
break;
}
case 3: {
// Image with errors
getImage(modem, imageErrorsCode, "image_with_errors.jpg");
}
case 4: {
// GPS
getGPS(modem, GPS_Code);
break;
}
case 5: {
// ARQ
getARQ(modem, ACK_Code, NACK_Code);
break;
}
default:
System.out.println("Try again please\n");
}
}
}
public static String getConsole(Modem modem) {
int l;
StringBuilder stringBuilder= new StringBuilder();
String string = null;
while (true) {
try {
l = modem.read();
if (l == -1) {
break;
}
System.out.print((char) l);
stringBuilder.append((char) l);
string = stringBuilder.toString();
} catch (Exception exc) {
break;
}
}
System.out.println("");
return string;
}
private static void getImage(Modem modem, String password, String fileName) throws IOException {
int l;
boolean flag;
FileOutputStream writer = new FileOutputStream(fileName, false);
flag = modem.write((password + "\r").getBytes());
System.out.println("\nReceiving " + fileName + "...");
if (!flag) {
System.out.println("Code error or end of connection");
writer.close();
return;
}
while (true) {
try {
l = modem.read();
writer.write((char) l);
writer.flush();
if (l == -1) {
System.out.println("END");
break;
}
}
catch (Exception exc) {
break;
}
}
writer.close();
}
private static void getGPS(Modem modem, String password) throws IOException {
int rows = 99;
String Rcode = "";
Rcode = password + "R=10200" + rows;
System.out.println("Executing R parameter = " + Rcode + " (XPPPPLL)");
modem.write((Rcode + "\r").getBytes());
String stringConsole = getConsole(modem);
if (stringConsole == null) {
System.out.println("Code error or end of connection");
return;
}
String[] stringRows = stringConsole.split("\r\n");
if (stringRows[0].equals("n.a")) {
System.out.println("Error : Packages not received");
return;
}
System.out.println("**TRACES**\n");
float l1 = 0, l2 = 0;
int difference = 8;
difference *= 100 / 60;
int traceNumber = 7;
String[] traces = new String[traceNumber + 1];
int tracesCounter = 0, flag = 0;
for (int i = 0; i < rows; i++) {
if (stringRows[i].startsWith("$GPGGA")) {
if (flag == 0) {
String str = stringRows[i].split(",")[1];
l1 = Integer.valueOf(str.substring(0, 6)) * 100 / 60;
flag = 1;
}
String str = stringRows[i].split(",")[1];
l2 = Integer.valueOf(str.substring(0, 6)) * 100 / 60;
if (Math.abs(l2 - l1) >= difference) {
traces[tracesCounter] = stringRows[i];
if (tracesCounter == traceNumber)
break;
tracesCounter++;
l1 = l2;
}
}
}
for (int i = 0; i < traceNumber; i++) {
System.out.println(traces[i]);
}
String w = "", T_cd_fnl = password + "T=";
int p = 1;
System.out.println();
for (int i = 0; i < traceNumber; i++) {
String[] strSplit = traces[i].split(",");
System.out.print("T parameter = ");
String str1 = strSplit[4].substring(1, 3);
String str2 = strSplit[4].substring(3, 5);
String str3= String.valueOf(Integer.parseInt(strSplit[4].substring(6, 10)) * 60 / 100).substring(0, 2);
String str4= strSplit[2].substring(0, 2);
String str5= strSplit[2].substring(2, 4);
String str6= String.valueOf(Integer.parseInt(strSplit[2].substring(5, 9)) * 60 / 100).substring(0, 2);
w = str1 + str2 + str3 + str4 + str5 + str6 + "T";
p = p + 5;
System.out.println(w);
T_cd_fnl = T_cd_fnl + w + "=";
}
T_cd_fnl = T_cd_fnl.substring(0, T_cd_fnl.length() - 2);
System.out.println("\nSending code: " + T_cd_fnl);
getImage(modem, T_cd_fnl, "traces GPS.jpg");
}
private static void getEcho(Modem modem, String strl) throws InterruptedException, IOException {
FileOutputStream echo_time_writer = new FileOutputStream("echoTimes.txt", false);
FileOutputStream echo_counter_writer = new FileOutputStream("echoCounter.txt", false);
int h;
int runtime = 5, packetCounter = 0;
String str = "";
System.out.println("\nRuntime (mins) = " + runtime + "\n");
long start_time = System.currentTimeMillis();
long stop_time = start_time + 60 * 1000 * runtime;
long send_time = 0, receiveTime = 0;
String time = "", ClockTime = "";
echo_time_writer.write("Clock Time\tSystem Time\r\n".getBytes());
while (System.currentTimeMillis() <= stop_time) {
packetCounter++;
send_time = System.currentTimeMillis();
modem.write((strl + "\r").getBytes());
while (true) {
try {
h = modem.read();
System.out.print((char) h);
str += (char) h;
if ( h== -1) {
System.out.println("\nCode error or end of connection");
return;
}
if (str.endsWith("PSTOP")) {
receiveTime = System.currentTimeMillis();
ClockTime = str.substring(18, 26) + "\t";
time = String.valueOf((receiveTime - send_time) + "\r\n");
echo_time_writer.write(ClockTime.getBytes());
echo_time_writer.write(time.getBytes());
echo_time_writer.flush();
str = "";
break;
}
} catch (Exception e) {
break;
}
}
System.out.println("");
}
echo_counter_writer.write(("\r\nRuntime: " + String.valueOf(runtime)).getBytes());
echo_counter_writer.write(("\r\nPackets Received: " + String.valueOf(packetCounter)).getBytes());
echo_counter_writer.close();
echo_time_writer.close();
}
private static void getARQ(Modem modem, String strl, String nack_code) throws IOException, InterruptedException {
FileOutputStream arq_time_writer = new FileOutputStream("ARQtimes.txt", false);
FileOutputStream arq_counter_writer = new FileOutputStream("ARQcounter.txt", false);
int runtime = 5;
int xor = 1;
int f = 1;
int m;
int packageNumber = 0;
int iterationNumber = 0;
int[] nack_times_counter = new int[15];
int nack_to_package = 0;
String time = "", clock_time = "", s = "";
long start_time = System.currentTimeMillis();
long stop_time = start_time + 60 * 1000 * runtime;
long send_time = 0, receive_time = 0;
System.out.printf("Runtime (mins) = " + runtime + "\n");
arq_time_writer.write("Clock Time\tSystem Time\tPacket Resends\r\n".getBytes());
while (System.currentTimeMillis() <= stop_time) {
if (xor == f) {
packageNumber++;
nack_times_counter[nack_to_package]++;
nack_to_package = 0;
send_time = System.currentTimeMillis();
modem.write((strl + "\r").getBytes());
} else {
iterationNumber++;
nack_to_package++;
modem.write((nack_code + "\r").getBytes());
}
while (true) {
try {
m = modem.read();
System.out.print((char) m);
s += (char) m;
if (m == -1) {
System.out.println("\nCode error or end of connection");
return;
}
if (s.endsWith("PSTOP")) {
receive_time = System.currentTimeMillis();
break;
}
} catch (Exception e) {
break;
}
}
System.out.println("");
String[] string = s.split("<");
string = string[1].split(">");
f = Integer.parseInt(string[1].substring(1, 4));
xor = string[0].charAt(0) ^ string[0].charAt(1);
for (int i = 2; i < 16; i++) {
xor = xor ^ string[0].charAt(i);
}
if (xor == f) {
System.out.println("Packet ok");
receive_time = System.currentTimeMillis();
time = String.valueOf((receive_time - send_time) + "\t");
clock_time = s.substring(18, 26) + "\t";
arq_time_writer.write(clock_time.getBytes());
arq_time_writer.write(time.getBytes());
arq_time_writer.write((String.valueOf(nack_to_package) + "\r\n").getBytes());
arq_time_writer.flush();
} else {
xor = 0;
}
s = "";
}
arq_counter_writer.write(("\r\nRuntime: " + String.valueOf(runtime)).getBytes());
arq_counter_writer.write("\r\nPackets Received (ACK): ".getBytes());
arq_counter_writer.write(String.valueOf(packageNumber).getBytes());
arq_counter_writer.write("\r\nPackets Resent (NACK): ".getBytes());
arq_counter_writer.write(String.valueOf(iterationNumber).getBytes());
arq_counter_writer.write("\r\nNACK Time Details".getBytes());
for (int i = 0; i < nack_times_counter.length; i++) {
arq_counter_writer.write(("\r\n" + i + ":\t" + nack_times_counter[i]).getBytes());
}
arq_counter_writer.close();
arq_counter_writer.close();
System.out.println("Packets Received: " + packageNumber);
System.out.println("Packets Resent: " + iterationNumber);
System.out.println("\n\nFile arqTimes.txt is created.");
System.out.println("File arqCounter.txt is created.");
}
}
I know the problem is most probably in the getImage() function but I haven't figured it out yet.

Is it possible to use other class variable in other class at #Override Java

I was wondering is there a way to use other class variable in #Override?
Here is my first class. I've tried to use setters & getters, but still receiving an error:
public class Darbuotojas {
String dVardas;
String dPavarde;
int dAmzius;
int dPatirtis;
Programuotojas programuotojas = new Programuotojas();
String check = programuotojas.getDarboKalba();
Darbuotojas() { }
public Darbuotojas(String dVardas, String dPavarde, int dAmzius, int dPatirtis) {
this.dVardas = dVardas;
this.dPavarde = dPavarde;
this.dAmzius = dAmzius;
this.dPatirtis = dPatirtis;
}
#Override
public String toString() {
return dVardas + " " + dPavarde + " " + dAmzius + " " + dPatirtis + " " + check;
}}
And here is my another class:
public class Programuotojas extends Darbuotojas {
Programuotojas(){}
public String getDarboKalba() {
return darboKalba;
}
public void setDarboKalba(String darboKalba) {
this.darboKalba = darboKalba;
}
public String darboKalba;
public Programuotojas(String dVardas, String dPavarde, int dAmzius, int dPatirtis, String darboKalba) {
super(dVardas, dPavarde, dAmzius, dPatirtis);
this.darboKalba = darboKalba;
}
As I see I formulated bad and not understandable question for you guys. I will try to explain. I have father class Darbuotojas with 4 parameters, in subclass Programuotojas I add one more parameter - darboKalba. So what I want from Override to return these 4 paremeters from Darbuotojas + one from Programuotojas.
// Darbuotoju valdymas prasideda //
public void darbuotojuVald() {
System.out.println("---- Darbuotoju valdymas ----");
System.out.println("[1] Prideti nauja darbuotoja");
System.out.println("[2] Pasalinti darbuotoja");
System.out.println("[3] Atnaujinti darbuotoja");
System.out.println("[4] Pamatyti darbuotoju sarasa");
System.out.println("[5] Gauti informacija apie pasirinkta darbuotoja");
Scanner SI = new Scanner(System.in);
int vartotojoIvestis = Integer.parseInt(SI.nextLine());
if (vartotojoIvestis == 1) {
System.out.println("---- Prideti nauja darbuotoja ----");
System.out.println("[1] Programuotoja");
System.out.println("[2] kita");
int vartotojoIvestis2 = Integer.parseInt(SI.nextLine());
if (vartotojoIvestis2 == 1) {
pridetiDarbuotojaProgramuotoja();
} else {
System.out.println("In progress....");
}
} else if (vartotojoIvestis == 4) {
bendrasDarbuotojuSarasas();
}
}
// Programuotojo pridejimas prasideda //
private void pridetiDarbuotojaProgramuotoja() {
System.out.println("---- Pridedamas naujas programuotojas ----");
System.out.println("Iveskite:");
System.out.println("Varda, pavarde, amziu, patirti, programavimo kalba");
Scanner SI = new Scanner(System.in);
String[] iveda = SI.nextLine().split(" ");
programuotojas.add(new Programuotojas(iveda[0], iveda[1], Integer.parseInt(iveda[2]), Integer.parseInt(iveda[3]), iveda[4]));
System.out.println("---- Sekmingai pridetas naujas darbuotojas ----");
System.out.println("Vardas: " + iveda[0]
+ ",pavarde: " + iveda[1]
+ ",amzius: " + iveda[2]
+ ",patirtis: " + iveda[3]
+ ",programavimo kalba: " + iveda[4]);
darbuotojuSarasas.clear();
darbuotojuSarasas.addAll(programuotojas);
darbuotojuVald();
}
private void bendrasDarbuotojuSarasas() {
System.out.println("---- Visas darbuotoju sarasas ----");
for(int i = 0; i < darbuotojuSarasas.size(); i++) {
System.out.println("ID " + i + " " + darbuotojuSarasas.get(i));
}
darbuotojuVald();
}
Reflection can be tricky, and I can't guarantee it'll work for all circumstances. This worked well enough for me.
package quicktest;
import java.lang.reflect.Field;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* #author Brenden
*/
public class FieldDumpTest {
public static void main( String[] args ) {
System.out.println( new FieldDump3() );
}
public final String topTestString = "This is a test.";
protected int topInt = 11;
float topFloat = 123.456f;
private short topShort = Short.MAX_VALUE;
#Override
public String toString() {
StringBuilder str = new StringBuilder();
Class<?> type = this.getClass();
do {
str.append( type.getName() );
str.append( " {" );
Field[] fields = type.getDeclaredFields();
for( int i = 0; i < fields.length; i++ ) {
Field field = fields[i];
str.append( field.getName() );
str.append( ":" );
try {
str.append( field.get( this ) );
} catch( IllegalAccessException | IllegalArgumentException ex ) {
str.append( "<NO ACCESS>" );
}
str.append( ", " );
}
str.append( "} " );
type = type.getSuperclass();
} while( type != null );
return str.toString();
}
}
class FieldDump2 extends FieldDumpTest {
private String test = "testtest";
}
class FieldDump3 extends FieldDump2 {
int ten = 10;
protected double fortytwo = 42.0;
}
Output:
run:
quicktest.FieldDump3 {ten:10, fortytwo:42.0, } quicktest.FieldDump2 {test:<NO ACCESS>, } quicktest.FieldDumpTest {topTestString:This is a test., topInt:11, topFloat:123.456, topShort:32767, } java.lang.Object {}
BUILD SUCCESSFUL (total time: 0 seconds)

Reading a text file using Java throws IOException

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...

Is there a way of storing Opencv/javacv Mat objects in a database?

After reading endless documents and trying to understand the examples about opencv/javacv for extracting keypoints, computing features with some DescriptorExtractors to match an input image against bunch of images to see if the input image is one of them or part of one of those images, I think, we should be storing the Mat objects after computing them.
I will use Emily Webb's code as an example:
String smallUrl = "rsz_our-mobile-planet-us-infographic_infographics_lg_unberela.jpg";
String largeUrl = "our-mobile-planet-us-infographic_infographics_lg.jpg";
IplImage image = cvLoadImage(largeUrl,CV_LOAD_IMAGE_UNCHANGED );
IplImage image2 = cvLoadImage(smallUrl,CV_LOAD_IMAGE_UNCHANGED );
CvMat descriptorsA = new CvMat(null);
CvMat descriptorsB = new CvMat(null);
final FastFeatureDetector ffd = new FastFeatureDetector(40, true);
final KeyPoint keyPoints = new KeyPoint();
final KeyPoint keyPoints2 = new KeyPoint();
ffd.detect(image, keyPoints, null);
ffd.detect(image2, keyPoints2, null);
System.out.println("keyPoints.size() : "+keyPoints.size());
System.out.println("keyPoints2.size() : "+keyPoints2.size());
// BRISK extractor = new BRISK();
//BriefDescriptorExtractor extractor = new BriefDescriptorExtractor();
FREAK extractor = new FREAK();
extractor.compute(image, keyPoints, descriptorsA);
extractor.compute(image2, keyPoints2, descriptorsB);
System.out.println("descriptorsA.size() : "+descriptorsA.size());
System.out.println("descriptorsB.size() : "+descriptorsB.size());
DMatch dmatch = new DMatch();
//FlannBasedMatcher matcher = new FlannBasedMatcher();
//DescriptorMatcher matcher = new DescriptorMatcher();
BFMatcher matcher = new BFMatcher();
matcher.match(descriptorsA, descriptorsB, dmatch, null);
System.out.println(dmatch.capacity());
My question is :
How can I store descriptorsA (or descriptorsB) in a DB --in java implementation of opencv- ? (They are Mat objects obtained after extractor.compute(image, keyPoints, descriptorsA); )
I am aware of the fact that Mat objects are not serializable objects in java implementation but surely, if you want to match an image against a set of archive images, you have to extract the descriptors of your archive and store them some where for feature use..
After some more search I have found some links in http://answers.opencv.org/question/8873/best-way-to-store-a-mat-object-in-android/
Although the answers are mainly for android devices and referring to earlier questions about saving keypoints ( Saving ORB feature vectors using OpenCV4Android (java API)), the answer "from Mat object to xml and xml to Mat object" in the code below seems to be working:
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.util.Locale;
import java.util.Scanner;
public class TaFileStorage {
// static
public static final int READ = 0;
public static final int WRITE = 1;
// varaible
private File file;
private boolean isWrite;
private Document doc;
private Element rootElement;
public TaFileStorage() {
file = null;
isWrite = false;
doc = null;
rootElement = null;
}
// read or write
public void open(String filePath, int flags ) {
try {
if( flags == READ ) {
open(filePath);
}
else {
create(filePath);
}
} catch(Exception e) {
e.printStackTrace();
}
}
// read only
public void open(String filePath) {
try {
file = new File(filePath);
if( file == null || file.isFile() == false ) {
System.err.println("Can not open file: " + filePath );
}
else {
isWrite = false;
doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(file);
doc.getDocumentElement().normalize();
}
} catch(Exception e) {
e.printStackTrace();
}
}
// write only
public void create(String filePath) {
try {
file = new File(filePath);
if( file == null ) {
System.err.println("Can not wrtie file: " + filePath );
}
else {
isWrite = true;
doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
rootElement = doc.createElement("opencv_storage");
doc.appendChild(rootElement);
}
} catch(Exception e) {
e.printStackTrace();
}
}
public Mat readMat(String tag) {
if( isWrite ) {
System.err.println("Try read from file with write flags");
return null;
}
NodeList nodelist = doc.getElementsByTagName(tag);
Mat readMat = null;
for( int i = 0 ; i<nodelist.getLength() ; i++ ) {
Node node = nodelist.item(i);
if( node.getNodeType() == Node.ELEMENT_NODE ) {
Element element = (Element)node;
String type_id = element.getAttribute("type_id");
if( "opencv-matrix".equals(type_id) == false) {
System.out.println("Fault type_id ");
}
String rowsStr = element.getElementsByTagName("rows").item(0).getTextContent();
String colsStr = element.getElementsByTagName("cols").item(0).getTextContent();
String dtStr = element.getElementsByTagName("dt").item(0).getTextContent();
String dataStr = element.getElementsByTagName("data").item(0).getTextContent();
int rows = Integer.parseInt(rowsStr);
int cols = Integer.parseInt(colsStr);
int type = CvType.CV_8U;
Scanner s = new Scanner(dataStr);
s.useLocale(Locale.US);
if( "f".equals(dtStr) ) {
type = CvType.CV_32F;
readMat = new Mat( rows, cols, type );
float fs[] = new float[1];
for( int r=0 ; r<rows ; r++ ) {
for( int c=0 ; c<cols ; c++ ) {
if( s.hasNextFloat() ) {
fs[0] = s.nextFloat();
}
else {
fs[0] = 0;
System.err.println("Unmatched number of float value at rows="+r + " cols="+c);
}
readMat.put(r, c, fs);
}
}
}
else if( "i".equals(dtStr) ) {
type = CvType.CV_32S;
readMat = new Mat( rows, cols, type );
int is[] = new int[1];
for( int r=0 ; r<rows ; r++ ) {
for( int c=0 ; c<cols ; c++ ) {
if( s.hasNextInt() ) {
is[0] = s.nextInt();
}
else {
is[0] = 0;
System.err.println("Unmatched number of int value at rows="+r + " cols="+c);
}
readMat.put(r, c, is);
}
}
}
else if( "s".equals(dtStr) ) {
type = CvType.CV_16S;
readMat = new Mat( rows, cols, type );
short ss[] = new short[1];
for( int r=0 ; r<rows ; r++ ) {
for( int c=0 ; c<cols ; c++ ) {
if( s.hasNextShort() ) {
ss[0] = s.nextShort();
}
else {
ss[0] = 0;
System.err.println("Unmatched number of int value at rows="+r + " cols="+c);
}
readMat.put(r, c, ss);
}
}
}
else if( "b".equals(dtStr) ) {
readMat = new Mat( rows, cols, type );
byte bs[] = new byte[1];
for( int r=0 ; r<rows ; r++ ) {
for( int c=0 ; c<cols ; c++ ) {
if( s.hasNextByte() ) {
bs[0] = s.nextByte();
}
else {
bs[0] = 0;
System.err.println("Unmatched number of byte value at rows="+r + " cols="+c);
}
readMat.put(r, c, bs);
}
}
}
}
}
return readMat;
}
public void writeMat(String tag, Mat mat) {
try {
if( isWrite == false) {
System.err.println("Try write to file with no write flags");
return;
}
Element matrix = doc.createElement(tag);
matrix.setAttribute("type_id", "opencv-matrix");
rootElement.appendChild(matrix);
Element rows = doc.createElement("rows");
rows.appendChild( doc.createTextNode( String.valueOf(mat.rows()) ));
Element cols = doc.createElement("cols");
cols.appendChild( doc.createTextNode( String.valueOf(mat.cols()) ));
Element dt = doc.createElement("dt");
String dtStr;
int type = mat.type();
if(type == CvType.CV_32F ) { // type == CvType.CV_32FC1
dtStr = "f";
}
else if( type == CvType.CV_32S ) { // type == CvType.CV_32SC1
dtStr = "i";
}
else if( type == CvType.CV_16S ) { // type == CvType.CV_16SC1
dtStr = "s";
}
else if( type == CvType.CV_8U ){ // type == CvType.CV_8UC1
dtStr = "b";
}
else {
dtStr = "unknown";
}
dt.appendChild( doc.createTextNode( dtStr ));
Element data = doc.createElement("data");
String dataStr = dataStringBuilder( mat );
data.appendChild( doc.createTextNode( dataStr ));
// append all to matrix
matrix.appendChild( rows );
matrix.appendChild( cols );
matrix.appendChild( dt );
matrix.appendChild( data );
} catch(Exception e) {
e.printStackTrace();
}
}
private String dataStringBuilder(Mat mat) {
StringBuilder sb = new StringBuilder();
int rows = mat.rows();
int cols = mat.cols();
int type = mat.type();
if( type == CvType.CV_32F ) {
float fs[] = new float[1];
for( int r=0 ; r<rows ; r++ ) {
for( int c=0 ; c<cols ; c++ ) {
mat.get(r, c, fs);
sb.append( String.valueOf(fs[0]));
sb.append( ' ' );
}
sb.append( '\n' );
}
}
else if( type == CvType.CV_32S ) {
int is[] = new int[1];
for( int r=0 ; r<rows ; r++ ) {
for( int c=0 ; c<cols ; c++ ) {
mat.get(r, c, is);
sb.append( String.valueOf(is[0]));
sb.append( ' ' );
}
sb.append( '\n' );
}
}
else if( type == CvType.CV_16S ) {
short ss[] = new short[1];
for( int r=0 ; r<rows ; r++ ) {
for( int c=0 ; c<cols ; c++ ) {
mat.get(r, c, ss);
sb.append( String.valueOf(ss[0]));
sb.append( ' ' );
}
sb.append( '\n' );
}
}
else if( type == CvType.CV_8U ) {
byte bs[] = new byte[1];
for( int r=0 ; r<rows ; r++ ) {
for( int c=0 ; c<cols ; c++ ) {
mat.get(r, c, bs);
sb.append( String.valueOf(bs[0]));
sb.append( ' ' );
}
sb.append( '\n' );
}
}
else {
sb.append("unknown type\n");
}
return sb.toString();
}
public void release() {
try {
if( isWrite == false) {
System.err.println("Try release of file with no write flags");
return;
}
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(file);
// write to xml file
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
// do it
transformer.transform(source, result);
} catch(Exception e) {
e.printStackTrace();
}
}
}
As the code proposed by Thorben was to slow in my case, I came up with the following code using serialization.
public final void saveMat(String path, Mat mat) {
File file = new File(path).getAbsoluteFile();
file.getParentFile().mkdirs();
try {
int cols = mat.cols();
float[] data = new float[(int) mat.total() * mat.channels()];
mat.get(0, 0, data);
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(path))) {
oos.writeObject(cols);
oos.writeObject(data);
oos.close();
}
} catch (IOException | ClassCastException ex) {
System.err.println("ERROR: Could not save mat to file: " + path);
Logger.getLogger(this.class.getName()).log(Level.SEVERE, null, ex);
}
}
public final Mat loadMat(String path) {
try {
int cols;
float[] data;
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(path))) {
cols = (int) ois.readObject();
data = (float[]) ois.readObject();
}
Mat mat = new Mat(data.length / cols, cols, CvType.CV_32F);
mat.put(0, 0, data);
return mat;
} catch (IOException | ClassNotFoundException | ClassCastException ex) {
System.err.println("ERROR: Could not load mat from file: " + path);
Logger.getLogger(this.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
For descriptors you OpenCV uses Mats of floats, in other cases you have to modify the code accordingly to this list found here:
CV_8U and CV_8S -> byte[]
CV_16U and CV_16S -> short[]
CV_32S -> int[]
CV_32F -> float[]
CV_64F-> double[]
After search all of the answers,i edit some code and it seems work.I use it to store the Sift Descriptor into HBase.
public static byte[] serializeMat(Mat mat) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
float[] data = new float[(int) mat.total() * mat.channels()];
mat.get(0, 0, data);
ObjectOutput out = new ObjectOutputStream(bos);
out.writeObject(data);
out.close();
// Get the bytes of the serialized object
byte[] buf = bos.toByteArray();
return buf;
} catch (IOException ioe) {
ioe.printStackTrace();
return null;
}
}

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.

Categories