English 中文(简体)
比较插图/记录中的两种特性,看它们是否相同
原标题:Comparing two characters in a string/array to see if they are the same

我试图制造一个阵列,除空间外,删除重复之处(“”)。 我看到了一些在线方法,但我不想复制。 我尝试了许多方法,但我不理解我的方法为什么不奏效。

这是我所尝试的:

在第一个方法中,该方法是接收投入、打电话、制作一个阵列清单、通过插图打字,同时在阵列清单中增加每个特性,第二次通过清单将每个特性与第一个指数的特性进行比较,同时检查这些特性是否平等,然后从阵列清单中删除。

问题似乎是“在平等后将其从阵列清单中删除”:

if(character.get(i).equals(character.get(k))) {
    character.remove(arr.charAt(i));                
}

第二次

for(int k = 0;k < characters.length;k++) {
    if(characters[i]==characters[k]) {
        System.out.print(character);                        
        character.remove(characters[i]);                    
    }   
import java.util.*;

public class NoRepeats {
    
    public static void main(String args[]) {
        System.out.print("Please enter a phrase: ");
        Scanner scanner = new Scanner(System.in);
        String input = scanner.nextLine();
        
        char[] characters = chars(input);
    }
    
    public static char[] chars(String arr) {
        ArrayList<Character> character = new ArrayList<Character>();

        for(int i = 0; i<arr.length();i++) {
            character.add(arr.charAt(i));           

            for(int k = 1; k<arr.length();k++) {
                if(character.get(i).equals(character.get(k))) {
                    character.remove(arr.charAt(i));                
                }
            }
        }
        System.out.print(character);
        return null;
    }
}
import java.util.*;

public class NoRepeats {
    
    public static void main(String args[]) {
        System.out.print("Please enter a phrase: ");
        Scanner scanner = new Scanner(System.in);
        String input = scanner.nextLine();
        //receive input
        char[] characters = chars(input);
        //call function
    }
    
    public static char[] chars(String arr) {
        ArrayList<Character> character = new ArrayList<Character>();
        //create an empty arraylist
        char[] characters = arr.toCharArray();
        
        for(int j = 0; j<characters.length;j++) {
            character.add(characters[j]);
        }
       
        for(int i = 0; i<characters.length;i++) {
            /*traverse through the orignal array adding a character to 
            the empty array list each time*/            
                for(int k = 0;k < characters.length;k++) {
                    if(characters[i]==characters[k]) {
                    System.out.print(character);                        
                    character.remove(characters[i]);                    
                }                   
            }
        }
        return null;
    }
}

预期投入:

“And I think to myself: what a wonderful world!”

预期产出:

And I thk o myself: w ru !

第一个错误是:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 1 out of bounds for length 1 at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64) at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70) at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:266) at java.base/java.util.Objects.checkIndex(Objects.java:359) at java.base/java.util.ArrayList.get(ArrayList.java:427) at NoRepeats.chars(NoRepeats.java:20) at NoRepeats.main(NoRepeats.java:10)

第二种错误是:

"Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 118 out of bounds for length 2 at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64) at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70) at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:266) at java.base/java.util.Objects.checkIndex(Objects.java:359) at java.base/java.util.ArrayList.remove(ArrayList.java:504) at NoRepeats.chars(NoRepeats.java:33) at NoRepeats.main(NoRepeats.java:11) "

问题回答

First need to formulate your algorithm in words (or kind od pseudocode). Something like this: Problem: remove duplicated chars from string except space. Solution (pseudocode):

output_string = ""
used_chars = ""
for (c : input_string) {
  if (c ==    ) output_string += c;
  else if (!used_chars.contains(c)) {
    output_string += c;
    used_chars += c;
  }
}
print(output_string)

Now you can implement this in any language you want. Implementation in java can be:

static String solution(String input_string) {
    String output_string = "";
    Set<Character> used_chars = new TreeSet<>();
    for (char c : input_string.toCharArray()) {
        if (c ==    ) output_string += c;
        else if (!used_chars.contains(c)) {
            output_string += c;
            used_chars.add(c);
        }
    }
    return output_string;
}

public static void main(String[] args) {
    System.out.println(solution("And I think to myself: what a wonderful world!"));
}

<><>Code>:

package app;

import java.util.Scanner;

public class NoRepeats {
    public NoRepeats(){}

    public String scan(){
        System.out.print("Please enter a phrase: ");
        
        Scanner scanner = new Scanner(System.in);
        String read = scanner.nextLine(); //receive input
        scanner.close(); //do not forget to close
        
        return read;
    }

    public int contains(String character, char c, boolean caseInsensitive){
        int N = character.length();
        
        if(caseInsensitive) c = Character.toLowerCase(c);

        for(int i = 0; i < N; i++){
            char next = character.charAt(i);
            if(caseInsensitive) next = Character.toLowerCase(next);
            
            if(c == next) return i;
        }

        return -1;
    }

    public String getChars(String arr) {
        String character = "";

        for(int i = 0; i < arr.length(); i++){
            char next = arr.charAt(i);

            if(Character.isWhitespace(next) || contains(character, next, true) == -1) character += next;
            //else; //ignore
        }

        return character;
    }

    public static void main(String args[]) {
        NoRepeats noRepeats = new NoRepeats();

        String input = noRepeats.scan(),
               chars = noRepeats.getChars(input);

        System.out.println("String: " + chars);
    }
}

<>>Input:

And I think to myself: what a wonderful world!

<<>Output>:

String: And I thk o myself: w  ru !

你用<代码>i将特性阵列重新编号,在试图查阅内容时该阵列太短。

我建议你使用

public static char[] chars(String arr) {
    Set<Character> seen = new HashSet<>();
    char[] result = new char[arr.length()];
    int len = 0;
    for (char ch : arr.toCharArray()) {
        if (Character.isLetter(ch))
            if (!seen.add(Character.toLowerCase(ch))) {
                continue; //skip to end of loop
            }
        
        result[len++] = ch;
    }
    return Arrays.copyOf(result, len);
    
}

这里是它如何工作。

String input = "And I think to myself: what a wonderful world!";
char[] result = chars(input);
System.out.println(new String(result));

印刷

And I thk o myself: w  ru !





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签