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!
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"));
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
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; } } } }
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!