Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I need help with a Java assignment: prompt the user to enter a positive value of

ID: 3912125 • Letter: I

Question

I need help with a Java assignment:

prompt the user to enter a positive value of type byte.

cast this input first to type int and then to type char.

if the char is a printable ASCII character (from 32 to 123 ), display it.

if the user's input is bad, the program should end gracefully with an error message.

Sample Run 1

Enter a positive byte value 67

In ASCII, that is character C

Sample Run 2

Enter a positive byte value 300

Bad input. Run program again

Sample Run 3

Enter a positive byte value twelve

Bad input. Run program again

Explanation / Answer


import java.util.Scanner;

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

/**
*
* @author Vamsi
*/
public class bad_input {
  
public static void main(String argv[])
{
byte b;//variable declaration
Scanner sc = new Scanner(System.in);
  
try
{
//reading input
System.out.print("Enter a positive byte value: ");
b =sc.nextByte();
//type casting to int
int n = (int)b;
  
//checking whether valid ascii character or not
if(b>=32 && b<=123)
{
//type casting to char
char c = (char)n;
System.out.println("In ASCII, that is character "+c);
}
}
catch(Exception e)
{
System.out.println("Bad input. Run program again");

}


  
}
}

output1:

run:
Enter a positive byte value: 67
In ASCII, that is character C
BUILD SUCCESSFUL (total time: 2 seconds)

output2:

run:
Enter a positive byte value: 300
Bad input. Run program again
BUILD SUCCESSFUL (total time: 3 seconds)

output3:

run:
Enter a positive byte value: twelve
Bad input. Run program again
BUILD SUCCESSFUL (total time: 4 seconds)

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote