Question

Start with the code below and complete the getInt method. The method should prompt the user...

Start with the code below and complete the getInt method. The method should prompt the user to enter an integer. Scan the input the user types. If the input is not an int, throw an IOException; otherwise, return the int. In the main program, invoke the getInt method, use try-catch block to catch the IOException.

import java.util.*;

import java.io.*;

public class ReadInteger {

pubilc static void main() {

// your code goes here }

public static int getInt() throws IOException {

// your code goes here }

}

Homework Answers

Answer #1

CODE :

import java.util.*;

import java.io.*;
public class ReadInteger {

   public static void main(String[] args) {


      try {

         int a = getInt();
         System.out.println(a+" is an integer.");


      } catch (IOException e) {
         System.out.println("IOException called!");

      }

   }

   public static int getInt() throws IOException {

      Scanner sc= new Scanner(System.in);
      System.out.println("Enter an integer: ");

      if(sc.hasNextInt()){
         int num=sc.nextInt();
         return num;
      }

        else{
           throw new IOException("exception") ;

      }
   }

}

EXAMPLES:

1.

2.

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
Write an application in which you declare an array of eight first names. Write a try...
Write an application in which you declare an array of eight first names. Write a try block in which you prompt the user for an integer and display the name in the requested position. Create a catch block that catches the potential ArrayIndexOutOfBoundsException thrown when the user enters a number that is out of range. The catch block also should display the error message Subscript out of range. import java.util.*; public class BadSubscriptCaught {    public static void main(String[] args)...
What is the minimum modification needed to make the code that follows compile? public void readData()...
What is the minimum modification needed to make the code that follows compile? public void readData() {     boolean dataNotFound = true;     if (dataNotFound) {         throw new IOException();     }     catch(IOException e) {         System.out.println("data file can't be found");     } } a. Place the if statement within a try block. b. Add a throws clause to the method declaration. c. Set dataNotFound to false. d. No modification is needed.
Write an application that asks a user to enter an integer. Display a statement that indicates...
Write an application that asks a user to enter an integer. Display a statement that indicates whether the integer is even or odd. ------------------------------------------ import java.util.Scanner; class EvenOdd {     public static void main(String[] args) {         // Write your code here     }     public static boolean isEven(int number) {     } }
Write the complete code necessary to prompt the user for 4 sequential numbers, calculate the summation...
Write the complete code necessary to prompt the user for 4 sequential numbers, calculate the summation of the 4 numbers and display the results including the words "The summation of 1,2,3,4 is". A summation is defined as n + n+1 + n+2.... Declare necessary variables and be sure to include comments. Include int main(void) { Code goes here } The programming language is C in Visual Basic
This is the code I have written for my Java homework assignment but I can't seem...
This is the code I have written for my Java homework assignment but I can't seem to get it to run. Any help would be appreciated! import javax.swing.JOptionPane; import java.io.*; import java.util.Scanner; public class javaGamev5 { public static void main(String[] args) throws IOException { String question = null, answerA = null, answerB = null, answerC = null ; int menuChoice = 0, correctAnswer = 0, points = 0, score = 0, highscore = 0; displayIntro(); do { menuChoice = displayMainMenu();...
Analyze this code and run it, if there are any issues note them and fix them,...
Analyze this code and run it, if there are any issues note them and fix them, if not give the output and Big O notation runtime: public class PrintBits { public static void printBits(int a) { try { String str = Integer.toBinaryString((Integer) a); for(int i = 0; i < str.length(); i++){ System.out.print (str.charAt(i)); } } catch (ClassCastException e) { throw new RuntimeException ("Argument is not an Integer"); } } public static void main (String[] args){ printBits (-17); System.out.println(); printBits (17);...
This is a java assignment on repl.it my code works but I keep failing the tests....
This is a java assignment on repl.it my code works but I keep failing the tests. Can anyone help me Write the body of the fileAverage() method. Have it open the file specified by the parameter, read in all of the floating point numbers in the file and return their average (rounded to 1 decimal place) For the testing system to work, don't change the class name nor the method name. Furthermore, you cannot add "throws IOException" to the fileAverage()...
Complete method printPopcornTime(), with int parameter bagOunces, and void return type. If bagOunces is less than...
Complete method printPopcornTime(), with int parameter bagOunces, and void return type. If bagOunces is less than 3, print "Too small". If greater than 10, print "Too large". Otherwise, compute and print 6 * bagOunces followed by "seconds". End with a newline. Example output for ounces = 7: 42 seconds import java.util.Scanner; public class PopcornTimer { public void printPopcornTime(int bagOunces) { /* Your solution goes here */ } public static void main (String [] args) { PopcornTimer popcornBag = new PopcornTimer();...
7.6 LAB: Exception handling to detect input String vs. Integer The given program reads a list...
7.6 LAB: Exception handling to detect input String vs. Integer The given program reads a list of single-word first names and ages (ending with -1), and outputs that list with the age incremented. The program fails and throws an exception if the second input on a line is a String rather than an Integer. At FIXME in the code, add a try/catch statement to catch java.util.InputMismatchException, and output 0 for the age. Ex: If the input is: Lee 18 Lua...
Hello, I am trying to create a Java program that reads a .txt file and outputs...
Hello, I am trying to create a Java program that reads a .txt file and outputs how many times the word "and" is used. I attempted modifying a code I had previously used for counting the total number of tokens, but now it is saying there is an input mismatch. Please help! My code is below: import java.util.*; import java.io.*; public class Hamlet2 { public static void main(String[] args) throws FileNotFoundException { File file = new File("hamlet.txt"); Scanner fileRead =...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT
Active Questions
  • To the TwoDArray, add a method called transpose() that generates the transpose of a 2D array...
    asked 4 minutes ago
  • How could your result from GC (retention time, percent area, etc.) be affected by these following...
    asked 14 minutes ago
  • QUESTION 17 What are the tasks in Logical Network Design phase? (Select five. ) Design a...
    asked 16 minutes ago
  • What is the temperature of N2 gas if the average speed (actually the root-mean-square speed) of...
    asked 25 minutes ago
  • Question One: Basic security concepts and terminology                         (2 marks) Computer security is the protection of...
    asked 38 minutes ago
  • In program P83.cpp, make the above changes, save the program as ex83.cpp, compile and run the...
    asked 46 minutes ago
  • the determination of aspirin in commercial preparations experment explain why the FeCl3-KCl-HCl solution was ased as...
    asked 58 minutes ago
  • Describe important events and influences in the life of Wolfgang Amadeus Mozart. What styles, genres, and...
    asked 1 hour ago
  • 3.12 Grade Statistics Write a python module "school.py" that prints school information (first 3 lines of...
    asked 1 hour ago
  • Using python, please explain. The factorial of an integer N is the product of the integers...
    asked 1 hour ago
  • alamoto Co. manufactures a single product that goes through two processes — mixing and cooking. The...
    asked 1 hour ago
  • QUESTION 21 _______ is the ease of use with which network users can access the network...
    asked 1 hour ago