Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/334.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 显示字符串中匹配的字符_Java - Fatal编程技术网

Java 显示字符串中匹配的字符

Java 显示字符串中匹配的字符,java,Java,对学习java非常陌生,我正在开发一个简单的程序,它显示两个用户输入字符串之间的匹配字符数。最后,它将显示匹配的字符总数以及匹配的字母。我一直在研究如何将值从内部for循环带回到要调用的主方法 import java.util.Scanner; public class CountMatches { public static void main(String[] args) { int matches = 0; String aString;

对学习java非常陌生,我正在开发一个简单的程序,它显示两个用户输入字符串之间的匹配字符数。最后,它将显示匹配的字符总数以及匹配的字母。我一直在研究如何将值从内部for循环带回到要调用的主方法

import java.util.Scanner;
public class CountMatches
{
    public static void main(String[] args)
    {
        int matches = 0;
        String aString;
        String anotherString;


        Scanner inputDevice = new Scanner(System.in);
        System.out.print("Enter a String >> ");
        aString = inputDevice.nextLine();
        System.out.print("Enter another string>> ");
        anotherString = inputDevice.nextLine();

        for(int i = 0; i < aString.length(); ++i)
        {

            for(int j = 0; j < anotherString.length(); ++j)
            {
                if(aString.charAt(i) == anotherString.charAt(j))
                    matches++;

            }

        }

       System.out.println(matches + " character(s) in " + aString + " are 
       also in " + anotherString);

   }
}
import java.util.Scanner;
公共类计数匹配
{
公共静态void main(字符串[]args)
{
int匹配=0;
绷带;
另一串;
扫描仪输入设备=新扫描仪(System.in);
System.out.print(“输入字符串>>”;
aString=inputDevice.nextLine();
System.out.print(“输入另一个字符串>>”;
另一个字符串=inputDevice.nextLine();
对于(int i=0;i

编辑:我还应该提到我正在做的这个任务,我还没有达到使用数组的程度。我们刚刚讨论了循环和if-then语句。所以我很早就开始学习java

您的逻辑不正确。可能需要在使用时探索其他一些数据结构,如Stack和ArrayList。看起来像这样

    int matches = 0;
    String aString;
    String anotherString;


    Scanner inputDevice = new Scanner(System.in);
    System.out.print("Enter a String >> ");
    aString = inputDevice.nextLine();
    System.out.print("Enter another string>> ");
    anotherString = inputDevice.nextLine();

    System.out.println(aString);
    System.out.println(anotherString);

    // we will store astring characters in a stack data structure
    Stack<Character> aStringStack = new Stack<Character>();
    // a list to store the matched characters
    List<Character> tempList = new ArrayList<>();

    //First adding all the chars from astring to the Stack
    for(int i = 0; i < aString.length(); i++)
    {
        aStringStack.push(aString.charAt(i));
    }


    for(int i = 0; i < aStringStack.size(); i++)
    {
        //Now iterating over the astring stack and popping the 
        // values from the top one at a time
        char temp = aStringStack.pop();

        for(int j = 0; j < anotherString.length(); j++)
        {
            //If the popped value is present in the anotherstring
            // then incrementing the match counter and storing the
            //matched character in our matched character array list
            if(temp == anotherString.charAt(j))
            {
                matches++;
                tempList.add(temp);

                // Also important to break the loop here to avoid
                // getting duplicates
                break;
            }

        }

    }

    System.out.println(matches + " character(s) in " + aString + " are  also in " + anotherString);
    System.out.println(tempList);
int匹配=0;
绷带;
另一串;
扫描仪输入设备=新扫描仪(System.in);
System.out.print(“输入字符串>>”;
aString=inputDevice.nextLine();
System.out.print(“输入另一个字符串>>”;
另一个字符串=inputDevice.nextLine();
系统输出打印项次(aString);
System.out.println(另一个字符串);
//我们将在堆栈数据结构中存储astring字符
堆栈aStringStack=新堆栈();
//用于存储匹配字符的列表
List templast=new ArrayList();
//首先将astring中的所有字符添加到堆栈中
对于(int i=0;i

还将建议将此答案与@Serge的答案进行比较,以了解如何使用不同的数据结构来解决同一问题。

您需要为您的字符及其计数器提供某种类型的数据库。有多种方法可以做到这一点。下面使用
HashMap
来执行此操作,其中字符是键,计数器是值。这不是一个非常有效的方法,但它符合解释的目的

    // allocate the char/counter map
    HashMap<Character, Integer> cMap = new HashMap<>();

    for (int i = 0; i < aString.length(); ++i) {

        for (int j = 0; j < anotherString.length(); ++j) {
            if (aString.charAt(i) == anotherString.charAt(j)) {
                // see if the char already has an associated counter
                Integer count = cMap.get(aString.charAt(i));
                if (count == null)
                    count = 0; // if no counter is found, create one and set it to '0' (before incrementing)
                count++; 

                cMap.put(aString.charAt(i), count); // put the new counter value in the map
                matches++;
            }
        }
    }

    // traverse all map entries and print the key/value (char/counter) paires
    for (Map.Entry<Character, Integer> entry : cMap.entrySet()) {
        System.out.println(entry.getKey() + ": " + entry.getValue());
    }
//分配字符/计数器映射
HashMap cMap=新的HashMap();
对于(int i=0;i
存储匹配字符的一种方法是使用数据结构。当两个字符串中都遇到匹配字符时,可以将该字符添加到集合中。在本例中,集合是用于保存对象的数据结构;人物。有很多不同类型的数据结构,但主要类型是Set、List和Queue

我使用ArrayList为您编写了一个解决方案:

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class CountMatches {
    public static void main(String[] args) {
        String aString;
        String anotherString;
        List<Character> matchingChars = new ArrayList<Character>();

        Scanner inputDevice = new Scanner(System.in);
        System.out.print("Enter a String >> ");
        aString = inputDevice.nextLine().toLowerCase();
        System.out.print("Enter another string>> ");
        anotherString = inputDevice.nextLine().toLowerCase();

        for (int i = 0; i < aString.length(); ++i) {
            for (int j = 0; j < anotherString.length(); ++j) {
                if (aString.charAt(i) == anotherString.charAt(j) && !matchingChars.contains(aString.charAt(i))) {
                    matchingChars.add(aString.charAt(i));
                }
            }
        }
        System.out.println(matchingChars.size() + " character(s) in " + aString + " are also in " + anotherString);
        System.out.println("The Matching character(s) are " + matchingChars);
    }
}
因为我们将字符添加到一个列表中,您可以检查列表的大小,所以您不再需要使用“matches”变量引用保持计数,因为我们只需调用matchingChars.size()

为了防止同一个字符被添加到列表中两次,我们必须仅在列表尚未包含该字符的情况下,使用

另外,作为建议,(正如我在上面的示例中所做的),您可以使用String.toLowercase()方法将字符串转换为小写,以便在比较字符时忽略字符的大小写


如果您想了解有关集合的更多信息,[Java Collections教程]()可能值得一看。

一个简单、最好、更少的代码,例如:

Set<Character> aStringSet = new TreeSet<Character>();
for(int i = 0; i < aString.length(); i++) {
    aStringSet.add(aString.charAt(i));
}

Set<Character> anotherSet = new TreeSet<Character>();
for(int i = 0; i < anotherString.length(); i++) {
    anotherSet.add(anotherString.charAt(i));
}

aStringSet.retainAll(anotherSet);
System.out.print(aStringSet.size() + " character(s) in " + aString + " are also in " + anotherString);
System.out.println(" matched characters are " + aStringSet.toString());
我用过。并在
TreeSet
中获取匹配的元素

Oracle文档:

retainAll(Collection<?> c)
retainAll(集合c)
仅保留此集合中包含在 指定的集合(可选操作)

Withou
Enter a String >> table
Enter another string>> fable
4 character(s) in table are also in fable matched characters are [a, b, e, l]
retainAll(Collection<?> c)
for(int j = 0; j < anotherString.length(); ++j)
        {
            if(aString.charAt(i) == anotherString.charAt(j))
            {
            matches++;
            aChar = aString.charAt(i);              
            foundStr = foundStr + " " + aChar;
            }

        }