Select the correct answer.
(1) Which of the following will open a file named MyFile.txt and allow you to read data from it?
(a) File file = new File("MyFile.txt");
(b) FileWriter inputFile = new FileWriter();
(c) File file = new File("MyFile.txt");
FileReader inputFile = new FileReader(file);
(d) FileWriter inputFile = new FileWriter("MyFile.txt");
(2) How many times will the following do - while loop be executed?
int x = 11;
do {
x += 20;
} while (x > 100);
(a) 0 (b) 4 (c) 5 (d) 1 (e) 2
(3) Examine the following code:
Scanner keyboard = new Scanner(System.in);
int studentGrade = 0;
int totalOfStudentGrades = 0;
while(studentGrade != -1) {
System.out.println("Enter student grade: :");
studentGrade = keyboard.nextInt();
totalOfStudentGrades += studentGrade;
}
In the loop header: while(studentGrade != -1) , what is the purpose
of " -1 " ?
(a) It initializes the count of the number of grades.
(b) It is a sentinel.
(c) It tells the program to give the student a grade of -1 , if he does not have any grades.
(d) If the grade is not -1 , the while statement will not be executed.
(4) You can use this method to determine whether a file exists.
(a) the File class's canOpen
method
(b) the File class's exists
method
(c) the Scanner class's exists method
(d) the FileWriter class's fileExists method
(5) Which line(s) below opens MyFile.txt allows to append data to its existing contents?
(a) File fwriter = new File("MyFile.txt");
FileWriter outFile = new FileWriter(fwriter, true);
(b) FileWriter outfile = new FileWriter(true, "MyFile.txt");
(c) File fwriter = new File("MyFile.txt");
FileWriter outFile = new FileWriter(fwriter);
(d) File outfile = new File("MyFile.txt", true);
(6) A(n) ________ is an object that is generated in memory as the result of an error or an unexpected event.
(a) default exception handler (b) error message
(c) exception handler (d) exception
(7) In a try / catch construct, after the catch statement is executed ________ .
(a) the program returns to the statement following the statement in which the exception occurred
(b) the program resumes at the statement that immediately follows the try / catch construct
(c) the program terminates
(d) the program resumes at the first statement of the try statement
(8) An exception’s default error message can be retrieved using this method.
(a) getErrorMessage() (b) getDefaultErrorMessage()
(c) getMessage() (d) getDefaultMessage()
(9) In the following code, assume that inputFile references a Scanner object that has been successfully used to open a file:
double totalIncome = 0.0;
while (inputFile.hasNext())
{
try
{
totalIncome += inputFile.nextDouble();
}
catch(InputMismatchException e)
{
System.out.println("Non-numeric data encountered in the file.");
inputFile.nextLine();
}
finally
{
totalIncome = 35.5;
}
}
What will be the value of totalIncome after the following values are read from the file?
2.5
8.5
3.0
5.5
abc
1.0
(a) 35.5 (b) 75.0 (c) 0.0 (d) 19.5
(10) Why does the following code cause a compiler error?
try
{
number = Integer.parseInt(str);
}
catch (IllegalArgumentException e)
{
System.out.println("Bad number format.");
}
catch (NumberFormatException e)
{
System.out.println(str + " is not a number.");
}
(a) Because you can have only one catch clause in a try statement.
(b) Because the Integer.parseInt method does not throw a NumberFormatException.
(c) Because the Integer.parseInt method does not throw an IllegalArgumentException.
(d) Because NumberFormatException
inherits from
IllegalArgumentException. The code should handle
NumberFormatException before IllegalArgumentException.
Question 1
Answer:
(c) File file = new File("MyFile.txt");
FileReader inputFile = new FileReader(file);
Question 2
Answer:
(d) 1
Question 3
Answer: (b) It is a sentinel.
Question 4
Answer: (b) the File class's exists method
Question 5
Answer:
(a) File fwriter = new File("MyFile.txt");
FileWriter outFile = new FileWriter(fwriter, true);
Question 6
Answer: (d) exception
Question 7
Answer:
(b) the program resumes at the statement that immediately follows the try / catch construct
Question 8
Answer:
(c) getMessage()
Question 9
Answer:
(a) 35.5
Question 10
Answer:
(d) Because NumberFormatException
inherits from
IllegalArgumentException. The code should handle
NumberFormatException before IllegalArgumentException.
Select the correct answer. (1) Which of the following will open a file named MyFile.txt and...
Placing Exception Handlers File ParseInts.java contains a program that does the following: Prompts for and reads in a line of input Uses a second Scanner to take the input line one token at a time and parses an integer from each token as it is extracted. Sums the integers. Prints the sum. Save ParseInts to your directory and compile and run it. If you give it the input 10 20 30 40 it should print The sum of the integers...
Modify your program in Lab Assignment 4A to throw an exception if the file does not exist. An error message should result. Use the same file name in your program as 4A, however, use the new input file in 4B assignment dropbox. My code: import java.io.*; import java.util.*; public class Lab4B { public static void main(String[] args) throws IOException { final String input_file = "Lab_4A.txt"; final String output_file = "Lab_4A.txt"; Scanner x = null; FileWriter y = null; try {...
Modify the program that you wrote for the last exercise in a file named Baseball9.java that uses the Player class stored within an array. The program should read data from the file baseball.txt for input. The Player class should once again be stored in a file named Player.java, however Baseball9.java is the only file that you need to modify for this assignment. Once all of the input data from the file is stored in the array, code and invoke a...
import java.util.Scanner; import java.io.File; public class Exception2 { public static void main(String[] args) { int total = 0; int num = 0; File myFile = null; Scanner inputFile = null; myFile = new File("inFile.txt"); inputFile = new Scanner(myFile); while (inputFile.hasNext()) { num = inputFile.nextInt(); total += num; } System.out.println("The total value is " + total); } } /* In the first program, the Scanner may throw an...
Please help me fix my errors. I would like to read and write the text file in java. my function part do not have errors. below is my code import java.io.FileInputStream; import java.io.InputStreamReader; import java.io.FileWriter; import java.io.IOException; public class LinkedList { Node head; class Node { int data; Node next; Node(int d) { data = d; next = null; } } void printMiddle() { Node slow_ptr...
package Lab09; public class Lab09Driver { public static void main(String[] args) { new Lab09Driver(); } public Lab09Driver() { Scanner input = new Scanner(System.in); System.out.println("Would you like to load a previous file? (Y/N)"); String.choice = input.nextLine().trim().toUpperCase(); if (choice.charAt(0) == 'Y') { System.out.println("Enter the name of the file that you want to load:"); String.fileName = input.nextLine(); try { Scanner fileInput = new Scanner(new File(fileName)); while(fileInput.hasNextLine()){ String answer = fileInput.nextLine(); System.out.println(answer); }fileInput.close(); } catch (FileNotFoundException e) { System.out.println("Could not find the file, and...
Finish FormatJavaProgram.java that prompts the user for a file name and assumes that the file contains a Java program. Your program should read the file (e.g., InputFile.java) and output its contents properly indented to ProgramName_Formatted.java (e.g., InputFile_Formatted.java). (Note: It will be up to the user to change the name appropriately for compilation later.) When you see a left-brace character ({) in the file, increase your indentation level by NUM_SPACES spaces. When you see a right-brace character (}), decrease your indentation...
3. Handling exceptions with a finally clause a. Download the following file from the class website: TestFinally.java b. Examine the code to determine what it does. c. Compile the code and notice the error. d. Modify TestFinally.java to handle the exception following these instructions (and those embedded in the code): i. Embedded in the code is a note showing the location for the try statement. ii. The first line of the catch block should look like this: catch(IOException e) {...
composed the following java code to read a string from a text file but receiving compiling errors. The text file is MyNumData.txt. Included the original java script that generated the output file. Shown also in the required output results after running the java program. I can't seem to search for the string and output the results. Any assistance will be greatly appreciated. import java.io.BufferedReader; import java.io.FileReader; import java.util.ArrayList; public class Main { public static void main(String[] args) { System.out.print("Enter the...
I need help with my computer science 2 lab. First I am asked to run the following program and check output? public static void main(String []args) { String filename= "output.txt"; File file = new File(fileName); try{ FileWriter fileWriter = new FileWriter(file, true); fileWriter.write("CS2: we finished the lecuter\n"); fileWriter.close(); }catch (Exception e){ system.out.println("your message"+e); } String inputfileName = "output.text"; File fileToRead = new File (inputfileName); try { Scanner = new Scanner (fileToread); while(Scanner.hasNextLine()){ String line = scanner.nextLine(); system.out.println(line); } }catch(Eception...