Cách sửa lỗi array lengths differed, expected.length=8, actual.length=23


Đây là đề bàiJAVA của em, em không biết làm sao khi chạy JunitTest thì lại bị lỗi trên, có bác nào biết cách sửa giúp em không ạ, và 1 lỗi khác là java.util.NoSuchElementException. Em xin cảm ơn

package edu.wit.cs.comp1050;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

//TODO: document this class
public class PA4c {
	
	/**
	 * Removes all duplicate values
	 * from the supplied list
	 * 
	 * @param list list from which to remove repeated elements
	 */
	public static void removeRepeated(ArrayList<Integer> list) {
		// replace with your code
		for(int i=0;i<list.size();i++) {

			for(int j=i+1;j<list.size();j++){

			if(list.get(i) == list.get(j)) {

			list.remove(j);

			j++;

			}

			}

			}
	}

	/**
	 * Reads numbers from the keyboard and
	 * outputs the list of distinct values
	 * 
	 * @param args command-line arguments, ignored
	 */
	public static void main(String[] args) {
		// replace with your code
		 Scanner input = new Scanner(System.in);
		 String s = input.nextLine();

		 ArrayList<Integer> list = new ArrayList<Integer>();

		 while(!s.trim().equals("")) {

		 list.add(Integer.parseInt(s));

		 s = input.nextLine();

		 }

		 try{
			 if(list.size() > 0) {
		 
		 removeRepeated(list);

		 System.out.print("The distinct integer(s): ");

			 }for(Integer i: list){

		 System.out.print(i+" ");

		 }
			 

		 System.out.println();
			 

		 }catch (Exception e) {

		 System.out.println("No values entered.");
		 System.exit(0);

		 } 
	}

}

Đây là code em viết.

Remove rồi thì phải j-- để check lại vị trí đó chứ ?

Đoạn này bạn try - catch làm gì @@


Code của bạn viết rối quá, thử sửa những lỗi mình nêu trên kia xong rồi viết code clean hơn 1 chút xem nó có dễ Fix hơn không.

1 Like

Em đã sửa lại theo bác và phần for int j = i + 1 em sửa thành j = 0, xóa dòng list.remove(j), thế là hết lỗi, em xin cảm ơn bác nhiều lắm ạ

Bạn tích solution cho mình nhé :slight_smile:

83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?