gpt4 book ai didi

java - 根据 Switch Case 中的字母计算分数

转载 作者:行者123 更新时间:2023-12-02 09:50:08 24 4
gpt4 key购买 nike

我正在尝试创建一个类似拼字游戏的程序来计算单词中包含的字母的点。这些单词包含在 .txt 文件中。我可以让它从文件中读取,但不确定如何让它计算每个单词的值。我已经附上了到目前为止我所做的事情,并且想知道 switch case 是否是最好的方法,如果是,我如何为带有 switch case 的字母分配一个值。如有任何帮助,我们将不胜感激。

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package pointsproblem;

/**
*
*/

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;

public class PointsProblem {

/**
* @param args the command line arguments
* @throws java.io.FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException {
// TODO code application logic here

//create new object//
PointsProblem task1 = new PointsProblem();

File file = new File("dictionary.txt");
// read the file//
Scanner input = new Scanner(file);

//check if file can be found//
if (!file.isFile()) {
System.err.println("Cannot open file: " + input);
System.exit(0);
}
else {
System.out.println("Successfully opened file: " + input + ".");
}
//read all the lines in the file//
{
while (input.hasNext()) {
String word = input.nextLine();
System.out.println(word);
System.out.println("'" + input + "' is worth " + point + " points");



int point = "";
switch(point) {


case 'a': = "1":
case 'e': = "1";
case 'i': = "1";
case 'l': = "1";
case 'n': = "1";
case 'o': = "1";
case 'r': = "1";
case 's': = "1";
case 't': = "1";
case 'u': = "1";
case 'g': = "2";
case 'g': = "2";
case 'b': = "3";
case 'm': = "3";
case 'c': = "3";
case 'p': = "3";
case 'f': = "4";
case 'h': = "4";
case 'v': = "4";
case 'w': = "4";
case 'y': = "4";
case 'k': = "5";
case 'j': = "8";
case 'x': = "8";
case 'q': = "10";
case 'z': = "10";

return score = point + "";
}//end switch

}//end point calculation loop

public int getScore() {
return score;
}
//public boolean containsLetter(Character letter) {
//return points.contains(letter);//

}

我也尝试过将 X 的 int 值分配给该值。我希望它读取文件中包含的单词并给出总分。

最佳答案

看起来像 Map<Character, Integer>适合:

public class PointsProblem {
final Map<Character, Integer> pointsMap = Map.of(
'a', 1,
'e', 1,
//.......
'z', 10
);

然后,在您的函数中,只需使用 map 即可找到每个字符的对应点:

int wordPoints = 0;
for(char c : word.toCharArray())
wordPoints += pointsMap.get(c);

关于java - 根据 Switch Case 中的字母计算分数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56374940/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com