Home > Java > body text

I don't know how to fix the nextLine issue and make it work

WBOY
Release: 2024-02-09 11:54:30
forward
1142 people have browsed it

During the development process, we often encounter various problems, and sometimes even seemingly simple problems can leave us at a loss. For example, you may encounter a problem that bothers you, which is how to solve the nextLine problem and make it work properly. Don't worry, PHP editor Xinyi is here to provide you with some methods and techniques to solve this problem, hoping to help you solve this problem. Here we take a look!

Question content

do {
        System.out.println("write in format \"firstname lastname\"");
            
        //just want to scan a sentence with spaces
        String[] tempArr = sc.nextLine().split(" ");
            
        System.out.println("Hello " + tempArr[0]);

        System.out.println("Do you want to do it again Y/N");

    }while(sc.next().equals("Y"));
Copy after login

I don't know how to prevent the next row scanner from scanning whitespace after the first iteration

I want the loop to run until anything other than "y" is entered

Workaround

I would not use a do...while loop for this. You can easily do this by creating an infinite loop that stops if the answer is not "y". I'm assuming you want to loop over user input y and stop anything else. If it's the other way around, just flip the boolean value in the if statement. Try something like this:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (true) {
            System.out.println("write in format \"firstname lastname\"");
            String[] tempArr = sc.nextLine().split(" ");
            System.out.println("Hello " + tempArr[0]);
            System.out.println("Do you want to do it again Y/N");
            String answer = sc.nextLine();
            if (!answer.equalsIgnoreCase("Y")) {
                break;
            }
        }
    }
}
Copy after login

The above is the detailed content of I don't know how to fix the nextLine issue and make it work. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.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