java display input in range [closed]

巧了我就是萌 提交于 2019-12-11 05:05:15

问题


Hi what was wrong with the following program? As i want it to display user input integer value in a range of 1-10, 11-20,21-30 ... 191-200 ?

public class Program
{
    /**
     * This is the main entry point for the application
     */
   public static void main(String args[]) 
{
  int a[] = new int[100];
  int i = 0; 
  Scanner in = new Scanner(System.in);
  while(i<100)
  {
  System.out.println("Enter a int");
  a[i] = in.nextInt();
  displayStatistics(a[i]);


  }

}

    public static void displayStatistics(integer[] a[i])
    {
        if(a[i]>=1 && a[i]<=100) 
      {
        i++;
        System.out.println();  ----> need to display in range 1-10, 11-20,21-30 ... 191-200
      } else {
      System.out.println("Integer not in range of 1-200");
      }
    }
}

回答1:


public static void displayStatistics(int k)
    {
        if(k>=1 && k<=200) 
      {
        int low,high;
        if(k%10==0)
        {
            low=k-9;
            high=k;
        }
        else 
        {
            low=k-k%10+1;
            high=k-k%10+10;
        }
        System.out.println("value in range " +low+" -"+high); 

      } else {
      System.out.println("Integer not in range of 1-200");
      }
    }

Remember that you are passing an integer to the function , not the complete array




回答2:


You must get compiler error from the above code. Change the method

public static void displayStatistics(int a) {
    if (a >= 1 && a <= 100) {
        System.out.println("Input[" + a + "] is within the range 1 to 100");
    } else {
        System.out.println("Integer not in range of 1-200");
    }
}

Similarly you can add else if for another range check.



来源:https://stackoverflow.com/questions/13284372/java-display-input-in-range

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!