0% found this document useful (0 votes)
15 views

Solution To Practice Problems Itec 1620

The document contains code snippets for 6 Java programs that take user input and perform various tasks: 1. A program that takes 3 numbers as input and prints the greatest number. 2. A program that takes a number n as input and prints the sum of the first n numbers. 3. A program that takes an integer n as input and prints Pascal's triangle with n rows. 4. A program that takes two strings as input and checks if they contain the same characters. 5. A program that takes a string as input and counts the vowels and consonants. 6. The document prompts for a complete Java program but does not provide any code.

Uploaded by

komal khetpal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Solution To Practice Problems Itec 1620

The document contains code snippets for 6 Java programs that take user input and perform various tasks: 1. A program that takes 3 numbers as input and prints the greatest number. 2. A program that takes a number n as input and prints the sum of the first n numbers. 3. A program that takes an integer n as input and prints Pascal's triangle with n rows. 4. A program that takes two strings as input and checks if they contain the same characters. 5. A program that takes a string as input and counts the vowels and consonants. 6. The document prompts for a complete Java program but does not provide any code.

Uploaded by

komal khetpal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Question Code Explanation

Take three numbers from the user import java.util.Scanner; In this program, we have declared three variables `num1`, `num2`, and `num3` to store the three numbers
as input and print the greatest entered by the user. We have also declared a variable `greatest` to store the greatest number.
number. Write a complete Java public class GreatestNumber {
program public static void main(String[] args) { Then we have used the `Scanner` class to read the user input for the three numbers.
Scanner input = new Scanner(System.in);
Next, we have used conditional statements to compare the three numbers and store the greatest number in the
System.out.print("Enter the first number: "); `greatest` variable.
int num1 = input.nextInt();
Finally, we have printed the greatest number using the `System.out.println()` method.
System.out.print("Enter the second number: ");
int num2 = input.nextInt(); When we run this program, it prompts the user to enter three numbers, and then prints the greatest number
among them.
System.out.print("Enter the third number: ");
int num3 = input.nextInt();

int greatest = num1;

if (num2 > greatest) {


greatest = num2;
}

if (num3 > greatest) {


greatest = num3;
}

System.out.println("The greatest number is: " + greatest);


}
}
Take the number n as input and import java.util.Scanner; In this program, we first take the input for the value of n using Scanner class. We initialize the variable sum to 0
print the sum of first n numbers. and use a for loop to calculate the sum of first n numbers by adding each number to the sum variable. Finally,
Write a complete Java program public class SumOfNumbers { we print the sum using System.out.println statement. The Scanner class is closed at the end of the program.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the value of n: ");
int n = sc.nextInt();
int sum = 0;
for (int i=1; i<=n; i++) {
sum += i;
}
System.out.println("The sum of first " + n + " numbers is " + sum);
}
}
Take an integer n as input and import java.util.Scanner;
display Pascal's triangle. Write a
complete Java program. public class PascalTriangle {
public static void main(String[] args)
{
int no_row,c=1,blk,i,j;
System.out.print("Input number of rows: ");
Scanner in = new Scanner(System.in);
no_row = in.nextInt();
for(i=0;i<no_row;i++)
{
for(blk=1;blk<=no_row-i;blk++)
System.out.print(" ");
for(j=0;j<=i;j++)
{
if (j==0||i==0)
c=1;
else
c=c*(i-j+1)/j;
System.out.print(" "+c);
}
System.out.print("\n");
}
}
}
Write a complete Java Program that import java.util.Scanner;
will take two Strings as input and
check if all characters in both public class StringComparator {
string are same or not. If same, print
“similar”, otherwise, print “dissimilar” public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first string: ");
String string1 = scanner.next();
System.out.print("Enter the second string: ");
String string2 = scanner.next();

if (areStringsSimilar(string1, string2)) {
System.out.println("similar");
} else {
System.out.println("dissimilar");
}
}

public static boolean areStringsSimilar(String string1, String string2) {


if (string1.length() != string2.length()) {
return false;
}
int[] characterCount = new int[26]; // There are 26 lowercase English letters
for (int i = 0; i < string1.length(); i++) {
char ch = string1.charAt(i);
characterCount[ch - 'a']++;
}
for (int i = 0; i < string2.length(); i++) {
char ch = string2.charAt(i);
characterCount[ch - 'a']--;
}
for (int i = 0; i < 26; i++) {
if (characterCount[i] != 0) {
return false;
}
}
return true;
}
}
Write a complete Java Program that import java.util.Scanner;
will take a String as input and prints
how many vowels and public class CountVowelsConsonants {
consonants in that string. public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a string: ");
String string = input.nextLine();
int vowels = 0, consonants = 0;
for (int i = 0; i < string.length(); i++) {
char ch = string.charAt(i);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'A' || ch == 'E' || ch ==
'I' || ch == 'O' || ch == 'U') {
vowels++;
} else if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) {
consonants++;
}
}
System.out.println("Number of vowels in the string: " + vowels);
System.out.println("Number of consonants in the string: " + consonants);
}
}
Write a complete Java program to import java.util.Scanner; The program starts by asking the user for the length of the array, and then reads in the values for each element
compute the average value of an of the array. It then sorts the array using a simple bubble sort algorithm. Finally, it calculates the sum of all
array of integers except the largest public class ArrayAverage { elements except the first and last elements (which are the smallest and largest values) and divides it by the
and public static void main(String[] args) { number of elements minus 2 to get the average.
smallest values. Scanner input = new Scanner(System.in);
int n = input.nextInt(); Note that we've cast the sum to a double to ensure that the division is done with floating-point arithmetic, which
int[] arr = new int[n]; will give us a more accurate result.

for (int i = 0; i < n; i++) {


arr[i] = input.nextInt();
}

// sort the array


for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (arr[i] > arr[j]) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}

// compute the average


int sum = 0;
for (int i = 1; i < n - 1; i++) {
sum += arr[i];
}
double average = (double) sum / (n - 2);

System.out.println("The average of the array, excluding the smallest and largest


values, is: " + average);
}
}
Write a complete Java program that import java.util.*; In this program, we use the `Scanner` class to take input from the user as an array of 10 numbers. We then
will take an array of 10 numbers as loop through the array to find the smallest and second smallest elements. We use `Integer.MAX_VALUE` as a
input and find the smallest and public class SmallestNumbers { starting value for both variables to ensure that any number in the array will be smaller than them. We then loop
second smallest elements of that through the array and check each element against `smallest`. If it is smaller, we update `secondSmallest` to
array. public static void main(String[] args) { equal `smallest` and `smallest` to equal the current element. If the current element is not smaller than
Scanner input = new Scanner(System.in); `smallest`, we check if it is smaller than `secondSmallest` and update `secondSmallest` if it is.

// Prompt user to enter 10 numbers


int[] numArray = new int[10];
System.out.println("Enter 10 numbers:");
for (int i = 0; i < numArray.length; i++) {
numArray[i] = input.nextInt();
}

// Find the smallest and second smallest numbers in the array


int smallest = Integer.MAX_VALUE;
int secondSmallest = Integer.MAX_VALUE;
for (int i = 0; i < numArray.length; i++) {
if (numArray[i] < smallest) {
secondSmallest = smallest;
smallest = numArray[i];
} else if (numArray[i] < secondSmallest) {
secondSmallest = numArray[i];
}
}

// Print the smallest and second smallest numbers


System.out.println("The smallest number is: " + smallest);
System.out.println("The second smallest number is: " + secondSmallest);
}
}
Write a complete Java program that import java.util.Scanner;
will take an array of 10 numbers as
input and find the sum of all even public class SumOfEvenNumbers {
numbers given as input. public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] numbers = new int[10];
int sum = 0;

System.out.println("Enter 10 numbers:");

for (int i = 0; i < 10; i++) {


numbers[i] = scanner.nextInt();

if (numbers[i] % 2 == 0) {
sum += numbers[i];
}
}

System.out.println("The sum of all even numbers is " + sum);


}
}
If the first two numbers of fibonacci import java.util.Scanner; In each iteration of the loop, the program adds the first and second numbers to get the nth number, and
series are 0 and 1, then take an updates the values of the first and second numbers.
integer N as input (2 < N < 30) and public class Fibonacci {
print the Nth Fibonacci Number. public static void main(String[] args) {
Write a complete Java program. Scanner sc = new Scanner(System.in);

System.out.print("Enter the value of N: ");


int N = sc.nextInt();

int first = 0, second = 1, nth = 0;


for (int i = 3; i <= N; i++) {
nth = first + second;
first = second;
second = nth;
}

System.out.printf("The %dth Fibonacci number is %d", N, nth);


}
}
Given a decimal number as input, import java.util.Scanner; Explanation:
you need to write a program to - We first read the decimal number input from the user using the Scanner class.
convert the given decimal public class DecimalToBinary { - We initialize an empty string to store the binary number.
number into an equivalent binary public static void main(String[] args) { - We use a while loop to repeatedly divide the decimal number by 2 and get the remainder until the decimal
number. Write a complete Java Scanner scanner = new Scanner(System.in); number becomes 0.
program. System.out.print("Enter a decimal number: "); - For each iteration of the loop, we obtain the remainder of the division using the modulus operator (%). This
int decimalNumber = scanner.nextInt(); remainder is added to the left side of the binaryNumber string using concatenation.
String binaryNumber = ""; - We then update the decimalNumber by dividing it by 2 using integer division (/).
- Finally, we print the binaryNumber string which now contains the equivalent binary number.
// Conversion algorithm
while (decimalNumber > 0) {
int remainder = decimalNumber % 2;
binaryNumber = remainder + binaryNumber;
decimalNumber = decimalNumber / 2;
}

System.out.println("The equivalent binary number is: " + binaryNumber);


}
}
Write a complete Java program that import java.util.Scanner; 1. Create an integer array of size 10.
will take an array of 10 numbers as 2. Take user input for all 10 numbers.
input and find how many odd public class OddEvenCount { 3. Create two integer variables to count odd and even numbers.
numbers and how many even public static void main(String[] args) { 4. Iterate through the array using a for loop.
numbers are there in the array. Scanner input = new Scanner(System.in); 5. For each number in the array, use the modulo operator (%) to check if it is odd or even.
int[] numbers = new int[10]; 6. If the number is even, increment the even count variable.
int evenCount = 0; 7. If the number is odd, increment the odd count variable.
int oddCount = 0; 8. After iterating through the entire array, print the values of the odd and even count variables.

// Taking user input for 10 numbers


for (int i = 0; i < 10; i++) {
System.out.print("Enter number " + (i+1) + ": ");
numbers[i] = input.nextInt();
}

// Iterating through the array and incrementing the count variables


for (int i = 0; i < 10; i++) {
if (numbers[i] % 2 == 0) {
evenCount++;
} else {
oddCount++;
}
}

// Printing the count of odd and even numbers


System.out.println("Number of even numbers: " + evenCount);
System.out.println("Number of odd numbers: " + oddCount);
}
}
Given two given arrays of equal public class Main {
length, the task is to find if given
arrays are equal or not. Two arrays public static void main(String[] args) {
are said to be equal if both of them
contain the same set of elements int[] arr1 = {1, 2, 3, 4, 5};
and in the same order. Write a int[] arr2 = {1, 2, 3, 4, 5};
complete Java program.
if (checkEquality(arr1, arr2)) {
System.out.println("Both arrays are equal");
} else {
System.out.println("Both arrays are not equal");
}
}

public static boolean checkEquality(int[] arr1, int[] arr2) {

// check if both arrays have the same length


if (arr1.length != arr2.length) {
return false;
}

// check if each element in both arrays is equal and in the same order
for (int i = 0; i < arr1.length; i++) {
if (arr1[i] != arr2[i]) {
return false;
}
}

return true;
}
}
Write a complete Java program that import java.util.Scanner;
will take an N*N matrix as input and 1. Take the number N as input.
output its Transpose. If N = 3, then public class MatrixTranspose { 2. Then take the N*N matrix as input.
following contains the transpose public static void main(String[] args) { 3. In the transpose method, create a new matrix with the same number of rows and columns as the input
matrix for the 3*3 matrix. Scanner scanner = new Scanner(System.in); matrix.
4. Use a nested loop to iterate through the rows and columns of the input matrix.
// Taking input of the size of the matrix 5. Set the value of each element in the new matrix using the corresponding element in the input matrix but with
System.out.print("Enter the size of the square matrix: "); the row and column indices swapped.
int n = scanner.nextInt(); 6. In the main method, create an instance of the class and call the transpose method with the input matrix as
argument.
int[][] matrix = new int[n][n]; 7. Print the transpose matrix to the console.

// Taking input of the matrix elements


System.out.println("Enter the elements of the matrix: ");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
matrix[i][j] = scanner.nextInt();
}
}

// Printing the original matrix


System.out.println("Original Matrix:");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}

// Finding the transpose of the matrix


int[][] transpose = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
transpose[j][i] = matrix[i][j];
}
}

// Printing the transpose of the matrix


System.out.println("Transpose of Matrix:");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(transpose[i][j] + " ");
}
System.out.println();
}
}
}
For a given 4 × 4 matrix, the task is import java.util.Scanner; This program first takes input for the 4x4 matrix from the user. It then interchanges the first and last rows of the
to interchange the elements of the matrix using a for loop and a temporary variable. Finally, it displays the resultant matrix to the user.
first and last rows and then return public class MatrixInterchange {
the resultant matrix. Write a public static void main(String[] args) {
complete Java program. Scanner input = new Scanner(System.in);
int[][] matrix = new int[4][4];

// Taking input from user for the matrix


System.out.println("Enter the elements of the matrix:");
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
matrix[i][j] = input.nextInt();
}
}

// Interchanging the first and last rows of the matrix


for (int i = 0; i < 4; i++) {
int temp = matrix[0][i];
matrix[0][i] = matrix[3][i];
matrix[3][i] = temp;
}

// Displaying the resultant matrix


System.out.println("Resultant matrix after interchanging the first and last rows:");
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}
For a given number N as input, find import java.util.*;
all the prime numbers from 1 to N.
Write a complete Java program public class PrimeNumbers {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = sc.nextInt();

System.out.print("Prime numbers from 1 to " + n + " are: ");


for (int i = 2; i <= n; i++) {
if (isPrime(i)) {
System.out.print(i + " ");
}
}
}

public static boolean isPrime(int num) {


if (num <= 1) {
return false;
}
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
}
Write a complete Java program that import java.util.Scanner;
will take an integer number as input
and check if the input value is a public class LeapYearChecker {
leap year or not.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);

System.out.print("Enter a year: ");


int year = input.nextInt();

if ((year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0)) {


System.out.println(year + " is a leap year.");
} else {
System.out.println(year + " is not a leap year.");
}

}
Write a complete Java program that import java.util.Scanner;
will take an N*N matrix as input and
sort all the values in each column. public class MatrixSorter {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);

System.out.print("Enter the size of the matrix: ");


int n = input.nextInt();

int[][] matrix = new int[n][n];


System.out.println("Enter the elements of the matrix:");

// Input matrix elements


for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
matrix[i][j] = input.nextInt();
}
}

// Sort columns
for (int j = 0; j < n; j++) {
for (int i = 0; i < n - 1; i++) {
for (int k = i + 1; k < n; k++) {
if (matrix[i][j] > matrix[k][j]) {
int temp = matrix[i][j];
matrix[i][j] = matrix[k][j];
matrix[k][j] = temp;
}
}
}
}

// Output sorted matrix


System.out.println("Sorted matrix:");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}

}
}
Write a complete Java program that import java.util.Scanner;
takes a String as input and find if
the text “final exam” is in that string public class Main {
or not. If found, print “Found”; public static void main(String[] args) {
otherwise, print “Not Found”. Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();

if(input.contains("final exam")) {
System.out.println("Found");
} else {
System.out.println("Not Found");
}
}
}
Write a complete Java program that import java.util.Scanner; In this program, we first define the input string (in this case, "hello world"). We then convert the string to a
takes a String as input and sort the character array using the toCharArray() method.
string in ascending order. Then print public class AsciiSorter {
the ascii values of each character in public static void main(String[] args) { To sort the character array, we use the bubble sort algorithm. We loop through each element of the array and
the sorted string. Scanner scanner = new Scanner(System.in); compare it with the element next to it. If the current element is greater than the next element, we swap them.
System.out.print("Enter a string: "); We repeat this process until the array is sorted.
String input = scanner.nextLine();
char[] chars = input.toCharArray(); Finally, we loop through each character in the sorted array using a for-each loop, and print the ASCII value of
for (int i = 0; i < chars.length - 1; i++) { each character using the (int) c syntax to cast the character to an integer.
for (int j = i + 1; j < chars.length; j++) {
if (chars[i] > chars[j]) { You can replace the input string with any string of your choice to test the program.
char temp = chars[i];
chars[i] = chars[j];
chars[j] = temp;
}
}
}
for (char c : chars) {
System.out.print((int) c);
}
}
}
Write a complete Java program that import java.util.Scanner; In this program, we first ask the user to input an integer using Scanner class. Then, we create a boolean array
takes an integer as input and print with 10 elements to keep track of which digits are present and which are absent.
which digits from 0 to 9 are absent public class AbsentDigits {
in that integer. public static void main(String[] args) { We loop through each digit in the integer using modulo operator and divide by 10. We mark the corresponding
Scanner scan = new Scanner(System.in); index as true in the boolean array to indicate the presence of that digit.
System.out.print("Enter an integer: ");
int num = scan.nextInt(); Finally, we loop through the boolean array and print the indices where the value is false, indicating the absence
of that digit in the integer.
boolean[] digits = new boolean[10]; // to keep track of the presence of digits

// check each digit in the integer


while (num > 0) {
int digit = num % 10;
digits[digit] = true; // mark the digit as present
num /= 10;
}

// print absent digits


System.out.print("Absent digits: ");
for (int i = 0; i < digits.length; i++) {
if (!digits[i]) {
System.out.print(i + " ");
}
}
}
}
Write a complete Java Program that import java.util.Scanner;
will ask for an integer as input and
print the following pattern (see the public class PrintPattern {
sample public static void main(String[] args) {
input/output for details). Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
Sample Input: int n = input.nextInt();
5
for (int i = 1; i <= n; i++) {
Sample output: for (int j = 1; j <= i; j++) {
1 System.out.print(j);
12 }
123 System.out.println();
1234 }
12345 }
}
Write a complete Java Program that First, we import the Scanner class to allow user input. Then, we create a new Scanner object called input. We
will ask for an integer as input and import java.util.Scanner; then prompt the user to enter a positive integer, and store their input in the variable num.
calculate the product of its digits
public class ProductOfDigits { We then create a variable called product and initialize it to 1. We use a while loop to iterate through each digit
of the number by continuously dividing num by 10 to get the next digit. We calculate the product of each digit by
public static void main(String[] args) { multiplying it with the previous product. Once we have iterated through all the digits, we print out the final
Scanner input = new Scanner(System.in); product to the console.

System.out.print("Enter a positive integer: "); This program takes into account that the input integer may not have a fixed number of digits, so it is able to
int num = input.nextInt(); calculate the product of digits for any positive integer.

int product = 1;
while(num > 0) {
int digit = num % 10;
product *= digit;
num /= 10;
}

System.out.println("The product of the digits is " + product);


}
}
Write a complete Java Program that
will ask for an integer as input and import java.util.Scanner;
print if the number is prime or not.
public class PrimeNumberChecker {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
int num = input.nextInt();

boolean isPrime = true;


for(int i = 2; i <= num/2; i++) {
if(num % i == 0) {
isPrime = false;
break;
}
}

if(isPrime) {
System.out.println(num + " is a prime number.");
} else {
System.out.println(num + " is not a prime number.");
}
}
}
Write a complete Java program that import java.util.Scanner;
calculates the factorial of a given
integer. public class FactorialCalculator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int num = input.nextInt();

if (num < 0) {
System.out.println("Error: Only positive integers can be used to calculate factorial.
Exiting program...");
System.exit(0);
}

int factorial = 1;

for (int i = 1; i <= num; i++) {


factorial *= i;
}

System.out.printf("The factorial of %d is %d", num, factorial);


}
}
Write a complete Java program to import java.util.Scanner; In this program, we first create a `Scanner` object to read input from the user. We then prompt the user to enter
find the longest word in a sentence a sentence and read it using the `nextLine()` method.
entered by the user public class LongestWordInSentence {
public static void main(String[] args) { We then split the sentence into an array of words using the `split()` method, specifying a delimiter of space. We
Scanner input = new Scanner(System.in); initialize a variable `longestWord` to an empty string, which we'll use to keep track of the longest word we've
found so far.
System.out.print("Enter a sentence: ");
String sentence = input.nextLine(); We then loop through each word in the `words` array using a for-each loop. For each word, we check if its
length is greater than the length of the current `longestWord`. If it is, we update `longestWord` to the current
String[] words = sentence.split(" "); word.

String longestWord = ""; Finally, we print out the longest word we found using `System.out.println()`.

for (String word : words) {


if (word.length() > longestWord.length()) {
longestWord = word;
}
}

System.out.println("The longest word in the sentence is: " + longestWord);


}
}
Write a complete Java program that import java.util.Scanner; The algorithm then iterates over all integers starting from 1 up to the given number (inclusive). The reason for
will ask for an integer-type input and starting from 1 is that 1 is a divisor of every integer. The upper limit is the number itself because no integer can
print all of its divisors. public class DivisorFinder { have a divisor greater than itself.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int number = scanner.nextInt();
for (int i = 1; i <= number; ++i) {
if (number % i == 0) {
System.out.print(i + " ");
}
}
}
}
Write a complete Java program that import java.util.Scanner;
will ask for an integer-type input and
print all of its divisors in public class DivisorFinder {
reverse order. public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int number = scanner.nextInt();
for (int i = number; i >= 1; --i) {
if (number % i == 0) {
System.out.print(i + " ");
}
}
}
}
import java.util.Scanner;

public class NumberComparison {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter an integer: ");


int number = scanner.nextInt();

int comparisonResult;
if (number > 50) {
comparisonResult = 1;
} else {
comparisonResult = 0;
}

switch (comparisonResult) {
case 1:
System.out.println("Greater");
break;
Write a complete Java Program that case 0:
will ask for an integer-type input System.out.println("Smaller");
(you can assume that the break;
given input is either positive or default:
negative number) and check // This case is not expected to be reached
whether the given input is greater System.out.println("Unexpected error");
than break;
50 or not. If greater than 50, then }
print “Greater”. Otherwise, print
“Smaller”. You must solve this scanner.close();
problem using the Switch-Case }
statement. }
import java.util.Scanner;

public class PositiveOrNegative {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter an integer: ");


int number = scanner.nextInt();

// Using the expression to determine the sign


number = number - Math.abs(number);

// Using switch statement to determine the output


switch (number) {
Write a complete Java Program case 0:
that will ask for an integer-type input System.out.println("Positive");
(you can assume that the break;
input is either positive or negative default:
number) and check whether the // Since the expression doubles the negative value, divide by 2 to get the original
given input is positive or value
negative. If positive, print “Positive”. System.out.println(Math.abs(number / 2));
Otherwise, if the value is negative, break;
print the absolute value of the }
input. (You cannot use If-Else
statements for this problem. Only scanner.close();
the switch statement is }
allowed). }
import java.util.Scanner;

public class EvenOddChecker {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter an integer: ");


int number = scanner.nextInt();

switch (number % 2) {
case 0:
Write a complete Java Program that System.out.println("Even");
will ask for an integer-type input and break;
check whether the given case 1:
input is even or odd. If even, print System.out.println("Odd");
“Even”. Otherwise, print “Odd”. You break;
cannot use If-Else statements for // The default case is not necessary here as the remainder will always be 0 or 1
this problem. Only the switch }
statement is }
allowed. }

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy