Programming Activity 5-2 Complete Chapter 5, Programming Activity 2: Using the \
ID: 3829213 • Letter: P
Question
Programming Activity 5-2
Complete Chapter 5, Programming Activity 2: Using the "switch" Statement.
For the default case, also indicate whether the input value is greater than 4 or less than 0 and whether the value is even or odd.
Be sure to test with each of the valid input values suggested in the textbook: the integers from 0 to 4 (0, 1, 2, 3, and 4) plus some other invalid integer values, such as 5, -1, 10, and -6.
The following is an example of the console output from one testing session:
0 was entered.
1 was entered.
2 was entered.
3 was entered.
4 was entered.
The invalid value 5 was entered, which is greater than 4 and odd.
The invalid value -1 was entered, which is less than 0 and odd.
The invalid value 10 was entered, which is greater than 4 and even.
The invalid value -6 was entered, which is less than 0 and even.
Make sure you study the Programming Activity 5-2 Guidance document.
Upload your zipped assignment folder, which contains the java and class files.
Explanation / Answer
package org.students;
public class SwitchDemo1 {
public static void main(String[] args) {
//Declaring an array
int nos[]={0,1,2,3,4,5,-1,10,-6};
/* Based on the each value of the array print
* the corresponding message using switch case
*/
for(int i=0;i<nos.length;i++)
{
switch(nos[i])
{
case 0:
case 1:
case 2:
case 3:
case 4:{
System.out.println(nos[i]+" was entered.");
break;
}
default:{
if(nos[i]>4 && nos[i]%2!=0)
System.out.println("The invalid value "+nos[i]+" was entered, which is greater than 4 and odd.");
else if(nos[i]>4 && nos[i]%2==0)
System.out.println("The invalid value "+nos[i]+" was entered, which is greater than 4 and even.");
else if(nos[i]<0 && nos[i]%2==0)
System.out.println("The invalid value "+nos[i]+" was entered, which is less than 0 and even.");
else if(nos[i]<0 && nos[i]%2!=0)
System.out.println("The invalid value "+nos[i]+" was entered, which is less than 0 and odd.");
break;
}
}
}
}
}
_____________________
Output:
0 was entered.
1 was entered.
2 was entered.
3 was entered.
4 was entered.
The invalid value 5 was entered, which is greater than 4 and odd.
The invalid value -1 was entered, which is less than 0 and odd.
The invalid value 10 was entered, which is greater than 4 and even.
The invalid value -6 was entered, which is less than 0 and even.
________________Thank You
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.