有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

为什么这段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) 个答案

  1. # 1 楼答案

    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.

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