Sunday, February 23, 2014

Word Guessing Game using Java

import java.io.*;
import java.util.*;
class file4{
static int kc = 0;
public static void main(String []arg) throws IOException{
FileReader fr = new FileReader("D:\\java\\f1.txt"); 

    //the file should contain words separated by spaces !
BufferedReader br2 = new BufferedReader(fr);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Random r = new Random();

String st = br2.readLine();    

//Works for single line.Use while loop till null if file contains multiple lines.
//System.out.println(st);


String t[] = st.split(" ");
String t1= t[r.nextInt(t.length)];
char ch[] = new char[t1.length()];
char ch3[] = new char[t1.length()];
for(int j=0;j<t1.length();j++){
ch3[j]=t1.charAt(j);
}
String t2;

int i,k;

for(i=0;i<t1.length();i++){
ch[i]='-';
}

// System.out.println("\nenter ur guess");
char ch2;
String x2;
printchar(ch,t1.length());
while(true){
int j;
System.out.println("\nenter ur guess\n");
x2=br.readLine();
System.out.println();

if(scheck(x2,t1)==1)
for(j=0;j<x2.length();j++){

ch2=x2.charAt(j);
//ch2=(char)br.read();
for(k=0;k<t1.length();k++){

if(ch3[k]==ch2){
ch[k]=ch2;
}


}

}
printchar(ch,t1.length());
check2(ch,t1.length());


}
}


static void check2(char c[],int k){

int i,k1=0;
for(i=0;i<k;i++){
if(c[i]=='-'){
k1++;
}
}
kc++;
if(k1==0){
System.out.println(" is correct \nCongrats ! Guess has been completed in attempt no "+kc+"!");
System.exit(0);
}
else System.out.println("\tattempts so far :: "+kc);
//return;
//System.exit(0);
}
static void printchar(char c[],int k){
for(int i=0;i<k;i++)
System.out.print(c[i]);

}
static int scheck(String a,String b){
int a1 = a.length();
int b1 = b.length();
int i=0,j=0;

if(a1<b1){
String temp = a;
a = b ;
b = temp ;
int t = a1;
a1 = b1 ;
b1 = t ;
}

while(j!=b1){
while(i!=a1){
if(a.charAt(i)==b.charAt(j)){
i++;
j++;

if(j==b1){
return 1;
}
}
else {
i++;
j=0;
if(i==a1)
return 0;
}
}
j++;
}


return 0;
}
}





Output




2 comments:

Anonymous said...

Nice work shyamel

Anonymous said...

quite sophisticated