[英]How can I pick out the odd numbers and even numbers from a given array and then store them in another array?
[英]array error how many odd and even numbers in given terms
public class NewClass
{
public static void main(String[] args)
{
int n = 0;
int EvenNo;
int OddNo;
Scanner sc = new Scanner(System. in);
System.out.println("How many numbers will be entered?");
n = sc.nextInt();
int a[]=new int[n];
//I think Im missing some code here
System.out.println("Enter " + n + " Elements Separated by Space >> " );
String input;
input = sc. nextLine();
String[] tokens = input.split(" ");
int[] inputNumbers = new int[tokens.length];
EvenNo = OddNo = 0;
for(int i = 0; i < tokens.length; i++)
{
inputNumbers[i] = Integer.parseInt(tokens[i]);
if(inputNumbers[i] % 2 == 0 && inputNumbers[i] != 0)
EvenNo++;
else if(inputNumbers[i] % 2 != 0)
OddNo++;
}
System.out.print("\n");
System.out.println("The number of Even Numbers >> " + EvenNo);
System.out.print("The number of Odd Numbers >> " + OddNo);
}
}
您应该使用Integer.parseInt()
将扫描仪输入的字符串格式转换为 integer
....
System.out.println("How many numbers will be entered?");
n = Integer.parseInt(sc.nextLine());
...
这是问题所在。 你有这个...
System.out.println("How many numbers will be entered?");
n = sc.nextInt();
...后来是这个...
input = sc. nextLine();
长话短说, nextLine()
不能很好地与扫描仪的其他next***()
方法配合使用。 您可以在此处阅读更多信息 - https://stackoverflow.com/a/13102066/10118965
解决您的问题的最简单方法是执行此操作
System.out.println("How many numbers will be entered?");
n = sc.nextInt();
sc.nextLine();
这可能是解决这个问题的最不痛苦的方法。 但是在未来,如果你只使用nextLine()
就可以完全避免这个问题。 这些方便的方法很好,但是如您所见,如果您不了解它们的特殊细微差别,它们可能会给您带来麻烦。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.