简体   繁体   English

如何检查一个数组是否包含相同的值?

[英]How to check if one array contains value that is the same?

I'm learning about Java array and got stuck on this problem.我正在学习 Java 数组并陷入了这个问题。 I want to add the value of num and delete duplicate name if the name if equals.如果名称相等,我想添加 num 的值并删除重复的名称。 Thank you in advanced.先谢谢了。 Here's a little bit of my code:这是我的一些代码:

public static void main(String[]Args){
    Scanner input = new Scanner(System.in);
    int n;
    System.out.println("Input n= ");
    n=input.nextInt();
    String name[] = new String[n];
    int num[] = new int[n];

    for (int i = 0; i<n; i++){
        System.out.println("Input name= ");
        name[i]= input.next();
        System.out.println("Input num= ");
        num[i]=input.nextInt();
    }

for(int i=0;i<n;i++){       
System.out.println(name[i] + " " + num[i]);

    }

I'm expecting the result to be:我期待的结果是:

Example1 5例 1 5

Example2 6例 2 6

IF I input n=3如果我输入 n=3

name[1]="Example1"名称[1]="示例 1"

name[2] = "Example2"名称[2] = "示例 2"

name[3] = "Example1"名称[3] = "示例 1"

num[1] = 2数量[1] = 2

num[2] = 6数量[2] = 6

num[3] = 3数量[3] = 3

The actual result is:实际结果是:

Example1 2示例 1 2

Example2 6例 2 6

Example1 3示例 1 3

Remember that arrays starts at 0. This solution won't clear array so you will need to modify some of that to shift both arrays to left.请记住,数组从 0 开始。此解决方案不会清除数组,因此您需要修改其中的一些内容以将两个数组向左移动。

int n = 3;
    String[] name = new String[n];
    int[] num= new int[n];
    
    name[0] = "Example1";
    name[1] = "Example2";
    name[2] = "Example1";
    num[0] = 2;
    num[1] = 6;
    num[2] = 3;
    
    
    for (int i = 0; i < name.length; i++) {
        for (int j = i+1; j < name.length; j++) {
            if (name[i].equals(name[j])) {
                num[i] += num[j];
                num[j] = 0;
                name[j] = null;
            }
        }
    }


    for(int i=0;i<n;i++){
        if (name[i] != null) {
            System.out.println(name[i] + " " + num[i]);
        }
    }

Output:输出:

Example1 5例 1 5

Example2 6例 2 6

The following program accomplishes what you are after:以下程序完成您所追求的:

class Main {
  public static void main(String[] args) {
    int n = 2;
    String[] name = {"Example1", "Example2"};
    int[] num = {5, 6};

    //this is a comment

    for (int i = 0; i < n; i++){
      System.out.println(name[i] + "  " + num[i]);
    }

  }
}

You need to declare an array for num , name , and you also need to change your n value to 2 if you want to keep your loop format and only print out two elements.您需要为numname声明一个数组,如果您想保留循环格式并且只打印出两个元素,还需要将n值更改为 2。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM