我的安卓手机里有一个代码,可以通过collections.frequency查找重复的号码。这段代码只有在android上才能在java程序中正常运行。但不是作为android上的应用程序。这是我在android中的代码。
ArrayList<String> ll = new ArrayList<String>();
String item = inputText.getText().toString();
ll.add(item);
HashSet<String> set = new HashSet<>(ll);
for (String temp : set)
{
answertext.setText(temp + "shows that many times: " + Collections.frequency(ll, temp));
}输出如下:
33 44 33 44 shows that many times: 1如果用户通过文本框输入数字,则不会找到任何重复的数字。但是,如果在代码中删除用户输入,并将其替换为以下输入:
ll.add("33");
ll.add("44");
ll.add("33");
ll.add("44");
ll.add("24");
ll.add("24");输出将如下所示:
44 shows that many times: 2因此,在这里使用此输入,collections.frequency将查找重复的数字。但是为什么只有一个号码呢?为什么是44而不是33?为什么它不像java程序那样只在电话上输出所有重复的号码。没有Android的参与?我想让它与来自文本框的用户输入一起工作。在Java端,它工作得很好,我得到了以下代码:
List<String> list = new ArrayList<String>();
Scanner stdin = new Scanner(System.in);
System.out.println("Enter the amount of numbers you want to input: Input numbers separated by a space.");
int n = stdin.nextInt();
for (int i = 0; i < n; i++)
{
list.add(stdin.next());
}
System.out.println("\nCount all with frequency");
Set<String> uniqueSet = new HashSet<String>(list);
for (String temp : uniqueSet)
{
System.out.println(temp + " shows that many times : " + Collections.frequency(list, temp));
}//Enter the amount of numbers you want to input
12 //hit the return key
22 33 44 22 33 44 22 33 44 22 33 44
//the output is like so:
Count all with frequency
33 shows that many times: 4
44 shows that many times: 4
22 shows that many times: 4为什么这段代码可以在Java上运行,但不能在android上运行?
发布于 2015-05-28 10:17:11
String item = inputText.getText().toString();
ll.add(item);这将向列表中添加一项。我猜你想要单独添加每个单词,你可以这样做:
// split the input apart at the spaces
String[] items = inputText.getText().toString().split(" ");
// then add each part separately to the list
for(String item : items)
ll.add(item);你的第二个问题是setText...设置文本。它不会添加到文本的末尾,而是替换已有的内容。我不知道您打算如何显示多个字符串,但您可以这样做:
// clear answertext
answertext.setText("");
for (String temp : set)
{
// set the text to <whatever was already there> followed by this item
answertext.setText(answertext.getText() + temp + "shows that many times: " + Collections.frequency(ll, temp) + "\n");
}https://stackoverflow.com/questions/30495667
复制相似问题