扫描仪:如何在我的代码中在此处限制用户输入?

问题描述 投票:0回答:1

我一直在获得有关此代码的帮助,但仍然不明白。用户最多只能输入1000,但是在此代码中,即使他输入1001,该代码仍会继续并询问另一个不需要的问题。另一件事,如何使这段代码更短,更容易理解?

是否有其他方法可以用“ private static”和“ return”替换零件,我已经编辑了一些代码,并且工作正常。但是,那是唯一的问题。对不起,我上周刚刚学习了Java,但现在仍然不了解它。非常感谢你的帮助! :)

import java.util.Scanner;

import java.util.Arrays;

  public class Main {


  private static boolean isEven(double n) {
  return n % 2 == 0;
 }


private static int numOfOdd(double[] array) {
int count = 0;
for (double i : array) {
    if (!isEven(i)) {
        count++;
    }
}
return count;
}


private static int numOfEven(double[] array) {
int count = 0;
for (double i : array) {
    if (isEven(i)) {
        count++;
    }
  }
return count;
  }

      public static void main(String[] args) {

Scanner input = new Scanner(System.in);


int size;
while (true) {
    System.out.println("Enter the size of an array: ");
    size = input.nextInt();
    if (size < 0 || size > 1000) {
        System.out.println("Size must be between 0 and 1000");
    } else {
        break;
    }
  }


double[] original = new double[size];
for (int i = 0; i < size; i++) {
    System.out.println("Enter value:");
    original[i] = input.nextInt();
}

 double[] odds = new double[numOfOdd(original)]; 

double[] evens = new double[numOfEven(original)];


int indexOdd = 0;
int indexEven = 0;
for (double i : original) {
    if (isEven(i)) {
        evens[indexEven] = i;
        indexEven++;
    } else {
        odds[indexOdd] = i;
        indexOdd++;
    }
}


     System.out.println("Original: " + Arrays.toString(original));
     System.out.println("Odd: " + Arrays.toString(odds));
     System.out.println("Even: " + Arrays.toString(evens));
   }
 }
java arrays java.util.scanner
1个回答
0
投票

如果您希望程序在用户输入大于1000或小于0的数字后停止,则需要在break条件下添加if语句。

if (size < 0 || size > 1000) {
    System.out.println("Size must be between 0 and 1000");
    break;
}
© www.soinside.com 2019 - 2024. All rights reserved.