Java Scanner String input

前端 未结 5 1270
遇见更好的自我
遇见更好的自我 2020-12-05 11:02

I\'m writing a program that uses an Event class, which has in it an instance of a calendar, and a description of type String. The method to create an event uses a Scanner t

相关标签:
5条回答
  • 2020-12-05 11:15

    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);
        }
    }
    
    0 讨论(0)
  • 2020-12-05 11:15

    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

    0 讨论(0)
  • 2020-12-05 11:16

    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().

    0 讨论(0)
  • 2020-12-05 11: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.

    0 讨论(0)
  • 2020-12-05 11:30
        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();
    
    0 讨论(0)
提交回复
热议问题