【问题标题】:Always getting the same answer in java在java中总是得到相同的答案
【发布时间】:2020-01-05 09:48:01
【问题描述】:

谁能向我解释为什么我在运行以下代码时只得到 40 作为答案?

View problem in code coach

    import java.util.*;
    public class Program
    {
        public static void main(String[] args) {
            Scanner var = new Scanner (System.in);
            String n = var.nextLine();
            int p = var.nextInt();
            String[] a = var.nextLine().split(" ");
            List<String> list = new ArrayList<String>();
            for(int i=0;i<a.length;i++){
                list.add(a[i]);
            }
            list.add(n);
            Collections.sort(list);
            int y = list.indexOf(n)+1;
            if(y>p){
                System.out.print(((y/p)*20)+(y%p)*20);
            }
            else{
                System.out.print("20");
            }
        }
    }

【问题讨论】:

  • 欢迎来到 Stack Overflow。目前尚不清楚代码的用途 - 您没有在问题中解释它,并且没有 cmets。您是否尝试过在调试器中单步执行您的代码,以便了解它在什么时候的行为与您的预期不同?
  • 请输入示例;)
  • 您提供的链接已损坏。您尝试过哪些输入?对于不同的输入,我得到 20 和 40。
  • nextInt() 在输入时不使用 ENTER(换行符),因此允许 String[] a = var.nextLine().split(" "); 吸收它,因此永远不会真正调用它的意图。将var.nextLine(); 直接放在int p = var.nextInt(); 之后,看起来像这样int p = var.nextInt(); var.nextLine();
  • 该链接只能在手机上打开,而不能在电脑上打开

标签: java arrays arraylist collections java.util.scanner


【解决方案1】:

nextInt() 无法读取换行符。因此,当您使用 nextLine() 时,它会读取该换行符。 This answer might help you

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-07-26
    • 2011-09-15
    • 2016-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多