为什么这段java代码表现出奇怪的行为?
我一直在试图解决一个有竞争力的编程问题,我用我的逻辑解决了这个问题,但我无法理解一个输出
无论何时输入1作为输入,它都会显示输出0,而不是请求字符串输入
以下是问题的链接:-link
代码如下:
package Algorithms;// Working program using Reader Class
import java.util.*;
import java.io.*;
public class MaxndSecodMax
{
public static void main(String[] args) throws IOException
{
Scanner s = new Scanner(System.in);
int input = s.nextInt();
for(int k=0;k<input;k++)
{
HashMap<String, Integer> hash = new HashMap<>();
String x = s.nextLine();
String splitForm[] = x.split("");
for(String s1: splitForm){
if(hash.get(s1)!=null){
hash.put(s1, hash.get(s1)+1);
}
else{
hash.put(s1,1);
}
}
checkEvenOdd(hash);
}
}
private static void checkEvenOdd(HashMap<String, Integer> evenOdd){
ArrayList<Integer> even =new ArrayList<>();
ArrayList<Integer> odd =new ArrayList<>();
for (Map.Entry<String,Integer> entry : evenOdd.entrySet())
{
if(entry.getValue()%2==0){
even.add(entry.getValue());
}
else{
odd.add(entry.getValue());
}
}
if(odd.size()!=0){
System.out.println(odd.size()-1);
}
else{
System.out.println(0);
}
}
}
# 1 楼答案
您应该使用
next()
而不是nextLine()
,因为nextLine给出了当前行