输入扫描器不正确

时间:2013-10-27 11:25:18

标签: java arraylist

嘿,我试图从用户那里逐一接受输入,但它似乎接受了错误的输入......它实际上跳过了一个输入来自用户... 例如..在下面的代码中我想首先取名字然后是地址和最后一次联系,但是当我这样做时它会跳过名字输入......

import java.util.ArrayList;
import java.util.Scanner;
public class mainClass {
    public static void main(String args[]){

        int value = 0;
        ArrayList<Data> Contacts = new ArrayList<Data>();
        Scanner input = new Scanner(System.in);
        while(true){
            System.out.println("Enter 1  to add a Contact :: Enter 2  to View all Contact");
            value = input.nextInt();

            switch(value){

            case 1:

                System.out.println("Plz enter Name : ");
                String name = input.nextLine();
                System.out.println("Plz enter Address : ");
                String address = input.nextLine();
                System.out.println("Plz enter ContactNo : ");
                String contact = input.nextLine();

                Data objt1 = new Data(name, address, contact);
                Contacts.add(objt1);

                break;
            case 2:

                System.out.println("Name\t\tContact\t\tAddress");

                for(int i=0; i<Contacts.size(); i++)
                {

                    System.out.println(Contacts.get(i));
                }

                break;
            default:
                System.out.println("Sorry wrong input");

            }



        }
    }
}

数据类在这里

public class Data {

        private String name = "";
        private String address = "";
        private String cell = "";


        public Data(String n, String a, String c){

            name = n;
            address = a;
            cell = c;
        }

        public String toString()
        {
            return String.format("%s\t\t%s\t\t%s", name, cell, address);
        }
}

1 个答案:

答案 0 :(得分:0)

尝试在获取值后添加input.nextLine();,这将使用新的行字符

value = input.nextInt();
input.nextLine();

(或)

int value = Integer.parseInt(input.nextLine());