Java Skip Iteration 0

时间:2013-12-26 08:43:10

标签: java console-application

我是Java控制台的新手。

for (i=0;i<=noOfSP;i++)
    {
        System.out.println("NAME OF THE Plan #" + i + "?:  'Example input: 4GB' ");
        nameOfPlan = scn.nextLine();
        SubscriptionPlan subscriptionPlan = new SubscriptionPlan(nameOfPlan);
        if ( !gsmProvider.addSubscriptionPlan(subscriptionPlan) )
        {
            System.out.println("Adding Error. Program Will Closing.");
            System.exit(1);
        }
    }

在这个代码块中我想读名字。我从用户类型的Integer中读取“noOfSP”。但是迭代0不起作用?如果noOfSP为0,程序会跳过循环吗?为什么?

编辑: 我在for循环中编辑。好的但仍然无法读取0.迭代。

  

订购计划的数量? :'示例输入:1'   1   计划名称#0?:'示例输入:4GB'   计划名称#1?:'示例输入:4GB'

跳过0.迭代?为什么?

3 个答案:

答案 0 :(得分:1)

这是您的解决方案。变化

nameOfPlan = scn.nextLine();

nameOfPlan = new Scanner(System.in).nextLine();

为什么?

当您输入任何值并按Enter键时,新行字符将附加到输入的末尾。在您的情况下,当您按Enter键输入noOfSP值时,默认会附加换行符(/n)。

由于您使用scn.nextInt() noOfSP值(最有可能),因此只能获取int,并且仍有新行字符(\n) 。 您的第一个for循环迭代(迭代0)获取\n因此,在第一次迭代中跳过scn.nextLine()

注意:您也可以在scn.nextLine();循环之前添加for来解决此问题:

....
scn.nextLine();
for (i=0;i<=noOfSP;i++){
    .....

答案 1 :(得分:0)

至于循环说我的值应该小于noOfSP,这就是它跳过循环的原因。 将循环更改为

for (i=0;i<=noOfSP;i++)

答案 2 :(得分:0)

如果i = 0并且noOfSP在开始时为0,则(0 <0)将返回假
请改用:

for(i=0; i<=noOfSP;i++)