Java:使用相同的扫描程序变量来存储多组条目

时间:2014-02-22 04:41:13

标签: java

有没有办法使用相同的提示但是再次存储用户数据而不创建第二个变量?这一切都需要在时尚表格中同时显示(因此标签)

//Variables
        Scanner user = new Scanner(System.in);
        NumberFormat percent = NumberFormat.getPercentInstance();
        int num = 1;
        int group = 10, string = 12, formatting = 8;



        while (num <= 3)

        {




        System.out.print("Please enter name of assignment 1: ");
        String assignment = user.nextLine().toUpperCase();
        System.out.print("Please enter points earned: ");
        double earned = user.nextDouble();
        System.out.print("Please enter total points possible: ");
        double total = user.nextDouble();

        }

    System.out.print(assignment + "\t\t"); 
    System.out.print(earned + "\t"); 
    System.out.print(total + "\t\t"); 
    System.out.print(percent.format(earned / total) + "\n\t");


 when looping it is skipping the "Please enter name of assignment prompt:

    Please enter name of assignment 2: Please enter points earned: 



I expected the output to be:

    Please enter name of assignment 1: Practice Exam
    Please enter points earned: 89
    Please enter total points possible: 125

    Please enter name of assignment 2: FooBar
    Please enter points earned: 42

1 个答案:

答案 0 :(得分:0)

你正在消费这些数字,但你没有消费新行

试试这个

    String assignment;
    String exit=null;
    double earned, total;
    int i = 0;
    Scanner scan = new Scanner(System.in);

    while (!"Y".equalsIgnoreCase(exit)) {
        i++;
        System.out.print("Please enter name of assignment " + i + ": ");
        assignment = scan.nextLine().toUpperCase(); //consumes string + \n
        System.out.print("Please enter points earned: ");
        earned = scan.nextDouble();//consumes double
        scan.nextLine();//consumes \n
        System.out.print("Please enter total points possible: ");
        total = scan.nextDouble();
        scan.nextLine();

        System.out.print("Assignment\t");
        System.out.print("Score\t");
        System.out.print("Total       Points\t");

        System.out.print(assignment + "\t\t");
        System.out.print(earned + "\t");
        System.out.println(total + "\t\t");

        System.out.print("Stop?(Y/N)");
        exit = scan.nextLine();
    }

返回

Please enter name of assignment 1: 1
Please enter points earned: 1
Please enter total points possible: 1
Assignment  Score   Total       Points  1       1.0 1.0     
Stop?(Y/N)n
Please enter name of assignment 2: 2
Please enter points earned: 2
Please enter total points possible: 2
Assignment  Score   Total       Points  2       2.0 2.0     
Stop?(Y/N)y