Answer the question
In order to leave comments, you need to log in
How does the nextLine() method work in the Scanner class?
Wrote a little program:
import java.util.*;
public class inputtest1
{
public static void main(String[] args)
{
Scanner ott = new Scanner(System.in);
// объявлена константа сколько сантиметров в дюйме
final double CM_PER_INCH = 2.54;
// объявлены переменные: ширина листа, высота листа, исполнитель
double paperWidth;
double paperHeigth;
String name;
// получить от пользователя значения ширины и высоты листа в дюймах
System.out.print("Введите ширину листа в дюймах: ");
paperWidth = ott.nextDouble();
System.out.print("Введите высоту листа в дюймах: ");
paperHeigth = ott.nextDouble();
// получить от пользователя его фамилию
System.out.print("Введите свою фамилию: ");
name = ott.nextLine();
// программа выводит сообщение о размерах листа и фамилию исполнителя
System.out.println("Размеры листа в сантиметрах: "
+ paperWidth * CM_PER_INCH + " на " + paperHeigth * CM_PER_INCH
+ " сантиметров");
System.out.println("Данные вводил инженер: " + name);
}
}
System.out.print("Введите свою фамилию: ");
name = ott.nextLine();
Answer the question
In order to leave comments, you need to log in
nextLine() reads to the end of the current line (newline or end-of-stream) and returns whatever was on that line.
nextDouble() reads double. It doesn't read or skip anything AFTER the double.
So you enter something like "3.15\n", where \n is the newline character.
nextDouble() extracts 3.14 and leaves "\n" in the buffer.
nextLine() encounters \n and exits after reading 0 characters - an empty line.
Check: type "1 2 Ivanov" in one line and it will work (True, the space before Ivanov will be read as part of the last name)
It's fashionable to call nextLine() to absorb this line break and wait for a newline.
Faced a similar problem.
Instead of nextLine() I used next().
Earned normally.
Scanner methods are well described here in this article https://vertex-academy.com/tutorials/ru/rabota-so-...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question