Java Problem I. Solve the following programming problem in Java language . Provi
ID: 3837657 • Letter: J
Question
Java Problem
I. Solve the following programming problem in Java language. Provide the CODE and a SCREENSHOT of a test run of the code.
Design a program that merges the content of two text files containing chemical elements sorted by atomic number and produces a sorted file of elements. The program should read the content from the two files, and outputs the data ordered by atomic number to the output file. Assume the name of the output file. Use the provided files. The format of each file will be as following:
ATOMIC_NUMBER
ELEMENT_NAME
ELEMENT_ABBREVIATION
ATOMIC_WEIGHT
chems:
These is my code it doesn't work I need help:
ChemicalTest.java
package chemicaltest;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;
public class ChemicalTest {
public static void main(String[] args) throws IOException {
File file = new File("inp1.txt");
Chemical c[]=new Chemical[18];
int num;
String nam;
String abbre;
double weight;
int i=0;
try {
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
num=sc.nextInt();
nam=sc.next();
abbre=sc.next();
weight=sc.nextDouble();
c[i]=new Chemical(num,nam,abbre,weight);
i++;
}
sc.close();
}
catch (FileNotFoundException e) {
}
file = new File("inp2.txt");
try {
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
num=sc.nextInt();
nam=sc.next();
abbre=sc.next();
weight=sc.nextDouble();
c[i]=new Chemical(num,nam,abbre,weight);
i++;
}
sc.close();
}
catch (FileNotFoundException e) {
}
Arrays.sort(c);
file = new File("out.txt");
BufferedWriter out = new BufferedWriter(new FileWriter(file));
for(int k=0;k<i;k++)
{
out.write(Integer.toString(c[k].atomicNumber));
out.newLine();
out.write(c[k].name);
out.newLine();
out.write(c[k].abbrev);
out.newLine();
out.write(Double.toString(c[k].atomicWeight));
out.newLine();
}
out.close();
}
}
Chemical.java
package chemicaltest;
public class Chemical implements Comparable<Chemical> {
int atomicNumber;
String name;
String abbrev;
double atomicWeight;
public Chemical(int a,String n,String abbr,double w)
{
atomicNumber=a;
name=n;
abbrev=abbr;
atomicWeight=w;
}
@Override
public int compareTo(Chemical item) {
return Integer.compare(this.atomicNumber, item.atomicNumber);
}
}
Explanation / Answer
inp1.txt
inp2.txt
out.txt
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.