开始学习计算机科学的学生,尝试在Java中制作一个猜词游戏(hangman game)。

huangapple go评论64阅读模式
英文:

Beginning CS student trying to make a hangman game in java

问题

String[] str = {"apple", "apple"};
int attempts = 0;

String randStr = str[rand.nextInt(str.length)];
		
char [] ans = randStr.toCharArray();
char [] guess = new char[ans.length];

while(attempts <= 10){
    System.out.println("Enter A letter:");
    char userAns = (char) System.in.read();
		
    for(int i = 0; i < ans.length; i++) 
    {
        if(ans[i] == userAns) 
        {
            int loc = i;
            guess[loc] = ans[loc];
            correct++;
        }
    }
    attempts++;
    System.out.println(Arrays.toString(guess));	
}

请注意,由于这是纯粹的翻译任务,我只为你提供了代码的翻译部分。如果您有任何关于代码的问题或需要进一步的解释,请随时问我。

英文:

So I kinda got the code to do what I want it to do.

Take in an user inputted char
compare it to each char in a random array
if they equal each other save the location of when they equal each other to a variable
Save the character that was correctly guessed to a blank char array in the same location.
repeat...

The problem I am having is when looping, the program loops 3 times instead of just asking for another input after first loop.

***Ex.(What code prints):***
Enter A letter: 
a
[a, , , , ]
Enter A letter:
[a, , , , ]
Enter A letter:
[a, , , , ]
Enter A letter:

**Ex.(What I would like code to print)***
Enter A letter:
a
[a, , , , ]
Enter A letter:
p
[a, p, p, , ]

String[] str = {&quot;apple&quot;, &quot;apple&quot;};
int attempts = 0;

String randStr = str[rand.nextInt(str.length)];
	
	char [] ans = randStr.toCharArray();
	char [] guess = new char[ans.length];

while(attempts&lt;=10){
	System.out.println(&quot;Enter A letter: &quot;);
	char userAns = (char) System.in.read();
	
	for(int i = 0;i&lt;ans.length;i++) 
	{
		if(ans[i]==userAns) 
		{
			int loc = i;
			guess[loc] = ans[loc];
			correct++;
		}
	}
	attempts++;
	System.out.println(Arrays.toString(guess));	
}

答案1

得分: 0

问题出在你对 System.in.read(). 方法的使用上。你以为在读取一个字符,但实际上获取了更多内容。你输入了 'a',然后按下 [Enter] 键。实际发生的是,[Enter] 键会生成两个额外的非打印字符:\r(回车符)和 \n(换行符),这是 Windows 的标准行为。System.in.read() 并不仅仅是读取下一个 char,而是读取下一个数据字节,无论是什么类型的数据。看起来像是循环的两次额外迭代实际上是 read() 调用消耗了按下 [Enter] 键生成的两个字符。

解决这个问题最简单的方法是使用 Scanner 类来读取输入,这在从控制台读取用户数据时几乎是标准的做法。

你需要导入 Scanner,创建一个 Scanner 实例,然后使用它从用户处获取一个字符串。然后使用 String.charAt() 来获取用户输入的字符串的第一个字符(因为没有直接的方法从 Scanner 读取 char 类型的输入)。

import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;

public class Test {
    public static void main(String[] args) {
        Random rand = new Random();
        String[] str = {"apples", "apples"};
        int attempts = 0;
        int correct = 0;
        
        Scanner scanner = new Scanner(System.in);
        
        String randStr = str[rand.nextInt(str.length)];
        
        char userAns = '
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;

public class Test {
    public static void main(String[] args) {
        Random rand = new Random();
        String[] str = {"apples", "apples"};
        int attempts = 0;
        int correct = 0;
        
        Scanner scanner = new Scanner(System.in);
        
        String randStr = str[rand.nextInt(str.length)];
        
        char userAns = '\0';
        char[] ans = randStr.toCharArray();
        char[] guess = new char[ans.length];
        
        while (attempts < 10) {
            System.out.println("Enter A letter:");
            userAns = (scanner.nextLine()).charAt(0);
            
            for (int i = 0; i < ans.length; i++) {
                if (ans[i] == userAns) {
                    int loc = i;
                    guess[loc] = ans[loc];
                    correct++;
                }
            }
            attempts++;
            
            System.out.println(Arrays.toString(guess));
        }
    }
}
'
;
char[] ans = randStr.toCharArray(); char[] guess = new char[ans.length]; while (attempts < 10) { System.out.println("Enter A letter:"); userAns = (scanner.nextLine()).charAt(0); for (int i = 0; i < ans.length; i++) { if (ans[i] == userAns) { int loc = i; guess[loc] = ans[loc]; correct++; } } attempts++; System.out.println(Arrays.toString(guess)); } } }

如果你不能使用 Scanner(因为你的讲师还没有介绍它),那么... 欢迎来到 "Kludgeville"(指临时性修补的地方)。你需要读取多余的非打印字符并静默地丢弃它们。

代替:

char userAns = (char) System.in.read();

你需要:

char userAns = (char) System.in.read();
char garbage = (char) System.in.read();
char trash = (char) System.in.read();

你还需要修复你的程序永远不会结束的问题,即使用户猜对了单词也是如此。提示:通过修改 while 循环的条件来检测 correct 是否等于答案中的字符数,来解决这个问题。还有更优雅的方法来解决这个问题,但这个方法对你的目的来说也是可以的。

英文:

The problem you have lies with the use of System.in.read(). You think you're reading one character, but you're actually getting more. You type 'a' and then you hit [Enter]. What's actually happening is that the [Enter] key is generating two additional non-printing chars: \r (carriage return) and '\n' (newline), which is standard behavior for Windows. System.in.read() doesn't specifically read the next char, but rather, the next byte of data, whatever that may be. What looks like two extra iterations of the loop is actually the call to read() consuming the two characters created by pressing [Enter].

The easiest fix for this problem is to use the Scanner class to read input, which is pretty much standard for reading user data from console.

You want to import Scanner, create an instance of Scanner and then use it to take a String from the user. Then use String.charAt() to get the first char from whatever String the user enters (because there's no direct way to read char type input from Scanner).

import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;

public class Test
{
  public static void main(String[] args)
  {
    Random rand = new Random();
    String[] str = {&quot;apples&quot;, &quot;apples&quot;};
    int attempts = 0;
    int correct = 0;
// New code (one line)
    Scanner scanner = new Scanner(System.in);

    String randStr = str[rand.nextInt(str.length)];

    char userAns = &#39;
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class Test
{
public static void main(String[] args)
{
Random rand = new Random();
String[] str = {&quot;apples&quot;, &quot;apples&quot;};
int attempts = 0;
int correct = 0;
// New code (one line)
Scanner scanner = new Scanner(System.in);
String randStr = str[rand.nextInt(str.length)];
char userAns = &#39;\0&#39;;
char [] ans = randStr.toCharArray();
char [] guess = new char[ans.length];
while(attempts &lt; 10)
{
System.out.println(&quot;Enter A letter: &quot;);
// New code (one line)
userAns = (scanner.nextLine()).charAt(0);
for(int i = 0; i &lt; ans.length; i++)
{
if(ans[i] == userAns)
{
int loc = i;
guess[loc] = ans[loc];
correct++;
}
}
attempts++;
System.out.println(Arrays.toString(guess));
}
}
}
&#39;; char [] ans = randStr.toCharArray(); char [] guess = new char[ans.length]; while(attempts &lt; 10) { System.out.println(&quot;Enter A letter: &quot;); // New code (one line) userAns = (scanner.nextLine()).charAt(0); for(int i = 0; i &lt; ans.length; i++) { if(ans[i] == userAns) { int loc = i; guess[loc] = ans[loc]; correct++; } } attempts++; System.out.println(Arrays.toString(guess)); } } }

If you can't use Scanner (because your instructor hasn't introduced it), well... welcome to Kludgeville. You're going to need to read the extraneous non-printing characters and throw them away silently.

Instead of:

char userAns = (char) System.in.read();

you'll do:

char userAns = (char) System.in.read();
char garbage = (char) System.in.read();
char trash = (char) System.in.read();

You also need to fix the fact that your program never ends, even after the user guesses the correct word. HINT: fix it by altering the condition of your while loop to detect when correct is equal to the number of characters in the answer. There are more elegant ways to address that problem, but that approach will work OK for your purposes.

huangapple
  • 本文由 发表于 2020年10月25日 10:39:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/64519809.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定