lundi 30 mars 2015

Wrong array input

So I wanted to take the user input into a variable and then add it to the array but instead the character goes straight into the array and skips like 3 lines of code. The Code here



import java.util.*;
public class Hangman{

public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Please enter your word and press enter: ");
String word = sc.nextLine();
System.out.println("Please enter a relevant category and press enter: ");
String category = sc.nextLine();
word.toUpperCase();
char charArray[] = new char[word.length()];


for(int i = 0; i<=word.length(); i++){
System.out.println("Category: " + category);
System.out.println("Letters Guessed: " + Arrays.toString(charArray));
System.out.println("Your guess: ");
char guess = sc.nextLine().charAt(0);
compare(guess, word);
charArray[i] = guess;


}
}
public static boolean compare(char guess, String word){
for(int i = 0; i<word.length(); i++){
if(guess == word.charAt(i)){
return true;
}
}
return true;
}
}


Output :



Please enter your word and press enter:
hello
Please enter a relevant category and press enter:
test
Category: test
Letters Guessed: [hi
Category: test
Letters Guessed: [h, l
Category: test
Letters Guessed: [h, l, m
Category: test
Letters Guessed: [h, l, m, o
Category: test
Letters Guessed: [h, l, m, o, n
Category: test
Letters Guessed: [h, l, m, o, n]
Your guess:


can someone give some tips


Aucun commentaire:

Enregistrer un commentaire