有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java中的无平方字数组

我一直在为一个班级创建一个解决问题的程序。我有一个主要的方法和一个次要的测试方法来解决这个问题,但是当出现变化时,我无法让解决方案起作用。 问题是确保一个单词是正方形,下面是问题的摘录:

For this part, implement a method called isSquareFree that takes as input (a reference to ) an array of characters. You may assume that the elements of the array are all lower case letters. (In other words, you do not need to worry about a question like: "is Z the same letter as z?") Your method should test if the given input array of characters is square-free. If it is, the method should print a message stating that, otherwise it should print a message stating that the world is not square-free, where the square subword starts and what that subword is. For example, if the given array contained the word zatabracabrac the method should print: The word, zatabracabrac, is not square free, since it has subword, abrac twice starting at position 4 of the word.

下面是我的当前代码,它适用于有一个重复字符彼此相邻的情况,但我不确定如何继续检查是否有多个重复字符(例如abab),也不确定如何打印重复子字

public static void main(String[] args) {

    // part (a) of the main

    Scanner keyboard = new Scanner(System.in);

    System.out.println("***************************");
    System.out.println("        Part (a)");
    System.out.println("***************************");

    do{
        System.out.println("Enter a word and then press enter:");
        String str=keyboard.next();
        char[] word = str.toCharArray();

        isSquareFree(word);
        System.out.println("Do you want to test another word? Press y for yes, or another key for no");

    }while(keyboard.next().charAt(0)=='y');


}

public static void isSquareFree(char[] word){
    int sqf = 0;
    for(int i=0; i<word.length; i++){
        for(int j=0; j<word.length-1;j++){
            if (word[j] == word[j+1]){
                sqf = 1;
                j = word.length;
            }
            else{
                sqf = 2;
            }
        }
    }
    if (sqf == 1){
        System.out.println();
        System.out.println("Not Square Free");
    }
    else{
        System.out.println();
        System.out.println("Square Free");
    }
}}

我还想补充一点,对于这个问题,我不允许使用arrays类,也不允许使用string,我不能更改main方法,也不能更改其他方法的输入


共 (1) 个答案

  1. # 1 楼答案

    1. 要查看一个字符序列是否重复,对于给定的序列长度(例如,n),您可以将if替换为一个循环,该循环对0和n之间的word[j+x]word[j+n+x]的每个值进行比较;如果所有的EM>n>EEM>匹配,只考虑它们相同。因此,您需要为x循环这些n值;如果你需要考虑不同的值 n,那么你需要另一个循环来完成这些。

      从您的代码中不清楚您使用的是{{CD6>},但是如果它是重复部分的长度(我称之为EM>nEEE>),那么您只需要考虑长度为^ {<7CD>}的一半(否则没有重复的空间)。p>

    2. 要打印子单词,可以按顺序打印每个字母(使用print而不是println