2016-05-19 2 views
-2

Я закодировал программу, которая проверяет элементы двух массивов и говорит, являются ли они анаграммами или нет. Мой код работает неправильно. Не могли бы вы рассказать мне, является ли ошибка в цикле for при сортировке отдельных массивов? Что нужно исправить? Должен ли я использовать разные имена счетчиков для циклов двух массивов?Проверка анаграммы в java

/*/ Anagrams: 

Example: two sets of numbers: {10, 40, 20, 30} and {20, 10, 30, 40} are anagrams to 
     each other 

/*/ 

import static java.lang.System.*; 
import java.util.*; 

class Anagram_Check{ 
    public static void main(String[] args){ 
     Scanner orcho = new Scanner(in); 
     out.println("Please enter the amount of numbers for the first array: "); 
     int quantity1 = orcho.nextInt(); 
     out.println("Please enter the amount of numbers for the second array: "); 
     int quantity2 = orcho.nextInt(); 

     if(quantity1 != quantity2){ 
      out.println("No, the arrays will not be anagrams"); 
     } 

     else{ 
      int[] myArray1 = new int[quantity1]; 

      out.println("Please enter the numbers of the first array: "); 

      for(int count = 0; count < myArray1.length; count++){ 
       myArray1[count] = orcho.nextInt(); 
      } 

      int icu; 

      for(int count = 0; count < myArray1.length; count++){ 
       for(int check = 0; check < myArray1.length - 1; check++){ 
        if(myArray1[check] > myArray1[check + 1]){ 
         icu = myArray1[check]; 
         myArray1[check] = myArray1[check + 1]; 
         myArray1[check + 1] = icu; 
        } 
       } 
      } 

      int[] myArray2 = new int[quantity2]; 

      out.println("Please enter the numbers of the second array: "); 

      for(int count = 0; count < myArray2.length; count++){ 
       myArray2[count] = orcho.nextInt(); 
      } 

      for(int count = 0; count < myArray2.length; count++){ 
       for(int check = 0; check < myArray2.length - 1; check++){ 
        icu = myArray2[check]; 
        myArray2[check] = myArray2[check + 1]; 
        myArray2[check + 1] = icu; 
       } 
      } 

      int d = 0; 

      for(int count = 0; count < myArray1.length; count++){ 
       if(myArray1[count] == myArray2[count]){ 
        d = 1; 
       } 

       else{ 
        d = 5; 
       } 
      } 

      if(d == 1){ 
       out.println("Yes, they are anagrams"); 
      } 

      else if (d ==5){ 
       out.println("No, they are not anagrams"); 
      } 
     } 

     orcho.close(); 
    } 
} 
+4

[Вопросы, ищущих отладки помощи («почему не этот код работает?») Должен включать в себя желаемое поведение, конкретную проблему или ошибку и короткий код, необходимый для воспроизведения его в самом вопросе. Вопросы без четкого описания проблемы не полезны другим читателям] (http://stackoverflow.com/help/on-topic). Пожалуйста, отредактируйте свой вопрос. – Turing85

+0

Спасибо. Да, я отредактировал соответственно @ Turing85 –

+0

Почему вы их сортируете? –

ответ

1

Я думаю, что проблема заключается в следующем цикл:

int d = 0; 

    for(int count = 0; count < myArray1.length; count++){ 
     if(myArray1[count] == myArray2[count]){ 
      d = 1; 
     } 
     else{ 
      d = 5; 
     } 
    } 

, как вы меняете значение «D» на каждой итерации, когда вы проверяете значение позже вы действительно только проверки, если последний элемент обоих массивов равен. Простое исправление было бы добавить

break; 

после того, как в конце утверждения еще, как только вы знаете, как массивы не равны, нет никакой необходимости продолжать проверку.

редактировать - также было бы лучше использовать логическое значение для г вместо междунар, как это только два возможных значения

например, при проверке, если массивы анаграммы

boolean d = true; 

for(int count=0; count < myArray1.length; count++){ 
    if (myArray[count]!=myArray2[count]){ 
     d=false; 
     break; 
    } 
} 

if (d) { 
    System.out.println("Yes, they are anagrams"); 
}else{ 
    System.out.println("Yes, they are not anagrams"); 
} 
+0

Так что мне делать в инструкции if? @Wayne –

+0

Я обновлю свой ответ – Wayne

+0

Извините, но он все еще не работает! После того, как я дал оператор break, как вы сказали в своем ответе, все же, если я ввожу 1,2,3,4 в первый массив и 3,4,2,1 во втором, выход по-прежнему «нет». –

0

Используйте этот простой алгоритм сортировки, называемый Bubble Sort. Его можно использовать для сортировки небольших списков. Это также эффективно. Перейдите в свой список, и он сделает все остальное.

e.g bubbleSort (myArray1);

public static void bubbleSort(int[] list) { 

    boolean flag = true; //checks if all the values have been compared 
         //default is set to true only to enter the loop 

    while (flag) { 

     flag = false; //assume all values are compared 

     for (int i = 0; i < (list.length - 1); i++) { 

      if (list[i] < list[i + 1]) { 

       int temp = list[i]; 
       list[i] = list[i + 1]; 
       list[i + 1] = temp; 
       flag = true; //all values are not compared since 
          // were still able to do comparisons 
      } 
     } 
    } 
} 
0
import java.util.Arrays; 
import java.util.Scanner; 

//this program checks if the arrays are anagrams to each other; 
//done by Nadim Baraky 

public class Anagram_Check { 


    public static void main(String[] args) { 

    Scanner sc = new Scanner(System.in); 

    System.out.print("Please enter the amount of numbers of the first array: "); 
    int quantity_1 = sc.nextInt(); 

    System.out.print("Please enter the amount of numbers of the second array: "); 
    int quantity_2 = sc.nextInt(); 

    if(quantity_1 != quantity_2) { 
     System.out.println("No , the arrays will not be anagrams"); 
    } 

    else { 

     int[] myArray1 = new int[quantity_1]; 
     System.out.print("Please enter the numbers of the first array: "); 

     //filling the array with numbers 
     for(int i = 0; i < myArray1.length; i++) { 
      myArray1[i] = sc.nextInt(); 
     } 
     Arrays.sort(myArray1); //this method sorts the array in increasing order 

     int[] myArray2 = new int[quantity_2]; 
     System.out.print("Please enter the numbers of the second array: "); 

     for(int i = 0; i < myArray2.length; i++) { 
       myArray2[i] = sc.nextInt(); 
     } 
     sc.close(); 
     Arrays.sort(myArray2); 

     if(anagram_checker(myArray1, myArray2)) { 
      System.out.println("Yes, they are anagrams."); 
     } 
     else { 
      System.out.println("No, they are not anagrams."); 
     } 
    } 
} 


//this method returns ture if the two arrays are anagrams and false otherwise 
    public static boolean anagram_checker(int[] myArray1, int[] myArray2) { 
     for(int i = 0; i < myArray1.length; i++) { 
     //this loop goes over all the elements of the two arrays and checks if the elements are not equal 
      if(myArray1[i] != myArray2[i]) { 
      return false; 
      } 
     } 
      //reaching this point means that all elements are equal & it'll return true 
      return true; 
    } 

}

Смежные вопросы