Scanner doesn't read whole sentence - difference between next() and nextLine() of scanner class

后端 未结 22 1091
北荒
北荒 2020-12-03 01:14

I\'m writing a program which allows the user to input his data then outputs it. Its 3/4 correct but when it arrives at outputting the address it only prints a word lets say

相关标签:
22条回答
  • 2020-12-03 02:09

    Default delimiter of Scanner is whitespace. Check javadoc for how to change this.

    0 讨论(0)
  • 2020-12-03 02:09
    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 s="";
            while(scan.hasNext())
            {
                s=scan.nextLine();
            }
    
            System.out.println("String: " +s);
            System.out.println("Double: " + d);
            System.out.println("Int: " + i);
        }
    }
    
    0 讨论(0)
  • 2020-12-03 02:09

    To get the whole adress add

    s.nextLine();//read the rest of the line as input
    

    before

    System.out.println("Enter Your Address: ");
    String address = s.next();
    
    0 讨论(0)
  • 2020-12-03 02:10
    import java.util.Scanner;
    
    public class Solution {
    
        public static void main(String[] args) {
            Scanner scan = new Scanner(System.in);
            String s = scan.next();
            s += scan.nextLine();
            System.out.println("String: " + s);
    
        }
    }
    
    0 讨论(0)
提交回复
热议问题