如何在继续之前等待输入?

时间:2014-02-01 02:18:42

标签: java input

import java.util.Scanner;
class bazar
{
    void calculate ()
    {
        int sum=0;
        Scanner sc = new Scanner (System.in);
        System.out.println("Hi ! welcome to out advance calculator");
        System.out.println("Enter the number of items that you wish to compute");
        int c = sc.nextInt();
        String item[] = new String[c];
        int price[] = new int[c];
        for (int i=1; i<=c; i++)
        {
          System.out.println( "please enter the item name : " );
          item[i] = sc.nextLine();
          System.out.println();**// i need to wait for input before proceeding**
          System.out.println();
          System.out.println();
          System.out.println( "please enter the price of " +item[i]+":");
          price[i] = sc.nextInt();
          sum=sum+price[i];
        }
        //display part 
        for (int k=1; k<=c; k++)
        {
            System.out.println(  "ITEM                       PRICE");
            System.out.println (item[k]+"                  "+price[k]); 
        }
        System.out.println();
        System.out.println();
        System.out.println();
        System.out.println();
        System.out.println("YOUR BILL TOTAL HAS COME TO----------------->"+sum);
    }
}

2 个答案:

答案 0 :(得分:0)

在nextInt()调用之后添加对nextLine()的调用,以清除管道中nextInt()离开的剩余“\ n”。

答案 1 :(得分:0)

扫描仪nextInt()(和类似的)函数不读取用户输入字符串后输入的换行符。所以它仍然在缓冲区中。但是,当接收到新行字符时,nextLine()函数会立即返回。 要解决此问题,请确保没有任何换行符留在缓冲区中。最快的方法是在每次调用nextInt()和类似函数后使用nextLine()调用。 或者避免使用nextLine()并使用next()函数。但它无法读取多字串。

相关问题