繁体   English   中英

为什么此Java代码显示出奇怪的行为?

[英]Why this java code is showing strange behavior?

我一直在尝试解决一个竞争性的编程问题,我已经按照自己的逻辑解决了这个问题,但是我无法理解输出,

每当我输入1作为输入时,它就会显示输出0,而不是要求输入字符串。

这是问题的链接:- 链接

这是代码:

    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);
        }

    }
}

java.util.Scanner.nextLine()方法使此扫描程序前进到当前行之外,并返回被跳过的输入。 此方法返回当前行的其余部分,但不包括最后的任何行分隔符。 该位置设置为下一行的开始。

您应该使用next()而不是nextLine() ,因为nextLine给出了当前行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM