简体   繁体   中英

Why this java code is showing strange behavior?

I have been trying to solve a competitive programming question, i have solved the question by my logic but i cant understand an output,

Whenever i enter 1 as input it shows output 0, instead of asking for an string input.

Here is the link to question:- link

Here is the code:

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

    }
}

The java.util.Scanner.nextLine() method advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.

you should use next() instead of nextLine() , as nextLine gives the current line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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