不等待输入java

时间:2013-03-22 10:31:44

标签: java java.util.scanner

我有一个程序应该采用整数输入,根据输入输出一些字符,然后提示再次运行程序。 E.g。

Please enter an integer --> 3

x

xx

xxx

xx

x

Do you want to run again?

这是我的程序的代码:

import java.util.*;
public class CMIS242Assignment1Stars 
{
    public static void main(String[] args) 
    {
        String again;

       do //start of "run again" loop
        {
            System.out.print("Input a positive integer and press [ENTER]--> ");
            Scanner input = new Scanner(System.in);

            if (input.hasNextInt()) // check if input is parsable to an int
            {        
                int num = Integer.parseInt(input.next());

                if (num <= 0) //check if num is positive
                {
                    System.out.println(num + " is not a positive integer. Using +" + (num*-1) + " instead.");
                    num = num *= -1;
                }    
                String stars = new String(new char[num]).replace("\0", "*"); // create a string of '*' of length 'num'
                int forNum = num * 2;
                int flip = 0;

                for (int x = 0; x <= forNum ; x++)
                {
                    System.out.println(stars.substring(0,stars.length() - num)); //create substrings of variable length from 'stars'

                    if(num <= 0)
                    {
                        flip = 1;
                    }

                    if(flip == 0)
                    {
                        num--;
                    }
                    else
                    {
                        num++;
                    }
                }
            }           
            else 
            {
                System.out.println("ERROR: Please input a positive integer!");//error message if a non-integer is entered
            }

            System.out.print("Would you like to run again? [Yes / No] ");
            again = input.next();     
        }
        while(again.equalsIgnoreCase("yes") || again.equalsIgnoreCase("y")); // end of "run again" loop

        System.out.print("Good Bye!"); //exit message        
    }
}

我认为问题在于确保输入正确的代码。如果输入了int或者负int,那么程序可以正常工作,但是当输入非int时,程序不会等待“再次运行”提示。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

你需要稍微修改一下你的逻辑。

最简单的解决方案是修复你的其他声明。

else 
{
  //Move scanner position.
  String badInput = input.next();
  System.out.println("ERROR: Please input a positive integer!");//error message if a non-integer is entered
}

您检查是否input.hasNextInt()但是它没有,控制台有一些不是整数的东西。使用hasNextInt()时,hasNextInt()方法实际上不会移动扫描仪位置。要解决此问题,我们在else语句中使用input.next()