Question

In: Computer Science

Write a program in Java to: Read a file containing ones and zeros into a two-dimensional...

Write a program in Java to:

Read a file containing ones and zeros into a two-dimensional int array. Your program must (1) read the name of the file from the command-line arguments, (2) open the file, (3) check that each line has the same number of characters and (4) check that the only characters in a line are ones and zeros. If there is no such command-line argument or no such file, or if any of the checks fail, your program should exit, and it's ok if your program exits by returning from main, by throwing an exception, or in any other way.

Must use ArrayList instead of arrays, and this program must not declare any int array variables. Your ones and zeros will be saved in a variable declared and initialized as:
java.util.ArrayList<java.util.ArrayList<Integer>> dataFromFile = new java.util.ArrayList<java.util.ArrayList<Integer>>();

You may again need to read the file twice, but you may instead be able to read it just once -- both solutions are fine for this assignment, it is up to you.

Print the array by columns and rows, so that it prints (the below zeros and ones is the input text file):

0000000000001000000000000
0000000000010100000000000
0000000000100010000000000
0000000001000001000000000
0000000010000000100000000
0000000100000000010000000
0000001000000000001000000
0000010000000000000100000
0000100000000000000010000
0001000000000000000001000
0010000000000000000000100
0100000000000000000000100
1000000000000000000000100
0100000000000000000000100
0010000000000000000000100
0001000000000000000001000
0000100000000000000010000
0000010000000000000100000
0000001000000000001000000
0000000100000000010000000
0000000010000000100000000
0000000001000001000000000
0000000000100010000000000
0000000000010100000000000
0000000000001000000000000

Solutions

Expert Solution

All operations are performed successfully

1)read the name of the file from the command-line arguments

2)open the file

3)check that each line has the same number of characters

4)check that the only characters in a line are ones and zeros

5)Print the array by columns and rows

import java.util.Scanner;
import java.util.*; 
import java.io.File;
import java.io.FileNotFoundException;
public class Main {
    public static void main(String args[]) {
        if(0 < args.length){ //check if fine name given as input or not
            String filename = args[0];
            try {
                File myObj = new File(filename);    //creating file object
                Scanner fileobj = new Scanner(myObj);   //reading file using file object

                int len = 0;        //declaring len variable which is used to check if each line contain same number of characters.

                ArrayList<ArrayList<Integer> > datafromfile = new ArrayList<ArrayList<Integer> >();
                int k = 0;
                
                while (fileobj.hasNextLine()) {
                    String data = fileobj.nextLine();
                    datafromfile.add(new ArrayList<Integer>());

                    if(len == 0) len = data.length();  //for 1st line in file
                    else{
                        if(len!=data.length()){  //if any line contain extra number of characters/elements we simply return
                            return;
                        }
                    }

                    for(int i = 0;i<data.length();i++){
                        if(data.charAt(i)!= '0' || data.charAt(i)!='1'){    //check if given file contains only 0 and 1
                            return;
                        }else{
//if data is 0 or 1 then we store that in our array list
                            datafromfile.get(k).add(i,(int)data.charAt(i));
                        }
                    }
                    k++;
                    // System.out.println(data);
                }
                fileobj.close();
                // data from input file is printed
                for(int i = 0;i<datafromfile.size();i++){
                    for(int j = 0; j < datafromfile.get(i).size(); j++){
                        System.out.println(datafromfile.get(i).get(j));
                    }
                    System.out.println();
                }
            } catch (FileNotFoundException e) {
                System.out.println("An error occurred.");
                e.printStackTrace();
            }
        }else{
            return;
        }
    }
}

OUTPUT :


Related Solutions

Write an assembly program for the MSP430 to calculate the number of zeros and ones in...
Write an assembly program for the MSP430 to calculate the number of zeros and ones in an array. If the number of zeros is more than the number of ones, the red LED(connected to P1.0 on the MSP430 launchpad) will turn on. Otherwise, the green LED (connected to P1.6 on the MSP430 launchpad) will turn on.
Please write a java program to write to a text file and to read from a...
Please write a java program to write to a text file and to read from a text file.
Write a C++ program to read a data file containing the velocity of cars crossing an...
Write a C++ program to read a data file containing the velocity of cars crossing an intersection. Then determine the average velocity and the standard deviation of this data set. Use the concept of vector array to store the data and perform the calculations. Include a function called “Standard” to perform the standard deviation calculations and then return the value to the main function for printing. Data to use. 10,15,20,25,30,35,40,45,50,55. Please use something basic.
Your assignment is to write a C++ program to read a text file containing the information...
Your assignment is to write a C++ program to read a text file containing the information of the employees of a company, load them into memory and perform some basic human resources operations. This assignment will help you practice: multiple file programming, classes, public and private methods, dynamic memory allocation, constructors and destructors, singly linked list and files. Implementation This lab assignment gives you the opportunity to practice creating classes and using dynamic memory in one of the required classes....
Write a Java program to read a set of integers from a file, dataX, and a...
Write a Java program to read a set of integers from a file, dataX, and a set of ranges from a second file, rangeX, and, for each range [a, b] in rangeX, report the SUM of all the integers in dataX which are in the range [a, b]. As the integers are read from file dataX, insert them in a binary search tree. After all the integers have been inserted into the binary search tree, read the ranges from file...
Write a java program that will read a file called stateinfo.txt and will store the information...
Write a java program that will read a file called stateinfo.txt and will store the information of the file into a map. The stateinfo.txt file contains the names of some states and their capitals. The format of stateinfo.txt file is as follows. State                Capital ---------                         ----------- NSW               Sydney VIC                 Melbourne WA                 Perth TAS                 Tasmania QLD                Brisbane SA                   Adelaide The program then prompts the user to enter the name of a state. Upon receiving the user input, the program should...
Write a program in Java, that creates a Jframe with a menu containing only file. Inside...
Write a program in Java, that creates a Jframe with a menu containing only file. Inside file there should be items: Open, Save, and Save As. Selecting open prompts the user to input a file name to a txt document containing employee information and displays a Jtable with the information, which can be edited. With column headers {"First Name" , "Last Name" , "Occupation" , "Office #"} Example: Gary Osbourn Teacher 113 Michelle Ramirez Teacher 101 Ava Gomez Principal 120...
Write a program in Java that reads a file containing data about the changing popularity of...
Write a program in Java that reads a file containing data about the changing popularity of various baby names over time and displays the data about a particular name. Each line of the file stores a name followed by integers representing the name’s popularity in each decade: 1900, 1910, 1920, and so on. The rankings range from 1 (most popular) to 1000 (least popular), or 0 for a name that was less popular than the 1000th name. A sample file...
In java, Write a program that reads a data file containing final exam scores for a...
In java, Write a program that reads a data file containing final exam scores for a class and determines the number of passing scores (those greater than 60) and the number of failing scores (those less than 60). The average score as well as the range of scores should also be determined. The program should request the name of the data file from the end user. The file may contain any number of scores. Using a loop, read and process...
JAVA Assignment: Project File Processing. Write a program that will read in from input file one...
JAVA Assignment: Project File Processing. Write a program that will read in from input file one line at a time until end of file and output the number of words in the line and the number of occurrences of each letter. Define a word to be any string of letters that is delimited at each end by either whitespace, a period, a comma or the beginning or end of the line. You can assume that the input consists entirely of...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT