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...
Find the readData() method Inside this method is a try block without any catch statements. Add...
Find the readData() method Inside this method is a try block without any catch statements. Add the following 5 catch statements to this file (Hint: put them in the right order): RuntimeException Exception FileNotFoundException NumberFormatException InputMismatchException For each of these print out a short message describing the exception that occurred Java Class import java.io.File; import java.io.FileNotFoundException; import java.util.InputMismatchException; import java.util.Scanner; public class ReadInData {    public static double readData(String fileName) {        File file = new File(fileName);       ...
Use a swift language in xcode software for the following code? 20 pts Create a class...
Use a swift language in xcode software for the following code? 20 pts Create a class called Polygon, this class will have: a. Properties: i. Number of sides ii. Interior angles b. Method i. sides(), this will print to the console how many sides the polygon has ii. interiorAngle(), this will calculate the interior angles and set it to the interior angles property Create another class named Triangle that inherits from Polygon. This class will have to: a. Properties: i....
true or false C++ a.    (T or F)  There can be no code between a try-block and its...
true or false C++ a.    (T or F)  There can be no code between a try-block and its associated catch-block. b.    (T or F)  The reserved word throw is used to signal that an exception has occurred. c.    (T or F)  The correct use of throw can be anywhere in a program; a try /  catch structure is used only in class definitions. d.    (T or F)  In C++, class is not a reserved word. e.    (T or F)  Class attributes have no fixed type; their type can be changed during...
What is the output of the following code snippet? (If there is some kind of syntax...
What is the output of the following code snippet? (If there is some kind of syntax error indicate this by marking "error" in your answer choice) 1.        int laps = 8;        if (laps++ > --laps)               laps += 2;        else if (--laps > (laps - 1))               laps += 4;        else if (++laps)               laps -= 3;        cout << laps << endl; 2. What is the output of the following code snippet?     int j = 47;     int i = 8;     j =...
in java What object is passed to the start method in a JavaFX program? What should...
in java What object is passed to the start method in a JavaFX program? What should you do with it?
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...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT