Comparing two string arrays in java using string.equals - java

I have a method that works fine and gives desired result. Here is it's code:
public class arraycomparison {
public static void main(String args[]) {
try {
Scanner sc1 = new Scanner(new FileInputStream("/Users/esna786/File1.txt"));
Scanner sc2 = new Scanner(new FileInputStream("/Users/esna786/File2.txt"));
List<String> File1Content = new ArrayList<String>();
List<String> File2Content = new ArrayList<String>();
List<String> commonWords = new ArrayList<String>();
//Getting the contents of File1
while (sc1.hasNext()) {
File1Content.add(sc1.next());
}
String arr1[] = File1Content.toArray(new String[File1Content.size()]);
//Getting the contents of File1
while (sc2.hasNext()) {
File2Content.add(sc2.next());
}
String arr2[] = File2Content.toArray(new String[File2Content.size()]);
int count = 0;
for (int i = 0; i < arr1.length; i++) {
for (int j = 0; j < arr2.length; j++) {
if (arr1[i].equals(arr2[j])) {
commonWords.add(arr1[i]);
count++;
}
}
}
String[] comWords = commonWords.toArray(new String[commonWords.size()]);
System.out.println("Total Number of Common Words are: "+comWords.length);
for (int i = 0; i < comWords.length; i++) {
System.out.println(i + 1 + ": " + comWords[i]);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
it's out put is,
Total Number of Common Words are: 7
1: apple
2: ball
3: cat
4: duck
5: elephant
6: fan
7: goat
BUILD SUCCESSFUL (total time: 0 seconds)
Using the same files when I run the program code below almost same as above:
//Counting the number of matched words
public int getCommonWords(File File1, File File2) throws IOException {
try {
Scanner sc1 = new Scanner(new FileInputStream(File1));
Scanner sc2 = new Scanner(new FileInputStream(File1));
List<String> File1Content = new ArrayList<String>();
List<String> File2Content = new ArrayList<String>();
List<String> commonWords = new ArrayList<String>();
//Getting the contents of File1
while (sc1.hasNext()) {
File1Content.add(sc1.next());
}
String arr1[] = File1Content.toArray(new String[File1Content.size()]);
//Getting the contents of File1
while (sc2.hasNext()) {
File2Content.add(sc2.next());
}
String arr2[] = File2Content.toArray(new String[File2Content.size()]);
int count = 0;
for (int i = 0; i < arr1.length; i++) {
for (int j = 0; j < arr2.length; j++) {
if (arr1[i].equals(arr2[j])) {
commonWords.add(arr1[i]);
count++;
}
}
}
String[] comWords = commonWords.toArray(new String[commonWords.size()]);
System.out.println("Total Number of Common Words are: " + comWords.length);
for (int i = 0; i < comWords.length; i++) {
System.out.println(i + 1 + ": " + comWords[i]);
}
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
it displays following in the output area:
run:
Total words of File1.txt are: 11
Total Number of Common Words are: 11
1: apple
2: ball
3: cat
4: duck
5: elephant
6: fan
7: goat
8: a
9: b
10: c
11: d
it is even displaying the unmatched words as well, why is it so?
Please help.

You are getting the null pointer exception for an obvious reason, the variable commonWord is not pointing to an array (you didn't allocate memory for storing the array strings).
String commonWords[]=null;
You have 2 solutions:
Use fixed memory allocation:
String commonWords[]= new String[Math.min(arr1.length, arr2.length)];
int commonCount = 0;
....
commonWords[commonCount++] = arr2[i]
Use dynamic memory allocation:
ArrayList<String> commonWords = new ArrayList<>();
...
commonWords.add(arr2[i]);

If you want to preserve your logic and data structures, then use something like:
String commonWords[] = new String [Math.min(arr1.length, arr2.length)];
It's far from perfect, but will allow you to assign values to your array.
Then to print:
for(String str : commonWords) {
if (str != null) {
System.out.println(str);
}
}

Related

Read the data from the file and store it in two arrays

hello I am having trouble with trying to read a file and take the two columns of the file and put them respectively in their own arrays. Any help would be appreciated! Thanks!
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
// TODO Auto-generated method stub
System.out.println("Please enter the name of the file to be read");
String fileName = keyboard.nextLine();
Scanner chirping = null;//user input for file name
boolean fileValue = false; //this makes the value false until the correct file name is inputed
while(!fileValue) {
try {
FileReader dates = new FileReader(fileName); // connects to the user inputted file
chirping = new Scanner(dates); //scans the file
fileValue = true; //turns file value to true which takes us out of the while loop
}//end try
catch(IOException e) {
System.out.println("File Not Found, Please Try Again: ");
fileName = keyboard.nextLine();
}//end catch
}// end while
double[] dataSet = new double[30];
double[] chirpFreq = new double[30];
double[] temp = new double[30];
//double[] temp = new double[chirping.nextInt()];
for(int i = 0; chirping.hasNextDouble(); i++) {
dataSet[i] = chirping.nextDouble();
}
for(int j = 0; j <= dataSet.length; j++) {
if(j%2 == 0) {
chirpFreq[j] = dataSet[j];
}
else {
temp[j] = dataSet[j];
}
}
for(int i = 0; i <= chirpFreq.length; i++) {
System.out.print(chirpFreq[i]+ " ");
}
chirping.close();
}
//These are the values i am trying to sort into two separate arrays
20 88.6
16 71.6
19.8 93.3
18.4 84.3
17.1 80.6
15.5 75.2
14.7 69.7
17.1 82
15.4 69.4
16.2 83.3
15 79.6
17.2 82.6
16 80.6
17 83.5
14.4 76.3
I don't usually use nextDouble() to read files so i don't know what your problem is exactly, but you can refactor your code to this:
double[] firstColumn = new double[30];
double[] secondColumn = new double[30];
String line = "";
int i = 0;
// keep reading until there is nothing to read
while( (line = chirping.nextLine()) != null ) {
// this is a regex that splits the line into an array based on whitespace
// just use " " if your data is separated by space or "\t" if tab
String[] columns = line.split("\\s+");
firstColumn[i] = Double.parseDouble(columns[0]);
secondColumn[i++] = Double.parseDouble(columns[1]);
}
chirping.close();

reading file and adding into 2 dimensional double array

Im trying to read a file full of coordinates and then putting everything into double 2 dimensional array. When i run the code i get the exception error. Been trying to read the file for hours now(im a noobie in java)
Scanner input = new Scanner(new File(filename));
int row=0;
int col=0;
int rwn=0;
String[] line= new String[rwn];
while(input.hasNextLine()) {
line = input.nextLine().split(" ");//spliting 1
rwn++;
}
double[][] arrayOfEarth = new double[rwn][];//creating array for pairs
//itterating array ^ of splitting 1
for (int i=0;i<rwn;i++){
String[] ln =line[i].split(",");
double a= Double.parseDouble(ln[0]);
double b=Double.parseDouble(ln[1]);
double[] val={a,b};//adding the a and b doubles out of string to the value
arrayOfEarth[i]=val;//add arr to arr of arr
}
for (double[] c:arrayOfEarth){
System.out.println(String.format("%.0f and %.2f",c[0],c[1]));
}
}
catch (Exception e) {
System.out.println("Error bruh: "); e.printStackTrace();
}```
Your code confused me a bit.
But you can try this:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class App {
public static void main(String[] args) {
// Define sample data
String coord = ""
+ "0 90 -4228\n"
+ "0.166666666667 90 -4228\n"
+ "0.333333333333 90 -4228\n"
+ "0.5 90 -4228\n"
+ "0.666666666667 90 -4228";
Scanner input = new Scanner(coord);
int rwn = 0;
// Define a 'arrayOfEarth' as list
ArrayList<Double[]> arrayOfEarth = new ArrayList<>();
while (input.hasNextLine()) {
++rwn;
String[] line = input.nextLine().split(" ");
if (line.length == 0) {
continue;
}
arrayOfEarth.add(parseLine(line, rwn));
}
arrayOfEarth.stream()
.forEach(v -> System.out.println(Arrays.toString(v) + "\n"));
}
private static Double[] parseLine(String[] line, int row) {
if (line.length != 3) {
throw new IllegalArgumentException("Missing valiues in line " + row);
}
Double[] doubles = new Double[3];
for (int i = 0; i < 3; i++) {
try {
doubles[i] = Double.parseDouble(line[i]);
} catch (NumberFormatException e) {
throw new NumberFormatException("NAN in " + row + "/" + i + ". value: " + line[i]);
}
}
return doubles;
}
}
This is not 'clean' code - only an example.
I have used the Stream-API. If you use a Java Version < 8 you have to rewrite it with a traditional for-loop.
Scanner input = new Scanner(new File(filename));
int row=0;
int col=0;
int rwn=0;
//String[] line= new String[rwn]; you created line with zero length;
while(input.hasNextLine()) {
line = input.nextLine().split(" ");//spliting 1
rwn++;
}
String[] line= new String[rwn];
double[][] arrayOfEarth = new double[rwn][];//creating array for pairs
//itterating array ^ of splitting 1
for (int i=0;i<rwn;i++){
String[] ln =line[i].split(",");
double a= Double.parseDouble(ln[0]);
double b=Double.parseDouble(ln[1]);
double[] val={a,b};//adding the a and b doubles out of string to the value
arrayOfEarth[i]=val;//add arr to arr of arr
}
for (double[] c:arrayOfEarth){
System.out.println(String.format("%.0f and %.2f",c[0],c[1]));
}
}
catch (Exception e) {
System.out.println("Error bruh: "); e.printStackTrace();
}```
String[] line= new String[rwn]; has to be under while statement. you created line with 0 length

When I run my code I get (0, null) and cant figure out why

I am creating a program that is reading a file of names and ages then printing them out in ascending order. I am parsing through the file to figure out the number of name age pairs and then making my array that big.
The input file looks like this:
(23, Matt)(2000, jack)(50, Sal)(47, Mark)(23, Will)(83200, Andrew)(23, Lee)(47, Andy)(47, Sam)(150, Dayton)
When I am running my code I get the output of (0,null) and I am not sure why. I have been trying to fix it for a while and am lost. If anyone can help that would be great My code is below.
public class ponySort {
public static void main(String[] args) throws FileNotFoundException {
int count = 0;
int fileSize = 0;
int[] ages;
String [] names;
String filename = "";
Scanner inputFile = new Scanner(System.in);
File file;
do {
System.out.println("File to read from:");
filename = inputFile.nextLine();
file = new File(filename);
//inputFile = new Scanner(file);
}
while (!file.exists());
inputFile = new Scanner(file);
if (!inputFile.hasNextLine()) {
System.out.println("No one is going to the Friendship is magic Party in Equestria.");
}
while (inputFile.hasNextLine()) {
String data1 = inputFile.nextLine();
String[] parts1 = data1.split("(?<=\\))(?=\\()");
for (String part : parts1) {
String input1 = part.replaceAll("[()]", "");
Integer.parseInt(input1.split(", ")[0]);
fileSize++;
}
}
ages = new int[fileSize];
names = new String[fileSize];
while (inputFile.hasNextLine()) {
String data = inputFile.nextLine();
String[] parts = data.split("(?<=\\))(?=\\()");
for (String part : parts) {
String input = part.replaceAll("[()]", "");
ages[count] = Integer.parseInt(input.split(", ")[0]);
names[count] = input.split(", ")[1];
count++;
}
}
ponySort max = new ponySort();
max.bubbleSort(ages, names, count);
max.printArray(ages, names, count);
}
public void printArray(int ages[], String names[], int count) {
System.out.print("(" + ages[0] + "," + names[0] + ")");
// Checking for duplicates in ages. if it is the same ages as one that already was put in them it wont print.
for (int i = 1; i < count; i++) {
if (ages[i] != ages[i - 1]) {
System.out.print("(" + ages[i] + "," + names[i] + ")");
}
}
}
public void bubbleSort(int ages[], String names[], int count ){
for (int i = 0; i < count - 1; i++) {
for (int j = 0; j < count - i - 1; j++) {
// age is greater so swaps age
if (ages[j] > ages[j + 1]) {
// swap the ages
int temp = ages[j];
ages[j] = ages[j + 1];
ages[j + 1] = temp;
// must also swap the names
String tempName = names[j];
names[j] = names[j + 1];
names[j + 1] = tempName;
}
}
}
}
}
output example
File to read from:
file.txt
(0,null)
Process finished with exit code 0
What your code does is to Scan the file twice.
In the first loop you do
String data1 = inputFile.nextLine();
Code reads first line and then scanner goes to the next (second) line.
Later you do again inputFile.nextLine(); The second line is empty and the code never goes into the second loop and content is never read.
If you can use Lists, you should create two array lists and add ages and names into the arraylists in the first scan, so you scan the file once. When done, you could get the Array out of the arraylist.
If you should only use arrays and you want a simple update, just add another Scanner before the second loop:
ages = new int[fileSize];
names = new String[fileSize];
inputFile = new Scanner(file); // add this line

Searching in arraylist<String[]> from user input

I want to search in an arraylist from a user input but my if condition doesn't seem to work. Using boolean and .contains() doesn't work for my programme either. This is the coding:
String phone;
phone=this.text1.getText();
System.out.println("this is the phone: " + phone);
BufferedReader line = new BufferedReader(new FileReader(new File("C:\\Users\\Laura Sutardja\\Documents\\IB DP\\Computer Science HL\\cs\\data.txt")));
String indata;
ArrayList<String[]> dataArr = new ArrayList<String[]>();
while ((indata = line.readLine()) != null) {
String[] club = new String[2];
String[] value = indata.split(",", 2);
//for (int i = 0; i < 2; i++) {
int n = Math.min(value.length, club.length);
for (int i = 0; i < n; i++) {
club[i] = value[i];
}
boolean aa = dataArr.contains(this.text1.getText());
if(aa==true)
text2.setText("The data is found.");
else
text2.setText("The data is not found.");
dataArr.add(club);
}
for (int i = 0; i < dataArr.size(); i++) {
for (int x = 0; x < dataArr.get(i).length; x++) {
System.out.printf("dataArr[%d][%d]: ", i, x);
System.out.println(dataArr.get(i)[x]);
}
}
}
catch ( IOException iox )
{
System.out.println("Error");
}
Your dataArr is a list of String[], and you are searching for a String. The two are different kind of objects.
I don't really know how the content of the club array looks like, but you should either change dataArr in order to hold plain String, or to write a method which looks iteratively in dataArr for a String[] containing the output of this.text1.getText().
There is a lot wrong with the program. I assume you want to read a textfile and store each line in the arraylist. To do this you have to split each line of the textfile and store that array in the arrayList.
String[] value;
while ((indata = line.readLine()) != null) {
value = indata.split(",");
dataArr.add(value);
}
Now you have the contents of the file in the arrayList.
Next you want to compare the userinput with each element of the arraylist.
int j = 0;
for (int i = 0; i < dataArr.size(); i++) {
String[] phoneData = dataArr.get(i);
if (phoneData[1].equals(phone)) { // i am assuming here that the phone number is the 2nd element of the String[] array, since i dont know how the textfile looks.
System.out.println("Found number.");
club[j++] = phoneData[1];
} else if (i == dataArr.size()-1) {
System.out.println("Didn't find number.");
}
}
Edit:
As requested:
String phone;
phone = "38495";
System.out.println("this is the phone: " + phone);
BufferedReader line = new BufferedReader(new FileReader(new File("list.txt")));
String indata;
ArrayList<String[]> dataArr = new ArrayList<>();
String[] club = new String[2];
String[] value;// = indata.split(",", 2);
while ((indata = line.readLine()) != null) {
value = indata.split(",");
dataArr.add(value);
}
int j = 0;
for (int i = 0; i < dataArr.size(); i++) {
String[] phoneData = dataArr.get(i);
if (phoneData[1].equals(phone)) {
System.out.println("Found number.");
club[j++] = phoneData[1];
break;
} else if (i == dataArr.size()-1) {
System.out.println("Didn't find number.");
}
}
I hope this makes sense now.

summing column by column in java

i have file txt in desktop :
1 5 23
2 5 25
3 30 36
i want sum column by column 1 + 2 + 3 =... and 5 + 5...n and 23,...n
Scanner sc = new Scanner (file("patch");
while (sc.hasNextLine)
{
//each sum by column
}
help me please thanks
I would use a try-with-resources to clean up my Scanner using the File. Also, you could construct a Scanner around the line of input to get your int columns (that doesn't need to be closed because String(s) aren't closable anyway). Something like,
try (Scanner sc = new Scanner(new File("patch"))) {
while (sc.hasNextLine()) {
String line = sc.nextLine();
Scanner row = new Scanner(line);
long sum = 0;
int count = 0;
while (row.hasNextInt()) {
int val = row.nextInt();
if (count == 0) {
System.out.print(val);
} else {
System.out.printf(" + %d", val);
}
sum += val;
count++;
}
System.out.println(" = " + sum);
}
} catch (IOException e) {
e.printStackTrace();
}
As the Scanner(String) Constructor Javadoc documents
Constructs a new Scanner that produces values scanned from the specified string.
Edit To sum the columns is a little trickier, but you could read everything into a multidimensional List<List<Integer>> like
try (Scanner sc = new Scanner(new File("patch"))) {
List<List<Integer>> rows = new ArrayList<>();
int colCount = 0;
while (sc.hasNextLine()) {
List<Integer> al = new ArrayList<>();
String line = sc.nextLine();
Scanner row = new Scanner(line);
colCount = 0;
while (row.hasNextInt()) {
colCount++;
int val = row.nextInt();
al.add(val);
}
rows.add(al);
}
for (int i = 0; i < colCount; i++) {
long sum = 0;
for (List<Integer> row : rows) {
sum += row.get(i);
}
if (i != 0) {
System.out.print("\t");
}
System.out.print(sum);
}
System.out.println();
} catch (IOException e) {
e.printStackTrace();
}
Edit 2 For efficiencies sake, you might prefer to use a Map like
try (Scanner sc = new Scanner(new File("patch"))) {
Map<Integer, Integer> cols = new HashMap<>();
while (sc.hasNextLine()) {
String line = sc.nextLine();
Scanner row = new Scanner(line);
int colCount = 0;
while (row.hasNextInt()) {
int val = row.nextInt();
if (cols.containsKey(colCount)) {
val += cols.get(colCount);
}
cols.put(colCount, val);
colCount++;
}
}
for (int i : cols.values()) {
System.out.printf("%d\t", i);
}
System.out.println();
} catch (IOException e) {
e.printStackTrace();
}
Please find the code. Please go through the comments.
This is one way of doing for your reference. I want you to try other ways to improve your knowledge rather just using this code.
int sums[] = null;
while (sc.hasNextLine())
{
String row = sc.next();// get first row
String[] values = row.split(" ");// split by space
if(null == sums)
{
sums = new int[values.length];// create sum array with first row size
}
int index = 0;
for (String value : values)
{
sums[index] = sums[index]+Integer.parseInt(value);//adding current row value to current sum
index++;
}
}
if(null != sums)
{
int index=0;
for (int sum : sums)
{
System.out.println("Sum of column "+index+" : "+sum);// Printing each column sum
index++;
}
}
If your file is CSV formatted, then split line by comma(",") and find number of columns based on split array length.
Like below:
String line = sc.next();
String[] lineArr = line.split(",");
int len = lineArr.length;
create array of arraylists of size len and store each column field in the respective arraylist.
finally, at the end apply sum on each arraylist to calculate sum of each column values.

Categories