Home > Java > javaTutorial > How to solve the problem of reading carriage return in Scanner.nextLine() in Java

How to solve the problem of reading carriage return in Scanner.nextLine() in Java

PHPz
Release: 2023-04-15 09:19:11
forward
1122 people have browsed it

Problem description

When we use java to read keyboard input, if we first read an int variable and then read the string of the next line, we will find that the program running result is not as expected, and the program does not The next line of string was not read.

That happens in the following situation:

Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
String s=sc.nextLine();
Copy after login

Problem analysis

From code analysis, our requirement is to first enter an int variable, and then enter a string on the next line, that is When we use the keyboard to input, we actually input three parts:

3
words

They are: the number 3, the newline character, and the string words.

How to deal with the extra newlines

As you can see from the analysis just now, the cause of the problem is that the nextLine() method did not read our string, but read our Enter the newline character.

Method 1

Since there is an extra newline character, we can read the newline character before reading the string:

Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
sc.nextLine();//将换行符读掉
String s=sc.nextLine();
Copy after login

Method 2

Re-create the Scanner object:

Scanner sc1=new Scanner(System.in);
int n=sc1.nextInt();
Scanner sc2=new Scanner(System.in);
String s=sc2.nextLine();
Copy after login

In this way, after n is read, the newline character will be discarded, and the next line will be regarded as the beginning of sc2. Location.

Practical practice

The following is the first question of tengxun company’s summer software-related position internship written test on April 26, 2020:

One of the basics of data structure - queue

The queue has five basic operations, inserting the end of the queue, removing the head of the queue, deleting the head of the queue, queue size, and clearing the queue.

Now allows you to simulate the operation of a queue. Please refer to input for the specific format.

Input description:

Enter an integer T in the first line, indicating that there will be T sets of test data next.
For each set of test data:
Enter an integer Q in the first line, indicating that there are Q operations.
Next Q lines, each line enters a queue operation method, the specific format is as follows:
In the initial state, the queue is empty.
Insert the end of the queue: PUSH Clear the queue: CLEAR
11 The operation is guaranteed to be any one of the above five types.


Output description:

For each set of test data:

If the operation is "remove the head of the team", output the head element of the team, if it cannot be taken out, output " -1"

If the operation is "delete queue head", if it cannot be deleted, output "-1"
If the operation is "queue size", output the queue size

No need to output other operations


Example input

2

7

PUSH 1
PUSH 2

TOP
POP
TOP
POP
POP
5
PUSH 1
PUSH 2
SIZE
POP
SIZE


Result:

1

2

-1
2

1


Question Answer

This question is not difficult. You can use LinkedList to achieve the above operations. Of course, Queue The underlying implementation is originally LinkedList.

The reason why I list this question is because this question will cause the problem of nextLine() reading failure, because we first need to read the integer variable T, and then read it line by line. If it is not processed, Newline character problems will cause the program to run abnormally.

My AC answer:

import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc =new Scanner(System.in);
        int t=sc.nextInt();
        while(t>0){
            int q=sc.nextInt();
            List<Integer> n=new LinkedList<>();
            for(int i=0;i<=q;i++){//注意!i<=q,这里的‘=&#39;就是因为q和第一行输入之间的换行符
                String s=sc.nextLine();
                if(s.equals("")){//在这道题中,当我读取到换行符时,直接跳过,不做任何操作
                    continue;
                }
                if(s.startsWith("PUSH")){
                    n.add(Integer.parseInt(s.split(" ")[1]));
                }
                else if(s.equals("TOP")){
                    if(n.size()==0){
                        System.out.println(-1);
                    }
                    else
                        System.out.println(n.get(0));
                }
                else if(s.equals("POP")){
                    if(n.isEmpty()){
                        System.out.println(-1);
                    }
                    else
                        n.remove(0);
                }
                else if(s.equals("SIZE")){
                    System.out.println(n.size());
                }
                else if(s.equals("CLEAR")){
                    n.clear();
                }
            }
            t--;
        }
    }
}
Copy after login

In the above code, I first noticed the newline character between q and the following input using

for(int i=0;i<=q;i++)
Copy after login

.

After that, when a newline character is encountered:

String s=sc.nextLine();
if(s.equals(""))
    continue;
Copy after login

to solve the problem.

The above is the detailed content of How to solve the problem of reading carriage return in Scanner.nextLine() in Java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template