Java: Check if an array of integers without two specified numbers
30. Check if array excludes 0 and -1
Write a Java program to check if an array of integers is without 0 and -1.
Pictorial Presentation:
Sample Solution:
Java Code:
// Import the java.util package to use utility classes, including Arrays.
import java.util.*;
// Import the java.io package to use input and output classes.
import java.io.*;
// Define a class named Exercise30.
public class Exercise30 {
// The main method for executing the program.
public static void main(String[] args) {
// Declare and initialize an array of integers.
int[] array_nums = {50, 77, 12, 54, -11};
// Print the original array.
System.out.println("Original Array: " + Arrays.toString(array_nums));
// Call the test method with the array as an argument and print the result.
System.out.println("Result: " + test(array_nums));
}
// Define a method named test that takes an array of integers as input.
public static boolean test(int[] numbers) {
// Use an enhanced for loop to iterate through the array elements.
for (int number : numbers) {
// Check if the current number is 0 or -1.
if (number == 0 || number == -1) {
// If any number is 0 or -1, return false.
return false;
}
}
// If no number is 0 or -1, return true.
return true;
}
}
Sample Output:
Original Array: [50, 77, 12, 54, -11] Result: true
Flowchart:
For more Practice: Solve these Related Problems:
- Write a Java program to check if an array contains only prime numbers.
- Write a Java program to check if an array contains only even numbers.
- Write a Java program to check if an array contains only numbers greater than a specified value.
- Write a Java program to check if an array contains no duplicates.
Go to:
Java Code Editor:
PREV : Average excluding max and min.
NEXT : Check if total of 10s equals 30.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.