【问题标题】:Creating a method that will convert an Int into a String into the main using Java使用 Java 创建一个将 Int 转换为 String 的方法
【发布时间】:2020-01-28 05:53:16
【问题描述】:

我什至不知道从哪里开始解决这个问题,我必须获取一个可以在足球比赛中获得的分数,然后有一个方法将这个分数转换为主要的字符串。

代码如下:

public static void main(String[] args) {
    int correctCount = 0;
    if (translateScore(2).equals("safety") == true) { correctCount++;}
    if (translateScore(3).equals("field goal") == true) { correctCount++;}
    if (translateScore(6).equals("touchdown") == true) { correctCount++;}
    if (translateScore(7).equals("touchdown and extra point") == true) { correctCount++;}
    if (translateScore(8).equals("touchdown and 2-point conversion") == true) { correctCount++;}
    if (translateScore(-1).equals("") == true) { correctCount++;}
    if (translateScore(1).equals("invalid") == true) { correctCount++;}
    if (translateScore(10).equals("you must be playing Quidditch ") == true) { correctCount++;}
    if (correctCount == 8) {
        System.out.println("All tests passed");
    } else {
        System.out.println("At least one test failed");
    }
}

public static String translateScore (int score) {
    return "";  
}

【问题讨论】:

  • 你将如何“获得”分数?会在控制台中作为起始参数传递吗?
  • 并且不要将布尔值与true进行比较;它已经是truefalse
  • Integer.toString 确实存在...以及 int + "";
  • 为什么要翻译乐谱?似乎一开始就放弃翻译过程会更有效率。如果您需要翻译分数,我会推荐一组分配正确分数的 if 语句?或者,也许我误解了你想要做什么。你能说得清楚一点吗?

标签: java methods


【解决方案1】:

我不确定我是否理解正确,但如果您希望将几个不同的ints“转换”为一些固定字符串,那么也许您可以使用开关/大小写:

public static String translateScore(int score) {
    switch (score) {
    case 2:
        return "safety";
    case 3:
        return "field goal";
    // other cases...
    default:
        return "";
    }
}

【讨论】:

  • 基本上该方法必须获得 7 分,然后将该分数发送到 main 并打印为“touchdown”。我不能改变任何主要的东西,所以一切都必须在 translateScore 方法中发生,
  • 要么我误解了你,要么你误解了任务。 translateScore 返回 String,因此它不能“将该分数发送到主分数”。但是,它可以返回您在main 中拥有的固定字符串之一。
猜你喜欢
  • 1970-01-01
  • 2020-02-18
  • 2012-01-16
  • 2023-03-20
  • 1970-01-01
  • 2014-07-29
  • 2011-10-19
  • 1970-01-01
相关资源
最近更新 更多