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

JAVA Homework Help THANK YOU Question 1: Writing Exception Code A Write a method

ID: 3682864 • Letter: J

Question

JAVA Homework Help THANK YOU

Question 1: Writing Exception Code A

Write a method to read in three numbers from the user. Then read in the name of an output file. Output the three numbers to the file.

Use exception handling so the code will compile. Also use exception handling to account for the user entering in non-numbers.

The method header is: public void readNumbersOutputToFile()

Question 2: Writing Exception Code B

Write a method to read in positive numbers from the user. Stop when the user enters 0. Store the numbers in an ArrayList.

Use exception handling to account for the user entering a non-number. Keep reading in values after this happens.

Write your own exception class and use it to account for the user entering a negative number. Keep reading in values after this happens.

The method header is: public ArrayList<Integer> readNumbersFromUser()

Explanation / Answer

I have answered both the parts. please find the code below:

1)

/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
   public void readNumbersOutputToFile()
{
   int num1,num2,num3;
   Scanner sc=new Scanner(System.in);
   try{
System.out.println("Enter three integer: ");
num1=sc.nextInt();
       num2=sc.nextInt();
       num3=sc.nextInt();
           FileWriter fWriter = null;
BufferedWriter writer = null;
       fWriter = new FileWriter("text.txt");
writer = new BufferedWriter(fWriter);
writer.write(num1);
writer.write(num2);
writer.write(num3);
writer.newLine();
writer.close();
}
catch(InputMismatchException exception)
{
System.out.println("This is not an integer");
}
  
}
   public static void main (String[] args) throws java.lang.Exception
   {
      
       // your code goes here
   }
}

2)

/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
   public ArrayList<Integer> readNumbersFromUser()
   {
       Scanner sc=new Scanner(System.in);
       ArrayList<Integer> mylist = new ArrayList<Integer>();
       try
       {
   while (sc.hasNextInt()) {
   int i = sc.nextInt();
   mylist.add(i);
       }
       }
       catch(InputMismatchException exception)
{
System.out.println("This is not an integer");
}
       return mylist;
   }

   public static void main (String[] args) throws java.lang.Exception
   {
      
       // your code goes here
   }
}