为什么按回车键后没有打印?

huangapple go评论76阅读模式
英文:

Why isn't printing if i press enter?

问题

以下是已翻译的代码部分:

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Main {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        int count = 1;

        while (input.hasNext()) {
            String s = input.nextLine();
            System.out.println(count + " " + s);
            count++;
        }

        input.close();
    }
}

如果您需要进一步的帮助,请告诉我。

英文:

Here is a problem in hackerrank. I am a noob in java so am facing a problem. In the code logic if i press enter means \n nextLine() will get it and will print number 1 but if I press enter it does print 1 but when I input a string it will print all the previous number why?

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;


public class Main {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        int count = 1;

        while (input.hasNext()) {
            String s = input.nextLine();
            System.out.println(count + " " + s);
            count++;
        }

        input.close();
    }
}

My current result is:

(enter)//input
//no output
(enter)//input
//no output
(enter)//input
//no output
Hello World! //input
1
2
3
4 Hello World!//output 

But shouldn't it be like

(enter)//input
1 //output
(enter)//input
2 //output
(enter)//input
3 //output
Hello World!//input
4 Hello World! //output 

答案1

得分: 3

问题在于input.hasNext()不包括空白的新行。你应该将它更改为input.hasNextLine()以产生期望的效果,就像下面的示例中一样:

public class Main {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        int count = 1;

        while (input.hasNextLine()) {
            String s = input.nextLine();
            System.out.println(count + " " + s);
            count++;
        }

        input.close();
    }
}
英文:

The issue is that input.hasNext() does not include an empty new line. You should change it to input.hasNextLine() to produce the desired effects, such as in the following:

public class Main {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        int count = 1;

        while (input.hasNextLine()) {
            String s = input.nextLine();
            System.out.println(count + " " + s);
            count++;
        }

        input.close();
    }
}

huangapple
  • 本文由 发表于 2023年7月3日 04:51:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/76600745.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定