Question

In: Computer Science

(20 pts) In the following code inside a try block, what kind of object is passed...

  1. (20 pts) In the following code inside a try block, what kind of object is passed to the Scanner constructor?

Scanner file = new Scanner ( new File (“test.txt”));

  1. (20 pts) What is the output of this code sequence?

Scanner parse = new Scanner (“A 1 B 2 C 3 D”);

while (parse.hasNext())

    System.out.print(parse.next());

  1. (20 pts) What is wrong with following code?

try

{

Scanner file = new Scanner(new File(“c:\docs\data.txt”));

int n = 0;

while (file.hasNext())

{

String s = file.nextLine();

if (s.equals(“A”))

      n++;

}

System.out.println(“The value of n is “ +n);

file.close();

}

catch(IOException ioe)

{

ioe.printStackTrace();

}

    

  

  1. (40 pts) You coded the following class:

try

{

   Scanner file = new Scanner( new File(“test.txt”));

   String s = file.nextLine();

}
catch (FileNotFoundException fnf)

{

System.out.println(fnf.getMessage());

}

Will this code work correctly? If not how do you fix it.

Solutions

Expert Solution

# PLEASE LEAVE A THUMBS UP.

1.) Scanner file = new Scanner ( new File (“test.txt”));

This code is used to read a text file using java.util.scanner.

It must implement File not found exception or must be catch by the try catch block.

Here in the parameter of the constructor of Scanner the object of the File class is created .

lets have an example-

public class ReadFile

{

    public static void main(String[] args)

                throws FileNotFoundException

    {

        Scanner file = new Scanner(new File("test.txt"));

        int line = 1;

        while (file.hasNext())

        {

            String str = scan.nextLine();

            System.out.println((line++) + ": " + str);

        }

    }

}

2.)  

Scanner parse = new Scanner (“A 1 B 2 C 3 D”);

while (parse.hasNext())

    System.out.print(parse.next());

OUTPUT : A1B2C3D

// without any spaces, as next does not read spaces , but if you use nextLine() instead then spaces would be printed.

3.)

try

{

Scanner file = new Scanner(new File(“c:\docs\data.txt”));

int n = 0;

while (file.hasNext())

{

String s = file.nextLine();

if (s.equals(“A”))

      n++;

}

System.out.println(“The value of n is “ +n);

file.close();

}

catch(IOException ioe)

{

ioe.printStackTrace();

}

Here, the argument inside catch is wrong. Just remember whenever U try to read a a file, File not found expection is a must to be thrown or catch if a try-catch block is used.

For ex,

catch (FileNotFoundException e)

        {

            e.printStackTrace();

  

        }

4.) No, it will not read whole file for that you need to use a while loop and file.hasnext() function , the hasNext() method returns true if the given file contains another string. Hence why the code  will loop if file has another string. Once there are no more Strings in the file, hasNext() returns false.

try

{

   Scanner file = new Scanner( new File(“test.txt”));

while(file.hasnext()){

   String s = file.nextLine();

System.out.print(s);

}}
catch (FileNotFoundException fnf)

{

System.out.println(fnf.getMessage());

}


Related Solutions

Try the following: get some stuff: a small ball (or some kind of object that will...
Try the following: get some stuff: a small ball (or some kind of object that will roll - a golf ball or marble or toy car is great, but an empty soup can will do in a pinch) get a tape measure (a yardstick or a ruler will also work. You can also stretch a piece of string and mark off ruler lengths on the string to get the total length.) around ten coins Measure the distance from a tabletop...
1) Describe briefly what exceptions are and what their purpose is. What is the try block?...
1) Describe briefly what exceptions are and what their purpose is. What is the try block? What is the catch block? What happens with the flow of control if the catch block does not catch a thrown exception? Give a simple example. 2) Describe briefly what templates are and what their purpose is. 3) Write one line of code for each line below. What is the template type in each case? - Create a vector to store student IDs -...
// 5. Predict what the following code will print (write it down), then try it. var...
// 5. Predict what the following code will print (write it down), then try it. var myVariable = "global"; var myOtherVariable = "global"; function myFunction() { var myVariable = "local"; return myVariable; } function myOtherFunction() { myOtherVariable = "local"; return myOtherVariable; javascript
Modify the following program. Add using Exception handing and polymorphism. try-catch block, Finally block in java...
Modify the following program. Add using Exception handing and polymorphism. try-catch block, Finally block in java * description of class Driver here. *these is the main class where it acts like parent class. Compiler will execute firstly static method. import java.util.Scanner; public class Driver {     public static void main (String[] args){         Scanner stdIn = new Scanner(System.in);         String user;         String computer;         char a = 'y';         do {             System.out.println("What kind of Computer would you like?");...
Given the following code for AES Electronic Code Block implementation for the encryption functionality. Modify the...
Given the following code for AES Electronic Code Block implementation for the encryption functionality. Modify the code to create a function named ‘encryptECB(key, secret_message)’ that accepts key and secret_message and returns a ciphertext.          #Electronic Code Block AES algorithm, Encryption Implementation from base64 import b64encode from Crypto.Cipher import AES from Crypto.Util.Padding import pad from Crypto.Random import get_random_bytes secret_message = b" Please send me the fake passport..." password = input ("Enter password to encrypt your message: ") key= pad(password.encode(), 16) cipher...
The following code is inside a do while loop. choice is supposed to be an integer...
The following code is inside a do while loop. choice is supposed to be an integer input by the user. However, when a character is put instead of an integer, the code loops infinitely. Putting break; or exit(); after the catch statements terminates the whole program, which is wrong. How can i fix this? #include <iostream> #include <vector> #include <iomanip> #include<stdlib.h> #include <cctype> #include "MyGrades.h" using namespace std; int main () {    int choice; // user input for menu...
4. Given the following code for AES Electronic Code Block implementation for the encryption functionality. Modify...
4. Given the following code for AES Electronic Code Block implementation for the encryption functionality. Modify the code to create a function named ‘decryptECB(key, ciphertext)’ that accepts key and ciphertext and returns a plaintext. from base64 import b64decode from Crypto.Cipher import AES from Crypto.Util.Padding import pad from Crypto.Util.Padding import unpad # We assume that the password was securely shared beforehand password = input ("Enter the password to decrypt the message: ") key= pad(password.encode(), 16) ciphertext = input ("Paste the cipher...
Question 63.33 pts What is the first block in a blockchain called? Group of answer choices...
Question 63.33 pts What is the first block in a blockchain called? Group of answer choices Genesis block First block Alpha block Initial block Question 53.33 pts Data is permanently recorded on the Bitcoin network through files called Group of answer choices Blocks Nounce Node Safety file
Write Java code for each of the following problem a. Two players, a and b, try...
Write Java code for each of the following problem a. Two players, a and b, try to guess the cost of an item. Whoever gets closest to the price without going over is the winner. Return the value of the best bid. If both players guessed too high, return -1. example: closestGuess(97, 91, 100) → 97 closestGuess(3, 51, 50) → 3 closestGuess(12, 11, 10) → -1 b. Given a non-empty string, return true if at least half of the characters...
Problem 1. (20 Pts) Two storage structures, given code names Y and Z, are being considered...
Problem 1. (20 Pts) Two storage structures, given code names Y and Z, are being considered for a military base. The military uses a 6% percent/year expected rate of return and a 24-year life for decisions of this type. The relevant characteristics for each structure are shown below. Structure Y Structure Z First Cost 24225 24225 Estimated Life 12 years 24 years Estimated Salvage Value None $1,800 Annual Maintenance Cost $1,000 $720 a) What is the future worth of each...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT