【问题标题】:Comparing arrays in java?比较java中的数组?
【发布时间】:2013-06-18 22:50:14
【问题描述】:
import java.io.File;
import java.util.Scanner;

public class scoresedit {

public static void main(String[] args) throws Exception{
    System.out.println("Reads in a file at the beginning of a loop, displays these top 3 scores by name and their respective score." +
        "\nEnter a new name and score following a prompt. " +
        "\nIf the new name and score exceeds one of the top three scores," +
        "\nplaces the new name in the top three, moving all lower scores down, dropping the lowest score." +
        "\nSaves the results in the file top3Scores.txt."  +
        "\nStops the loop when exit is entered for a name.");
    File r = new File ("top3Scores.txt");
    System.out.println(r);
    String str = readSource (r);
    System.out.println(str);
    String[] strArray = new String[] {str};
    Scanner in = new Scanner(System.in);
    System.out.print("Enter a new name and score or 'exit' to quit:");
    String nameAndScore = in.nextLine();
    String[] nameAndScoreArray = new String[] {nameAndScore};
    String nameAndScoreArray1[] =  nameAndScore.split(" ");
    while (nameAndScore != "exit") {
        if (nameAndScoreArray[1] > strArray[1]) }
    }

private static String readSource(File r) throws Exception{
    Scanner in;
    in = new Scanner (r);
    String str = "";
    while (in.hasNext())
        str += in.nextLine() +"\n";
    in.close();
    return str;
}

}

当我尝试比较两个数组时,我不断收到错误“运算符 > 未定义参数类型 java.lang.String、java.lang.String”,但我不知道如何解决它。代码还没有完成;显然我在 if 语句下添加了更多内容,但我想先解决这个问题。

【问题讨论】:

    标签: java arrays


    【解决方案1】:

    您正在尝试比较 nameAndScoreArray[1]strArray[1] 是字符串,我假设它们包含两支球队的分数,得分最高的球队获胜,所以您想使用 Integer.parseInt(String string) 来查看哪个一个得分最高:

    if (Integer.parseInt(nameAndScoreArray[1]) > Integer.parseInt(strArray[1]))
    

    【讨论】:

    • 谢谢,是的,我正在尝试做类似的事情,用户输入一个名称和分数(例如:“John 5”),我正在尝试将输入的分数与最高分数进行比较从具有三个名称和分数的外部 .txt 文件中提取。然后,如果输入的分数更高,我将尝试替换 .txt 文件中的最高分数。
    • @M.J.K.如果您的Strings 还包含字母而不仅仅是数字,那么这将不起作用,您需要首先摆脱非数值。请参阅this 问题。顺便说一句,您可以在发布后最多 5 分钟编辑您的 cmets,只需点击编辑。
    • 非常感谢您的帮助,非常感谢
    【解决方案2】:

    您不能将String 与运算符<> 进行比较,而是需要使用compareTo

    【讨论】:

    • 谢谢,程序要求用户输入姓名和分数(例如:“John 5”),我尝试将字符串拆分为数组,以便比较用户输入的分数使用从外部 .txt 文件中提取的分数列表,您对如何执行此类操作有任何建议吗?抱歉,我刚刚阅读了您提供的 compareTo 链接,但还是不太明白
    • 那你需要利用这个答案:stackoverflow.com/a/17180327/122207
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多