2013-12-13 53 views
0

我試圖建立類似劊子手(初學者)字符數組比較

我試試這個:

int i = 0; 
int fails = 0; 
boolean success = false; 
boolean retval; 
char[] defineword = new char[] { 'h', 'u', 'n', 'g' }; 
char[] givenchar = new char[0]; 
char[] testchar = new char[] { 'h' }; 

while (success == false && fails < 5) { 
    System.out.println("Give a char: "); 
    String word = input.next(); // INPUT STRING 
    givenchar = word.toCharArray(); // CONVERT 

    retval = Arrays.equals(givenchar, testchar); 
    System.out.println("THE LETTER IS " + retval); 
    if (retval == true) { 
     testchar[0] = defineword[i + 1]; 
    } else { 
     fails++; 
    } 
} 

的問題是,它不能信之後繼續執行(「U」 ),它卡在'你'。

+1

1)沒有必要增加的主要標籤的稱號。 2)爲了更快地獲得更好的幫助,請發佈[SSCCE](http://sscce.org/)。 –

+1

你的代碼有很多錯誤,所以沒有一個簡單的答案。 –

回答

0

我會做的一個觀察是,你只有真正的比較是在givenchartestchar之間。

retval = Arrays.equals(givenchar, testchar); 

它將使意義,一旦你得到了這個是行不通的過去u因爲testchar永遠不會越過u無論是。我想你可能打算在某處添加一個i++

testchar[0] = defineword[i + 1]; 
+0

@Vulcan,這裏的問題是'i'沒有更新以反映新的狀態。 – rsp

0
package mer; 
import java.util.Scanner; 
public class Aswe 
{ 
int i=0; 
int f=0; 
boolean suc=false; 
boolean ret; 
char[] dw=new char[]{'h','u','n','g'}; 
char[] gc=new char[0]; 
char[] tc=new char[]{'h'}; 
Scanner i1; 
public void me() 
    { 
    i1=new Scanner(System.in); 
    while(suc==false&&f<5) 
    { 
     System.out.println("give a char"); 
     String ch=i1.nextLine(); 

     gc=ch.toCharArray(); 

     ret=eual(gc,tc); 
     System.out.println("the letter is"+ret); 

     if(ret) 
     { 
     tc[0]=dw[i+1]; 
     } 
    else 
     f++; 
} 
} 
public boolean eual(char[] a,char[] b) 
{ 
    if(a[0]==b[0]) 
    return true; 
    else 
    return false; 
} 
    public static void main(String ... args) 
{ 
    new Aswe().me(); 
} 
} 
0
private int fails = 0; 
private final int maxFails = 5; 

private char[] answer = new char[] {'j','a','v','a'}; 

public Hangman() { 

    Scanner scan = new Scanner(System.in); 

    /* 
    * Game Loop 
    */ 
    while(fails < maxFails){ 
     System.out.print("Enter a char: "); 
     char givenChar = scan.next().charAt(0); 
     System.out.println("Given char is: " + Check(answer,givenChar)); 
    } 
} 

/* 
* Check if the char exists in the array. 
*/ 
private boolean Check(char[] array,char value){ 

    for(int i = 0; i < array.length; i++){ 
     if(array[i] == value){ 
      return true; 
     } 
    } 

    /* 
    * Okay did not find any char that match return false. 
    */ 
    return false; 
} 
+0

我會推薦使用面向對象的編程。 – Robban64

+0

請不要只包含代碼 – placeybordeaux