Question

I need help with my computer science 2 lab. First I am asked to run 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 e){
System.out.println("I could not open to the file to read.");
}
}

then Write a java program to read the attached students.txt file line by line. Split each line text using the split() method of String class and display each line details using loop as follows.

Output:

            S.No: 1

First Name: mohamed

            Last Name: ali

            Telephone: 0504123456

            Courses: cs1, cs2, ds3

------------------------------------------------------------------------------

            S.No: 2

First Name: ahmed

            Last Name: hamdi

            Telephone: 0507415985

            Courses: cs1, cs2, ds3

------------------------------------------------------------------------------

            S.No: 3

First Name: kamel

            Last Name: salem

            Telephone: 0503245714

            Courses: cs1

------------------------------------------------------------------------------

            S.No: 4

First Name: Mohsen

            Last Name: Mohamed

            Telephone: 0503245714

            Courses: cs1, cs2

------------------------------------------------------------------------------

students.txt has this inside:

1:mohamed:ali:0504123456:cs1:cs2:ds3

2:ahmed:hamdi:0507415985:cs1:cs2:ds3


3:kamel:salem:0503245714:cs1
4:Mohsen:Mohamed:0503245714:cs1:cs2
0 0
Add a comment Improve this question Transcribed image text
Answer #1

check out the solution and do comment if any queries.

--------------------------------------------------------------------------------------

the given program has many errors, Java is case sensitive language so take care upper and lower cases in keywords and identifiers while using them.

----------------------------------------------

check out the modified program and analyse the tiny differences in the below program.

----------------------------------------------

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

public class TestRecord {
   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.txt";
       File fileToRead = new File (inputfileName);
       try {
        Scanner Scanner = new Scanner (fileToRead);
       while(Scanner.hasNextLine()){
           String line = Scanner.nextLine();
           System.out.println(line);
       }
       }catch(Exception e){
       System.out.println("I could not open to the file to read.");
       }
   } // main ends
} // class ends

------------------------------------------------------------------------------------------

Output :

Console output :

File output :

=========================================================================

Code :

Java program to read Students.txt file.

---------------------------------------------------------------------------------

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

public class TestRecord {
   public static void main(String []args) {
       String inputfileName = "students.txt";
       File fileToRead = new File (inputfileName);
       try {
        // file read
       Scanner Scanner = new Scanner (fileToRead);
       // read line by line using loop
       while(Scanner.hasNextLine()){
           String line = Scanner.nextLine();
           // split the line into array of strings
           String[] arr = line.split(":");
           // display the strings accordingly
           System.out.println("\nS.No: " + arr[0]);
           System.out.println("First Name: " + arr[1]);
           System.out.println("Last Name: " + arr[2]);
           System.out.println("Telephone: " + arr[3]);
           System.out.print("Courses: ");
           // except first 4 strings in array, rest are courses
           // so loop starts from 4 till array length and print results
           for(int i=4; i<arr.length; i++)      
           System.out.print(arr[i] + ", ");  
           System.out.println("\n----------------------------");
       }
       }catch(Exception e){
       System.out.println("I could not open to the file to read.");
       }
   } // main ends
} // class ends

--------------------------------------------------------------------------------

Code :

-----------------------------------------------------------------------------------------

Output :

Add a comment
Know the answer?
Add Answer to:
I need help with my computer science 2 lab. First I am asked to run the...
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. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Lab 19 - History of Computer Science, A File IO Lab FIRST PART OF CODING LAB:...

    Lab 19 - History of Computer Science, A File IO Lab FIRST PART OF CODING LAB: Step 0 - Getting Starting In this program, we have two classes, FileIO.java and FileReader.java. FileIO.java will be our “driver” program or the main program that will bring the file reading and analysis together. FileReader.java will create the methods we use in FileIO.java to simply read in our file. Main in FileIO For this lab, main() is provided for you in FileIO.java and contains...

  • I am trying to read from a file with with text as follows and I am...

    I am trying to read from a file with with text as follows and I am not sure why my code is not working. DHH-2180 110.25 TOB-6851 -258.45 JNO-1438 375.95 CS 145 Computer Science II IPO-5410 834.15 PWV-5792 793.00 Here is a description of what the class must do: AccountFileIO 1. Create a class called AccountFileIO in the uwstout.cs145.labs.lab02 package. (This is a capital i then a capital o for input/output.) a. This class will read data from a file...

  • This is my current output for my program. I am trying to get the output to...

    This is my current output for my program. I am trying to get the output to look like This is my program Student.java import java.awt.GridLayout; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import javax.swing.JFileChooser; public class Student extends javax.swing.JFrame {     BufferedWriter outWriter;     StudentA s[];     public Student() {         StudentGUI();            }     private void StudentGUI() {         jScrollPane3 = new javax.swing.JScrollPane();         inputFileChooser = new javax.swing.JButton();         outputFileChooser = new javax.swing.JButton();         sortFirtsName = new...

  • import java.io.*; import java.util.Scanner; public class CrimeStats { private static final String INPUT_FILE = "seattle-crime-stats-by-1990-census-tract-1996-2007.csv"; private...

    import java.io.*; import java.util.Scanner; public class CrimeStats { private static final String INPUT_FILE = "seattle-crime-stats-by-1990-census-tract-1996-2007.csv"; private static final String OUTPUT_FILE = "crimes.txt"; public static void main(String[] args) { int totalCrimes = 0; // read all the rows from the csv file and add the total count in the totalCrimes variable try { Scanner fileScanner = new Scanner(new File(INPUT_FILE)); String line = fileScanner.nextLine(); // skip first line while (fileScanner.hasNext()) { String[] tokens = fileScanner.nextLine().split(","); if (tokens.length == 4) { totalCrimes +=...

  • Ok So I have the code I need! and it runs on online codechef IDE! The...

    Ok So I have the code I need! and it runs on online codechef IDE! The code is below: import java.util.Scanner; import java.io.FileWriter; public class Main { public static void main(String[] args) {    Scanner sc = new Scanner(System.in);    double sales; System.out.print("Enter annual sales: "); sales = sc.nextDouble();    double fixed = 30000;    double commission = (7.0*sales)/100.0;    double total = fixed + commission;    System.out.println("Fixed Salary: "+fixed); System.out.println("Annual Sales: "+sales); System.out.println("Commission: "+commission); System.out.println("Total Salary: "+total);      ...

  • I need help debugging this Java program. I am getting this error message: Exception in thread...

    I need help debugging this Java program. I am getting this error message: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2 at population.Population.main(Population.java:85) I am not able to run this program. ------------------------------------------------------------------- import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Scanner; /* Linked list node*/ class node { long data; long year; String country; node next; node(String c,long y,long d) { country=c; year=y; data = d; next = null; } } public class Population { private static node head; public static void push(String...

  • QUESTION The ReadFile class opens and reads a text file. The WriteFile class opens and writes...

    QUESTION The ReadFile class opens and reads a text file. The WriteFile class opens and writes to a file. Compile and run these programs. There are several ways to read/write text files. The examples shown here are just one way of achieving this. Look at the API for the BufferedReader class. The readline() method is a simple way to read the text file line by line. It returns null when the end of the file has been reached. https://docs.oracle.com/javase/8/docs/api/java/io/BufferedReader.html Look...

  • i have to write a program that asks the names of 2 files. the first should...

    i have to write a program that asks the names of 2 files. the first should be open for reading second for writing. the program should read the the contents of the first file change all characters to uppercase and store in the second file. the second file will be a copy of the first file, except that all characters will be uppercase. use notepad to test the program. i got this so far {         String firstfile;         String...

  • Please help me fix my errors. I would like to read and write the text file...

    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...

  • Help check why the exception exist do some change but be sure to use the printwriter...

    Help check why the exception exist do some change but be sure to use the printwriter and scanner and make the code more readability Input.txt format like this: Joe sam, thd, 9, 4, 20 import java.io.File; import java.io.PrintWriter; import java.io.IOException; import java.io.FileNotFoundException; import java.io.FileWriter; import java.util.Scanner; public class Main1 { private static final Scanner scan = new Scanner(System.in); private static String[] player = new String[622]; private static String DATA = " "; private static int COUNTS = 0; public static...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT