编程要求输入两次

时间:2012-11-19 05:33:44

标签: java methods boolean-operations

我对这个程序的开头遇到了一些麻烦。 它应该取一个数字并确定它是否完美。 目前我要询问要检查多少个数字,每当我输入任何正数时,它再次询问。 并且,每当我输入第二个问题的负数时,程序结束并且不再提示。 关于如何解决这个问题的任何想法?

import java.util.Scanner;

public class aermel_Perfect
{
public static void main ( String args [] )
{
    int gN = getNum();
    int gP = getPerfect();
}


public static int getNum() //Get amount of numbers to check
{
Scanner input = new Scanner ( System.in );
System.out.print( "How many numbers would you like to test? " );
int count = input.nextInt();
int perfect = 1;
boolean vN = validateNum(count, perfect);
return count;
}   

public static boolean validateNum( int count, int perfect  ) //Check if number is valid
{
if (( count <= 0) || ( perfect <= 0))

{ 
    System.out.print( "Non-positive numbers are not allowed.\n");
}



else 
{
    return true;
}
return false;


}
public static int getPerfect() //Gets the numbers to test
{
Scanner input = new Scanner ( System.in );
int perfect = -1;
int count = getNum();
System.out.print("Please enter a perfect number: " );
perfect = input.nextInt();
boolean vN = validateNum(perfect, count);
return perfect;
}
}

2 个答案:

答案 0 :(得分:0)

int count = getNum();
System.out.print("Please enter a perfect number: " );
perfect = input.nextInt();

你在这里得到两个号码。

答案 1 :(得分:0)

while方法中使用get循环,例如在输入有效数字之前反复询问输入。

    public static int getNum() //Get amount of numbers to check
    {
      Scanner input = new Scanner ( System.in );
      System.out.print( "How many numbers would you like to test? " );
      int count = input.nextInt();
      int perfect = 1;
      boolean vN = validateNum(count, perfect);
      while(!vN ){
          System.out.println("Invalid input. Try again");
          count = input.nextInt();
          vN = validateNum(count, perfect);
      }
      return count;
    } 

Simiilarly,更新getPerfect方法并从此方法中删除int count = getNum();语句。

编辑:要反复询问完整号码count次,请按以下步骤更新您的主要方法:

   public static void main ( String args [] )
   {
      int gN = getNum();
      for(int indx=0; indx <gN; indx++){
         int gP = getPerfect();
         //use your gP numbers in the way you want
      }
   }

EDIT1:要拨打How many numbers would you like to test? "两次,我认为您只需在主方法中拨打getNum()方法两次,如下所示:

   public static void main ( String args [] )
   {
      int gN = getNum();//first call
      gN = getNum(); //second call
      int gP = getPerfect();
   }