I am trying to write a program that merges two arrays from numbers that are in two different text files into a third array.
I have the method done to merge the two arrays into the third array.
But I don't know how to get the numbers from the second file.
Here is my current code :
public static void main(String[] args) {
int[] mergedArray = {};
Scanner input = new Scanner(System.in);
System.out.println("Enter the name of your first file (including file extension): ");
String filename = input.next();
int[] firstArray;
try (Scanner in = new Scanner(new File(filename)))
{
int count = in.nextInt();
firstArray = new int[count];
firstArray[0] = count;
for (int i = 0; in.hasNextInt() && count != -1 && i < count; i++) {
firstArray[i] = in.nextInt();
}
} catch (final FileNotFoundException e) {
System.out.println("That file was not found. Program terminating...");
e.printStackTrace();
}
}
Any help would be appreciated thanks.
If i understood correctly, you just have to create a new Scanner, one for each file.
Like that:
public static void main(String[] args) {
int[] mergedArray = {};
Scanner input = new Scanner(System.in);
System.out.println("Enter the name of your first file (including file extension): ");
String filename1 = input.next();
System.out.println("Enter the name of your second file (including file extension): ");
String filename2 = input.next();
int[] firstArray = null;
int[] secondArray = null;
try {
Scanner in = new Scanner(new File(filename1));
int count = in.nextInt();
firstArray = new int[count];
firstArray[0] = count;
for (int i = 0; in.hasNextInt() && count != -1 && i < count; i++) {
firstArray[i] = in.nextInt();
}
} catch (final FileNotFoundException e) {
System.out.println("That file was not found. Program terminating...");
e.printStackTrace();
}
try {
Scanner in2 = new Scanner(new File(filename2));
int count = in2.nextInt();
secondArray = new int[count];
secondArray[0] = count;
for (int i = 0; in2.hasNextInt() && count != -1 && i < count; i++) {
secondArray[i] = in2.nextInt();
}
} catch (final FileNotFoundException e) {
System.out.println("That file was not found. Program terminating...");
e.printStackTrace();
}
// do the merge operation with the 2 arrays
}
Try this
import java.io.*;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.util.Scanner;
import static java.lang.System.*;
import java.util.Collection;
import java.util.Collections;
import java.util.ArrayList;
import java.util.Arrays;
public final class TwoSourceMergeOne{
public static void main(String[] args) {
Integer [] mergedArray = null;
try(Scanner console = new Scanner(in)){
out.println("Enter the Source file names (including file extensions) : ");
out.print(">> ");
String sourceX = console.next();
out.print("\n>> ");
String sourceY = console.next();
Path sourceXPath = Paths.get(sourceX);
Path sourceYPath = Paths.get(sourceY);
if(!Files.exists(sourceXPath,LinkOption.NOFOLLOW_LINKS) || !Files.exists(sourceXPath,LinkOption.NOFOLLOW_LINKS)){
out.println("Sorry. Some source files are missing. Please make sure that they are available !");
return;
}
Scanner xInput = new Scanner(new FileInputStream(sourceXPath.toFile()));
Scanner yInput = new Scanner(new FileInputStream(sourceYPath.toFile()));
Collection<Integer> sourceXData = new ArrayList<>();
Collection<Integer> sourceYData = new ArrayList<>();
while(xInput.hasNextInt()) sourceXData.add(xInput.nextInt());
while(yInput.hasNextInt()) sourceYData.add(yInput.nextInt());
if(!sourceXData.isEmpty() && !sourceYData.isEmpty()){
Integer [] soure_x_array = sourceXData.toArray(new Integer[sourceXData.size()]);
Integer [] source_y_array = sourceYData.toArray(new Integer[sourceYData.size()]);
mergedArray = new Integer[soure_x_array.length+source_y_array.length];
int index = 0;
for(int x : soure_x_array) mergedArray[index ++] = x;
for(int y : source_y_array) mergedArray[index ++] = y;
out.printf("The merged array is = %s",Arrays.toString(mergedArray));
}else{
out.println("Sorry. No input data !!!");
}
}catch(IOException cause){ cause.printStackTrace();}
}
}
The two source files should be in the same folder as the program.
Related
I am trying to write a java program that reads a text file and counts the number of times each word occurs. But I keep getting the No such element Exception. I assume there is something wrong with the ArrayList or how I am accessing the elements of it. Any help would be appreciated.
package text_analyzer;
import java.io.File;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.List;
public class Text_analyzer
{
public static void main(String[] args) throws Exception
{
File file = new File("TestFile.txt");
Scanner sc = new Scanner(file);
int i = 0, indexOfWord = 0, count = 0;
List<String> words = new ArrayList<String>();
List<Integer> wordCount = new ArrayList<Integer>();
while (sc.hasNextLine())
{
String word = sc.next();
if(words.contains(word))
{
indexOfWord = words.indexOf(word);
count = wordCount.get(indexOfWord);
count = count+1;
wordCount.add(indexOfWord, count);
}
else
{
words.add(i,word);
wordCount.add(i,1);
i++;
}
}
sc.close();
int no_of_elements = words.size();
for(int j = 0; j < no_of_elements; j++)
System.out.println(words.get(j));
}
}
Your logic is correct;
Check the path of the file, and make sure it is present or add an additional check in code.
File Path
Add exception handling for new File() method in case file is not found.
File file = new File("C:\\work\\TestFile.txt");
Scanner sc = null;
try {
sc = new Scanner(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Result: Output result
The program I am coding allows the user to find a matching credit card number in three text files. However, it outputs that no matches have been found in any of the comparisons between the files. If someone could guide me on how to fix this problem, that would be great! Down below is the code for the program.
Edit: it seems that I forgot to place the number 1000 in some of the comparisons between the files. I now have a null exception problem at
if(numbers1[i].compareTo(numbers2[i]) == 0){
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class MatchingNumber {
public static int counter = 0;
public static int flag;
static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
static BufferedReader in2 = new BufferedReader(new InputStreamReader(System.in));
static BufferedReader in3 = new BufferedReader(new InputStreamReader(System.in));
static int x;
static String[] numbers1 = new String[1000];
static String[] numbers2 = new String[1000];
static String[] numbers3 = new String[1000];
public static void main(String[] args) throws IOException {
loadNumbers();
firstCompare();
secondCompare();
thirdCompare();
}
public static void loadNumbers() throws IOException {
String findFile, file;
//ask for location of file
System.out.println("Enter File 1 Location: ");
//Read input
findFile = in.readLine();
//find file
file = findFile + "/creditCards1.txt";
BufferedReader in = new BufferedReader(new FileReader(file));
String findFile1, file1;
//ask for location of file
System.out.println("Enter File 2 Location: ");
//Read input
findFile1 = in2.readLine();
//find file
file1 = findFile1 + "/creditCards2.txt";
BufferedReader in2 = new BufferedReader(new FileReader(file1));
String findFile2,file2;
//ask for location of file
System.out.println("Enter File 3 Location: ");
//Read input
findFile2 = in3.readLine();
//find file
file2 = findFile2 + "/creditCards3.txt";
BufferedReader in3 = new BufferedReader(new FileReader(file2));
for (int i = 0; i < 1000; i++){
//read in the data
numbers1[i] = in.readLine();
numbers2[i] = in2.readLine();
numbers3[i] = in3.readLine();
counter++;
}
in.close();
in2.close();
in3.close();
}
public static void firstCompare() {
boolean found = false;
for (int i = 0; i < 1000; i++){
if(numbers1[i].compareTo(numbers2[i]) == 0){
flag = i;
found = true;
System.out.println(flag + "is the matching number in files 1 and 2");
}
}
if (!found){
System.out.println("No matches found files 1 and 2");
}
}
public static void secondCompare() {
boolean found = false;
for (int i = 0; i < 1000; i++){
if(numbers1[i].compareTo(numbers3[i]) == 0){
flag = i;
found = true;
System.out.println(flag + "is the matching number in files 1 and 3");
}
}
if (!found){
System.out.println("No matches found files 1 and 3");
}
}
public static void thirdCompare() {
boolean found = false;
for (int i = 0; i < 1000; i++){
if(numbers2[i].compareTo(numbers3[i]) == 0){
flag = i;
found = true;
System.out.println(flag + "is the matching number in files 2 and 3");
}
}
if (!found){
System.out.println("No matches found files 2 and 3");
}
}
}
First of all, why do you limit your amount of credit card numbers?
static String[] numbers1 = new String[1000];
static String[] numbers2 = new String[1000];
static String[] numbers3 = new String[1000];
I would recommend using:
static List<String> numbers1 = new List<String>();
static List<String> numbers2 = new List<String>();
static List<String> numbers3 = new List<String>();
This will allow you to increase your project's scalability and reduce redundancy when comparing.
When comparing, you can simply loop through one list and check if another list contains the element that you are looking for:
boolean found = false;
int i = 0;
while(!found)
{
if(numbers1.Contains(numbers2[i])
found = true;
i++;
}
I have written a spellchecker program that checks the spelling of all words in a file. It should read each word of a file and check whether it is contained in a word list. The program should write the incorrect words to a file and I have received an error message on lines 57-58, saying "type mismatch between void to String" and when I ran it on eclipse, I got an unresolved compilation problem" error. What am I doing wrong so it can run smoothly on both Eclipse & on the command line? Here's the code:
import java.util.*;
import java.io.*;
public class SpellChecker {
public static void readDict(){
File file = new File ("words.txt");
ArrayList <String> array = new ArrayList <String> ();
try{
Scanner input = new Scanner (file).useDelimiter("[A-Za-z]");
while (input.hasNext()){
String line = input.nextLine();
String [] wordArray = line.split(" ");
for(String str : wordArray){
array.add(str);
}
}
input.close();
}
catch(FileNotFoundException e){
System.out.println("File is not found.");
System.exit(1);
}
return;
}
public static void readFile(){
File file = new File ("mary.txt");
String [] array;
String [] array2 = null;
try{
Scanner input = new Scanner (file);
int i = 0;
array = new String [10];
while(i < array.length && input.hasNext()){
String story = input.nextLine();
String[] storyarray = story.split(" ");
array2[i] = storyarray[i];
i++;
for(i = 0; i < array2.length; i++){
System.out.println(array2[i]);
}
input.close();
}
}
catch(FileNotFoundException e){
System.out.println("File cannot be found.");
System.exit(1);
}
}
public static void main(String[] args) {
args[0] = readDict();
args[1] = readFile();
if(args == 4){
System.out.println(args[0]);
System.out.println(args[1]);
}
}
public static Scanner input = new Scanner(System.in);
}
I am writing code that reads in a text file through the command line arguments in the main method and prints out each word in it on its own line without printing any word more than once, it will not print anything, can anyone help?
import java.util.*;
import java.io.*;
public class Tokenization {
public static void main(String[] args) throws Exception{
String x = "";
String y = "";
File file = new File(args[0]);
Scanner s = new Scanner(file);
String [] words = null;
while (s.hasNext()){
x = s.nextLine();
}
words = x.split("\\p{Punct}");
String [] moreWords = null;
for (int i = 0; i < words.length;i++){
y = y + " " + words[i];
}
moreWords = y.split("\\s+");
String [] unique = unique(moreWords);
for (int i = 0;i<unique.length;i++){
System.out.println(unique[i]);
}
s.close();
}
public static String[] unique (String [] s) {
String [] uniques = new String[s.length];
for (int i = 0; i < s.length;i++){
for(int j = i + 1; j < s.length;j++){
if (!s[i].equalsIgnoreCase(s[j])){
uniques[i] = s[i];
}
}
}
return uniques;
}
}
You have several problems:
you're reading whole file line by line, but assign only last line to variable x
you're doing 2 splits, both on regexp, it is enough 1
in unique - you're filling only some parts of array, other parts are null
Here is shorter version of what you need:
import java.io.File;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class Tokenization {
public static void main(String[] args) throws Exception {
Set<String> words = new HashSet<String>();
try {
File file = new File(args[0]);
Scanner scanner = new Scanner(file);
while (scanner.hasNext()) {
String[] lineWords = scanner.nextLine().split("[\\p{Punct}\\s]+");
for (String s : lineWords)
words.add(s.toLowerCase());
}
scanner.close();
} catch (Exception e) {
System.out.println("Cannot read file [" + e.getMessage() + "]");
System.exit(1);
}
for (String s : words)
System.out.println(s);
}
}
For a homework assignment, I need to create a class that that can read and write Byte arrays to/from a file. I have successfully created classes that can read and write CSV and text, however I am having some difficulty, when it comes to arrays. The code below is features the class that I have written. It is largely based on my CSV class, the FileInput class http://www.devjavasoft.org/SecondEdition/SourceCode/Share/FileInput.java) and FileOutput Class (http://www.devjavasoft.org/SecondEdition/SourceCode/Share/FileOutput.java).
When running the program to read a text file I get the following error message:
"Exception in thread "main" java.lang.NullPointerException
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileInputStream.<init>(FileInputStream.java:101)
at java.io.FileReader.<init>(FileReader.java:58)
at com.gc01.FileManager.FileInput.<init>(FileInput.java:22)
at com.gc01.FileManager.ByteManager.readByte(ByteManager.java:28)
at com.gc01.FileManager.ByteManager.main(ByteManager.java:85)"
And my code:
import java.util.Scanner;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
public class ByteManager {
public String getByteFile(){
Scanner sc = new Scanner (System.in);
System.out.println("Please enter the file directory of the chosen txt file?");
System.out.println("For Example: /Users/UserName/Downloads/FileName.txt");
///Users/ReeceAkhtar/Desktop/FileName.txt
final String fileName = sc.nextLine();
System.out.println("How many columns are in the file?");
final int columns = sc.nextByte();
System.out.println("How many rows are in the file?");
final int rows = sc.nextByte();
return fileName;
}
public void readByte(final String fileName, int columns, int rows){
FileInput in = new FileInput(fileName);
int [] [] data = new int[rows] [columns];
String [] line;
for (int i = 0; i < rows; i++){
line = in.readString().split("\t");
for (int j = 0; j < columns; i++){
data [i][j] = Byte.parseByte(line[j]);
}
}
System.out.println("******File Read*****");
}
public String chooseFileOutput(){
Scanner sc = new Scanner (System.in);
System.out.println("Please enter the file directory for the output of the chosen file");
System.out.println("For Example: /Users/UserName/Downloads/FileName.txt");
///Users/ReeceAkhtar/Desktop/GeoIPCountryWhois.csv
final String fileNameOUT = sc.nextLine();
System.out.println("How many columns are in the file?");
final int columnsOut = sc.nextByte();
System.out.println("How many rows are in the file?");
final int rowsOut = sc.nextByte();
return fileNameOUT;
}
public void writeByte(final String fileNameOUT, int columnsOut, int rowsOut){
FileOutput createData = new FileOutput (fileNameOUT);
int newData = 0;
System.out.println("Enter data. To finish, enter 'TERMINATE_FILE'");
while(!"TERMINATE_FILE".equals(newData)){
Scanner input = new Scanner (System.in);
int [] [] data = new int[rowsOut] [columnsOut];
String [] line = null;
for (int i = 0; i < rowsOut; i++){
createData.writeInteger(newData = input.nextByte());
System.out.println("\t");
for (int j = 0; j < columnsOut; i++){
data [i][j] = Byte.parseByte(line[j]);
}
}
createData.close();
}
}
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
final ByteManager object = new ByteManager ();
System.out.println("1 for Read File, 2 for Write file");
String choice = in.nextLine();
if("1".equals(choice)){
object.getByteFile();
object.readByte(null, 0, 0);
} else if ("2".equals(choice)){
object.chooseFileOutput();
object.writeByte(null, 0, 0);
} else{
System.out.println("Goodbye!");
System.exit(0);
}
}
}
UPDATE
Thank you for your comments and advice below, I have now run into a another problem that I can not work out. I have re-written my readByte method. However when I now run it, I no longer get compiler errors (thanks to your advice), however I can not get the contents of the file to print. Instead the console just displays "File Read". I have studied various resources yet I can not find the solution. I am sure it is a simple mistake somewhere. The contents of the file I am trying to read is also below.
public String getByteFile(){
Scanner sc = new Scanner (System.in);
System.out.println("Please enter the file directory of the chosen txt file?");
System.out.println("For Example: /Users/UserName/Downloads/FileName.txt");
///Users/ReeceAkhtar/Desktop/FileName.txt
final String fileName = sc.nextLine();
System.out.println("How many columns are in the file?");
final int columns = sc.nextInt();
System.out.println("How many rows are in the file?");
final int rows = sc.nextInt();
return fileName;
}
public void readByte(final String fileName, int rows,int columns){
BufferedReader br = null;
String[] line;
String splitBy = "\t";
int [][] data = new int[rows] [columns];
try {
br = new BufferedReader(new FileReader(fileName));
for (int i = 0; i < rows; i++){
line = br.toString().split(splitBy);
for (int j = 0; j < columns; j++){
data[i] [j] = Integer.parseInt(line[j]);
System.out.println(data[i][j]);
}
}
} catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("*****File Read*****");
}
File Contents (separated by tab)
123 6565
123 6564
123 6563
123 6562
This code is the source of the error
object.readByte(null, 0, 0);
The parameter null is invalid state for FileInput. It should be a file name string.
You are passing null argument to readByte() from main()
object.readByte(null, 0, 0);
And in readByte()
FileInput in = new FileInput(fileName); //here it throws NPE
Pass valid file name.
NullPointerException
public class NullPointerException
extends RuntimeException
Thrown when an application attempts to use null in a case where an object is required. These include:
Calling the instance method of a null object.
Accessing or modifying the field of a null object.
Taking the length of null as if it were an array.
Accessing or modifying the slots of null as if it were an array.
Throwing null as if it were a Throwable value.