nextLine一次打印2个?

时间:2017-03-03 04:21:56

标签: java java.util.scanner

所以一切都编译得很好但是当我运行它时,要求城市的线和要求拉链的线同时打印出来。我需要它们单独打印,以便用户可以回答。

import java.util.Scanner;
public class PersonalInfo
{
   public static void main(String[] args)
   {
     String name, city, state, major;
     int zip, phone, address;

     Scanner scanner = new Scanner(System.in);

     System.out.println("Please enter your name: ");
     name = scanner.nextLine();

     System.out.println("please enter your address number: ");
     address = scanner.nextInt();

     System.out.println("Please enter the name of the city you live in: ");
     city = scanner.nextLine();

     System.out.println("Please enter your zip code: ");
     zip = scanner.nextInt();

     System.out.println("Please enter the name of the state you live in: ");
     state = scanner.nextLine();

     System.out.println("Please enter your phone number(format ##########): ");
     phone = scanner.nextInt();

     System.out.println("Please enter your college major: ");
     major = scanner.nextLine();

     System.out.println(name + "\n" + address + "," + city + "," + state +
                        "," + zip + "\n" + phone + "\n" + major);
   }
}

1 个答案:

答案 0 :(得分:0)

消费输入换行符的唯一方法是nextLine(),因此,如果您使用nextInt(),然后想要捕获其他任何内容,则必须在调用nextLine()后调用nextInt() {1}}。

例如:

System.out.println("please enter your address number: ");
address = scanner.nextInt();

scanner.nextLine();

System.out.println("Please enter the name of the city you live in: ");
city = scanner.nextLine();

输出:

please enter your address number: 
567
Please enter the name of the city you live in: 
Puerto Montt