Java 如何找到单个数字的数组元素
在给定的数组中,包含一些随机整数值,我们需要找出给定数组中可用的单个数字,并将这些单个数字输出。
数组可以包含正数或负数,无论数字的位数如何。因为这里的所有元素都属于数字类型。
注意- 取一个正整数数组。
让我们深入研究本文,了解如何使用Java编程语言来完成它。
为了向您展示一些实例
实例-1
给定的数组= [1, 12, 3, 4, 10, 15]。
给定数组中的单个数字元素= 1, 3, 4
实例-2
给定的数组= [451, 102, 3, 14, 100, 15]。
给定数组中的单个数字元素= 3
实例-3
给定的数组= [111, 612, 83, 4, 10, 5, 9, 89]。
给定数组中的单个数字元素= 4, 5, 9
步骤
步骤-1
步骤1 - 通过静态输入方法声明一个包含一些随机整数值的数组。
步骤2 - 使用for循环,检查数字是否介于0和9之间的条件。
步骤3 - 如果条件满足,则确认该数字是一个单个数字。
步骤4 - 将这些单个数字作为输出打印出来。
步骤-2
步骤1 - 通过静态输入方法声明一个包含一些随机整数值的数组。
步骤2 - 开始一个循环,检查数字的模10的余数与该数字本身是否相等。这表明该数字是一个单个数字。
步骤3 - 如果条件满足,则确认该数字是一个单个数字。
步骤4 - 将这些单个数字作为输出打印出来。
多种方法
我们以不同的方法提供了解决方案。
- 使用简单的数字检查方法
-
使用模数检查方法
让我们逐个查看程序及其输出。
方法1:使用简单的数字检查方法
在这种方法中,我们声明一个包含一些随机整数值的数组,并使用我们的算法找到单个数字,并将这些数字作为输出打印出来。
示例
public class Main {
public static void main (String[] args) {
//declare an integer type array
//and store some random positive integer values
int inputArray[] = {7, 12, 5, 9, 15};
//declare an integer value for counting single digit elements
//and initialize it with 0
int count = 0;
System.out.print ("Single digit elements present in array are: ");
//initiate the loop to find the single digits
for (int i = 0; i < inputArray.length; i++) {
//take a for loop to check every values
if (inputArray[i] >= 0 && inputArray[i] <= 9){
//If the number satisfied above condition
//its a single digit number so print that number
System.out.print(inputArray [i] + " ");
//increment the count value if any single digit found
count+=1;
}
}
//if no single digit detected
if(count==0){
//print not available as output
System.out.print(" N/A ");
}
}
}
输出
Single digit elements present in array are: 7 5 9
方法2:使用取模检查方法
在这种方法中,我们声明一个包含一些随机整数值的数组,并通过使用我们的算法找到单个数字,并将这些数字作为输出打印出来。
示例
public class Main {
public static void main (String[] args) {
//declare an integer arrays and store some random +ve integer values
int inputArray1[] = {20, 12, 33, 2, 11, 3};
//declare an integer value for counting single digit
//initialize it with value 0
int count = 0;
System.out.print ("Single digit elements present in the array are: ");
//take a for loop to find the single digits in first array
for (int i = 0; i < inputArray1.length; i++) {
//in each loop find the modulus value with 10
//so that we can find the single digit value
if (inputArray1[i] % 10 == inputArray1[i]){
//If the number satisfied above condition its a single digit number
System.out.print(inputArray1 [i] + " ");
//increment the count value if any single digit found
count+=1;
}
}
//if no single digit detected
if(count==0){
//print not available as output
System.out.print(" N/A ");
}
}
}
输出
Single digit elements present in the array are: 2 3
在本文中,我们使用Java编程语言探讨了在数组中查找单个数字元素的不同方法。