Java Scanner String input

谁都会走 提交于 2019-11-27 20:09:18

When you read in the year month day hour minutes with something like nextInt() it leaves rest of the line in the parser/buffer (even if it is blank) so when you call nextLine() you are reading the rest of this first line.

I suggest you call scan.nextLine() before you print your next prompt to discard the rest of the line.

ajas

When you read in the year month day hour minutes with something like nextInt() it leaves rest of the line in the parser/buffer (even if it is blank) so when you call nextLine() you are reading the rest of this first line.

I suggest you to use scan.next() instead of scan.nextLine().

    Scanner ss = new Scanner(System.in);
    System.out.print("Enter the your Name : ");
    // Below Statement used for getting String including sentence
    String s = ss.nextLine(); 
   // Below Statement used for return the first word in the sentence
    String s = ss.next();

If you use the nextLine() method immediately following the nextInt() method, nextInt() reads integer tokens; because of this, the last newline character for that line of integer input is still queued in the input buffer and the next nextLine() will be reading the remainder of the integer line (which is empty). So we read can read the empty space to another string might work. Check below code.

import java.util.Scanner;

public class Solution {

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);

    int i = scan.nextInt();
    Double d = scan.nextDouble();
    String f = scan.nextLine();
    String s = scan.nextLine();


    // Write your code here.

    System.out.println("String: " + s);
    System.out.println("Double: " + d);
     System.out.println("Int: " + i);
}

}

use this to clear the previous keyboard buffer before scanning the string it will solve your problem scanner.nextLine();//this is to clear the keyboard buffer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!