-2

我有一个程序应该接受整数输入,根据输入输出一些字符,然后提示再次运行程序。例如

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 作为输入时,程序不会等待“再次运行”提示。我怎样才能解决这个问题?

4

1 回答 1

1

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

对您来说最简单的解决方案是修复您的 else 语句。

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(). 为了解决这个问题,我们input.next()在 else 语句中使用了 a。

于 2013-03-22T10:48:51.253 回答