I have written a program to extract all integer value in the file and find the duplicate integer. But I want only those Integer value which is like ID="****.." / id="****..". I don't want to consider "dependsOnPresenceOf" value whatever it is.
My File is : for example
<line id="24867948" dependsOnPresenceOf="7417840">
<element text="Card Balance " id="18829409" dependsOnPresenceOf="28696224" />
<line id="2597826922" dependsOnPresenceOf="200114712343">
<methodElement fixedWidth="17" precededBySpace="false" id="418710522">
<line id="24867948" dependsOnPresenceOf="10565536">
<element text=" Cert. Number:" id="23917950" dependsOnPresenceOf="10565536" />
<line id="24867948" dependsOnPresenceOf="10565536">
<element text=" Cert. Number:" id="23917950" dependsOnPresenceOf="10565536" />
My Program is below which i have written to extract Integer value only :
public class DuplicateIDPicker {
protected static final Logger logger = Logger
.getLogger(com.aspire.pos.DuplicateIDPicker.class);
public static String finalContent = "";
public static void main(String[] args) throws FileNotFoundException {
String content = "";
/* Set location of the file as format below */
String path = "D://TASK/DuplicateFinder/OriginalFile/";
/* Set file name to be evaluate with extension */
String fileName = "SSLItems.bpt";
File f = new File(path.concat(fileName));
try {
content = readFile(f);
String extractedInteger = content.replaceAll("\\D+", " ");
String[] arrayOfID = findAllIDInArray(extractedInteger);
System.out.println("***********************");
HashSet<String> set = new HashSet<String>();
HashSet<String> newSet = new HashSet<String>();
System.out.println("Duplicate ID's found :");
for (String arrayElement : arrayOfID) {
if (!set.add(arrayElement)) {
// System.out.println("Duplicate Element is : "+arrayElement);
newSet.add(arrayElement);
}
}
System.out.println("-----------------------");
/* here are all Duplicate Id */
System.out.println(newSet);
} catch (IOException e) {
logger.error(e.getMessage());
}
}
#SuppressWarnings("resource")
public static String readFile(File f) throws IOException {
String data = "";
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
while ((data = br.readLine()) != null) {
// Print the content on the console
finalContent = finalContent + data;
}
return finalContent;
}
public static String[] findAllIDInArray(String str) {
String[] value = str.split(" ");
return value;
}
}
you can do content.replaceAll("dependsOnPresenceOf=\"\\d+\"", ""); to remove these unwanted strings
Here is a working solution that makes use of:
1) Java 7 read entire file in one line
2) Matcher ability to sequentially find occurences that match the expression
3) regex capturing group to get the desired numeric value
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class DuplicateIDPicker
{
public static void main(String[] args)
{
/* Set location of the file as format below */
String path = "C://Temp/";
/* Set file name to be evaluate with extension */
String fileName = "in.txt";
Set<String> all = new HashSet<>();
Set<String> duplicates = new HashSet<>();
String regex = "(id|ID)\\=\"" // attribute name + quoted equal and quotation
+ "(\\d+)" // id value marked as (capturing group)
+ "\""; // closing quotation
try {
String content = readFile(path + fileName);
Matcher m = Pattern.compile(regex).matcher(content);
while (m.find()) {
String idValue = m.group(2);
if (!all.add(idValue)) duplicates.add(idValue);
}
System.out.println(duplicates);
} catch (Exception e) {
e.printStackTrace();
}
}
public static String readFile(String fileFullPath) throws IOException
{
return new String(Files.readAllBytes(Paths.get(fileFullPath)));
}
}
This one is another solution to solve my problem.
public class DuplicateIDPicker {
protected static final Logger logger = Logger
.getLogger(com.aspire.pos.DuplicateIDPickerOld.class);
public static String finalContent = "";
public static void main(String[] args) throws FileNotFoundException,
IOException {
String content = "";
String[] arrayOFId = {};
String[] listOfID = {};
HashSet<String> set = new HashSet<String>();
HashSet<String> newSet = new HashSet<String>();
/* Set location of the file as format below */
String path = "D://TASK/DuplicateFinder/OriginalFile/";
/* Set file name to be evaluate with extension */
String fileName = "SSLPickupDeliveryOrderReceipt.txt";
File f = new File(path.concat(fileName));
content = readFile(f);
arrayOFId = findAllIDInString(content);
listOfID = extractIDOnly(arrayOFId);
System.out.println("***********************");
System.out.println("Duplicate ID's found :");
for (String arrayElement : listOfID) {
if (!set.add(arrayElement)) {
newSet.add(arrayElement);
}
}
System.out.println("-----------------------");
/* Duplicate Id stored in a Set : */
System.out.println(newSet);
}
/*
* This method is implemented to read file and
* return content in String format
*/
public static String readFile(File f) {
String data = "";
try {
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
while ((data = br.readLine()) != null) {
finalContent = finalContent + data;
}
br.close();
} catch (IOException e) {
logger.error(e.getMessage());
}
return finalContent;
}
/*
* This method is implemented to get Array string
* on the basis of '"'
*/
public static String[] extractIDOnly(String[] arr) {
ArrayList<String> listOfID = new ArrayList<String>();
for (int i = 0; i < arr.length; i++) {
String newString = arr[i];
String[] finalString = {};
for (int j = 0; j < newString.length();) {
finalString = newString.split("\"", 3);
for (int k = 1; k < finalString.length;) {
listOfID.add(finalString[1]);
break;
}
break;
}
}
return (String[]) listOfID.toArray(new String[listOfID.size()]);
}
/*
* This method is implemented to split the ID part only
*/
public static String[] findAllIDInString(String str) {
String[] value = str.split("id=");
return value;
}
}
Related
I am reading a file with a disease name and its remedies. Therefore, i want to save the name as key and remedies in a set as the value. How can i reach that? It seems there is some problems in my code.
public static HashMap<String,Set<String>> disease = new HashMap <> ();
public static void main(String[] args) {
Scanner fin = null;
try {
fin = new Scanner (new File ("diseases.txt"));
while (fin.hasNextLine()) {
HashSet <String> remedies = null;
String [] parts = fin.nextLine().split(",");
int i = 1;
while (fin.hasNext()) {
remedies.add(parts[i].trim());
i++;
}
disease.put(parts[0],remedies);
}
fin.close();
}catch(Exception e) {
System.out.println("Error: " + e.getMessage());
}
finally {
try {fin.close();} catch(Exception e) {}
}
Set <String> result = disease.get("thrombosis");
display(result);
public static <T> void display (Set<T> items) {
if (items == null)
return;
int LEN = 80;
String line = "[";
for (T item:items) {
line+= item.toString() + ",";
if (line.length()> LEN) {
line = "";
}
}
System.out.println(line + "]");
}
here is my code
cancer,pain,swelling,bleeding,weight loss
gout,pain,swelling
hepatitis A,discoloration,malaise,tiredness
thrombosis,high heart rate
diabetes,frequent urination
and here is what the txt contains.
In your code , you haven't initialized the remedies HashSet(thats why it is throwing NullPointerException at line number 14).
and second issue is : i is getting incremented by 1 and you are not checking with size of your pats array ( i > parts.length) .
I edited your code :
Scanner fin = null;
try {
fin = new Scanner(new File("diseases.txt"));
while (fin.hasNextLine()) {
HashSet<String> remedies = new HashSet<String>();
String[] parts = fin.nextLine().split(",");
int i = 1;
while (fin.hasNext()&&parts.length>i) {
remedies.add(parts[i].trim());
i++;
}
disease.put(parts[0], remedies);
}
import java.util.HashMap;
import java.util.HashSet;
import java.util.Scanner;
import java.io.File;
import java.util.Set;
public class Solution {
public static HashMap<String, Set<String>> disease = new HashMap<>();
public static void main(String[] args) {
Scanner fin = null;
try {
fin = new Scanner (new File("diseases.txt"));
while (fin.hasNextLine()) {
HashSet <String> remedies = new HashSet<>();
String [] parts = fin.nextLine().split(",");
for (int i=1; i < parts.length; i++) {
remedies.add(parts[i].trim());
}
disease.put(parts[0],remedies);
}
fin.close();
}catch(Exception e) {
System.out.println("Error: " + e.getMessage());
}
finally {
try {fin.close();} catch(Exception e) {}
}
Set <String> result = disease.get("thrombosis");
display(result);
}
public static <T> void display(Set<T> items) {
if (items == null)
return;
int LEN = 80;
String line = "[";
for (T item : items) {
line += item.toString() + ",";
if (line.length() > LEN) {
line = "";
}
}
System.out.println(line + "]");
}
}
Here is full working code. As suggested by #Pratik that you forget to initialize HashSet that's why NullPointerException error was coming.
You have a few issues here:
no need for inner while loop (while (fin.hasNext()) {) - instead use `for(int i=1; i
HashSet <String> remedies = null; - this means the set is not initialized and we cannot put items in it - nede to change to: HashSet<String> remedies = new HashSet<>();
It is better practice to close() the file in the finally part
The 'display' method will delete the line (if it is longer than 80 characters) before printing it.
it is better to use StringBuilder when appending strings
So the corrected code would be:
import java.io.File;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class TestSOCode {
public static HashMap<String,Set<String>> disease = new HashMap<>();
private static int LINE_LENGTH = 80;
public static void main(String[] args) {
Scanner fin = null;
try {
fin = new Scanner(new File("diseases.txt"));
while (fin.hasNextLine()) {
HashSet<String> remedies = new HashSet<>();
String[] parts = fin.nextLine().split(",");
disease.put(parts[0], remedies);
for (int i = 1; i < parts.length; i++) {
remedies.add(parts[i].trim());
}
}
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
} finally {
try {
fin.close();
} catch (Exception e) {
System.out.println("Error when closing file: " + e.getMessage());
}
}
Set<String> result = disease.get("thrombosis");
display(result);
}
public static <T> void display (Set<T> items) {
if (items == null)
return;
StringBuilder line = new StringBuilder("[");
int currentLength = 1; // start from 1 because of the '[' char
for (T item:items) {
String itemStr = item.toString();
line.append(itemStr).append(",");
currentLength += itemStr.length() + 1; // itemStr length plus the ',' char
if (currentLength >= LINE_LENGTH) {
line.append("\n");
currentLength = 0;
}
}
// replace last ',' with ']'
line.replace(line.length() - 1, line.length(), "]");
System.out.println(line.toString());
}
}
I'm creating a program that basically has information about elements (From the periodic table) such as the atomic mass, number and symbol. I want to store all the information about them in a text file, but am unsure of how to code it to call upon the information separately (And not just read the text file line by line).
This is the code I'm using for each element so far:
private Element(int atomicNumber, double atomicMass, String atomicSymbol, String atomicName) {
this.atomicNumber = atomicNumber;
this.atomicMass = atomicMass;
this.atomicSymbol = atomicSymbol;
this.atomicName = atomicName;
}
In the same file, I was creating an element like this:
Element H = new Element(1, 1.008, "H", "Hydrogen");
How could I, instead of having all 118 elements in the same file as the code, put them in a text file and read them from there?
I'm using methods such as getAtomicNumber() and getAtomicMass(), etc to call upon the information.
Thanks.
You have multiple choices, since you can add any structure in a text file. My recomendation would be XML or CSV format.
A CSV is more easy to manage/edit, but the XML is more structured and read friendly. I'm go with a simple CSV.
Put in your file a line for each Element (that will be readed into your Element class), and each Element attribute (number, mass, symbol and name) separated by comma in a specific order, something like this:
1,1.008,H,Hydrogen
2,5.021,C,Carbon
etc..
Then, your code should read the file, line by line, create instances of your element class and maybe save it in a list. Something like this:
Your Element Class
public class Element {
private int atomicNumber;
private double atomicMass;
private String atomicSymbol;
private String atomicName;
public Element(int atomicNumber, double atomicMass, String atomicSymbol, String atomicName) {
this.atomicNumber = atomicNumber;
this.atomicMass = atomicMass;
this.atomicSymbol = atomicSymbol;
this.atomicName = atomicName;
}
public double getAtomicMass() {
return atomicMass;
}
public void setAtomicMass(double atomicMass) {
this.atomicMass = atomicMass;
}
public String getAtomicSymbol() {
return atomicSymbol;
}
public void setAtomicSymbol(String atomicSymbol) {
this.atomicSymbol = atomicSymbol;
}
public String getAtomicName() {
return atomicName;
}
public void setAtomicName(String atomicName) {
this.atomicName = atomicName;
}
public int getAtomicNumber() {
return atomicNumber;
}
public void setAtomicNumber(int atomicNumber) {
this.atomicNumber = atomicNumber;
}
#Override
public String toString() {
return "atomicMass: " + atomicMass
+ " | atomicSymbol: " + atomicSymbol
+ " | atomicName: " + atomicName
+ " | atomicNumber: " + atomicNumber;
}
}
Elements file reader
public class ElementsFileReader {
public static List<Element> read(String filePath) throws IOException {
FileReader fileReader = new FileReader(new File(filePath));
BufferedReader br = new BufferedReader(fileReader);
List<Element> elements = new ArrayList<>();
String line = null;
while ((line = br.readLine()) != null) {
String[] lineParts = line.split(",");
int atomicNumber = Integer.parseInt(lineParts[0]);
double atomicMass = Double.parseDouble(lineParts[1]);
String atomicSymbol = lineParts[2];
String atomicName = lineParts[3];
elements.add(new Element(atomicNumber, atomicMass, atomicSymbol, atomicName));
}
return elements;
}
}
Your main application using ElementsFileReader and Element
public static void main(String[] args){
String filePath = "the path to your text file";
List<Element> elements;
try {
elements = ElementsFileReader.read(filePath);
} catch(IOException e){
System.err.println("Something gone wrong reading elements file...");
e.printStackTrace();
return;
}
for(Element element : elements){
System.out.println(element);
// do your stuff
}
}
Careful with the parseInt and parseDouble method, I'm assuming the right format in your text file.
Hope this can help you.
Write all the elements to a file in the same format (1,1.008,H,Hydrogen), read line by line and create a Pojo object for each line and write it to Map.
public Map readFile(String filePath) {
Map<Integer, Element> elementsMap = new HashMap<>();
Scanner s;
try {
s = new Scanner(new File(filePath));
while (s.hasNextLine()){
String[] properties = s.nextLine().split(",");
Element element = new Element();
element.setAtomicNumber(Integer.parseInt(properties[0]));
element.setAtomicMass(Double.parseDouble(properties[1]));
element.setAtomicSymbol(properties[2]);
element.setAtomicName(properties[3]);
elementsMap.put(element.getAtomicNumber(), element);
}
s.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return elementsMap;
}
You can have the Map key as any other unique element property according to your convenience.
I have created a web scraper which scrapes data from a website and store it in CSV file. But, the problem is there is a column on the website which have currency formatted values which have amounts like 7,100 or 85,210. When my code executed and scrapes the data, these values separated into two columns like 7 in one column and 100 in other column. Kindly, check the attached screenshots.
Code is as follows.
public class ComMarket_summary {
boolean writeCSVToConsole = true;
boolean writeCSVToFile = true;
boolean sortTheList = true;
boolean writeToConsole;
boolean writeToFile;
public static Document doc = null;
public static Elements tbodyElements = null;
public static Elements elements = null;
public static Elements tdElements = null;
public static Elements trElement2 = null;
public static String Dcomma = ",";
public static String line = "";
public static ArrayList<Elements> sampleList = new ArrayList<Elements>();
public static void createConnection() throws IOException {
System.setProperty("http.proxyHost", "191.1.1.202");
System.setProperty("http.proxyPort", "8080");
String tempUrl = "http://www.psx.com.pk/phps/mktSummary.php";
doc = Jsoup.parse(new URL(tempUrl), 1000);
System.out.println("Successfully Connected");
}
public static void parsingHTML() throws Exception {
for (Element table : doc.select("table.marketData")) {
Elements tables = doc.select("table.marketData");
table = tables.get(2);
File fold = new File("C:\\market_smry.csv");
fold.delete();
File fnew = new File("C:\\market_smry.csv");
for (Element trElement : table.getElementsByTag("tr")) {
trElement2 = trElement.getElementsByTag("tr");
tdElements = trElement.getElementsByTag("td");
FileWriter sb = new FileWriter(fnew, true);
//if (table.hasClass("marketData")) { //&&(tdElements.hasClass("tableHead")&&tdElements.hasClass("tableSubHead"))
for (Iterator<Element> it = tdElements.iterator(); it.hasNext();) {
if (it.hasNext()) {
sb.append(" , ");
sb.append(" \r\n ");
}
for (Iterator<Element> it2 = tdElements.iterator(); it.hasNext();) {
Element tdElement2 = it.next();
final String content = tdElement2.text();
if (it2.hasNext()) {
sb.append(formatData(content));
sb.append(" , ");
}
}
System.out.println(sb.toString());
sb.flush();
sb.close();
}
System.out.println(sampleList.add(tdElements));
}
}
}
private static final SimpleDateFormat FORMATTER_MMM_d_yyyy = new SimpleDateFormat("MMM d, yyyy", Locale.US);
private static final SimpleDateFormat FORMATTER_dd_MMM_yyyy = new SimpleDateFormat("d-MMM-yy", Locale.US);
public static String formatData(String text) {
String tmp = null;
try {
Date d = FORMATTER_MMM_d_yyyy.parse(text);
tmp = FORMATTER_dd_MMM_yyyy.format(d);
} catch (ParseException pe) {
tmp = text;
}
return tmp;
}
public static void main(String[] args) throws IOException, Exception {
createConnection();
parsingHTML();
}
Note: I am using windows 8, java version 1.8, jsoup 1.8
Before saving the value get rid of the comma by using String.replace
value = value.replace (",", "");
String.replace will get rid of your comma. While there are several other similar functions (replaceAll, replaceFirst), replace will be slightly faster and is typically the best choice for a single character.
See: https://docs.oracle.com/javase/6/docs/api/java/lang/String.html
And also: Difference between String replace() and replaceAll()
I am trying to do a file I/O in eclipse. Here is the code:
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.StringTokenizer;
public class TextDB {
public static final String SEPARATOR = "|";
// an example of reading
public static ArrayList readProfessors(String filename) throws IOException {
// read String from text file
ArrayList stringArray = (ArrayList) read(filename);
ArrayList alr = new ArrayList();// to store Professors data
for (int i = 0; i < stringArray.size(); i++) {
String st = (String) stringArray.get(i);
// get individual 'fields' of the string separated by SEPARATOR
StringTokenizer star = new StringTokenizer(st, SEPARATOR); // pass in the string to the string tokenizer using delimiter ","
String name = star.nextToken().trim(); // first token
String email = star.nextToken().trim(); // second token
int contact = Integer.parseInt(star.nextToken().trim()); // third token
// create Professor object from file data
Professor prof = new Professor(name, email, contact);
// add to Professors list
alr.add(prof);
}
return alr;
}
// an example of saving
public static void saveProfessors(String filename, List al) throws IOException {
List alw = new ArrayList();// to store Professors data
for (int i = 0; i < al.size(); i++) {
Professor prof = (Professor) al.get(i);
StringBuilder st = new StringBuilder();
st.append(prof.getName().trim());
st.append(SEPARATOR);
st.append(prof.getEmail().trim());
st.append(SEPARATOR);
st.append(prof.getContact());
alw.add(st.toString());
}
write(filename, alw);
}
/**
* Write fixed content to the given file.
*/
public static void write(String fileName, List data) throws IOException {
PrintWriter out = new PrintWriter(new FileWriter(fileName));
try {
for (int i = 0; i < data.size(); i++) {
out.println((String) data.get(i));
}
} finally {
out.close();
}
}
/**
* Read the contents of the given file.
*/
public static List read(String fileName) throws IOException {
List data = new ArrayList();
Scanner scanner = new Scanner(new FileInputStream(fileName));
try {
while (scanner.hasNextLine()) {
data.add(scanner.nextLine());
}
} finally {
scanner.close();
}
return data;
}
public static void main(String[] aArgs) {
TextDB txtDB = new TextDB();
String filename = "professor.txt";
try {
// read file containing Professor records.
ArrayList al = TextDB.readProfessors(filename);
for (int i = 0; i < al.size(); i++) {
Professor prof = (Professor) al.get(i);
System.out.println("Name " + prof.getName());
System.out.println("Contact " + prof.getContact());
}
Professor p1 = new Professor("Joseph", "jos#ntu.edu.sg", 67909999);
// al is an array list containing Professor objs
al.add(p1);
// write Professor record/s to file.
TextDB.saveProfessors(filename, al);
} catch (IOException e) {
System.out.println("IOException > " + e.getMessage());
}
}
}
And my Professor class:
import java.io.Serializable;
public class Professor implements Serializable {
private String name;
private String email;
private int contact;
public Professor(String n, String e, int c) {
name = n;
email = e;
contact = c;
}
public String getName() {
return name;
}
public int getContact() {
return contact;
}
public String getEmail() {
return email;
}
public boolean equals(Object o) {
if (o instanceof Professor) {
Professor p = (Professor) o;
return (getName().equals(p.getName()));
}
return false;
}
}
However, when I run it, the compiler told the the specified file "professor.txt" is not found. I thought the compiler will create the text file automatically based on these code?
Thanks in advance.
Before attempting to read the file in your application, create it if it doesn't exist, either directly :
String filename = "professor.txt" ;
File file = new File(fileName);
if(!file.exists()){
file.createNewFile();
}
Or by calling your write method.
String filename = "professor.txt" ;
File file = new File(fileName);
if(!file.exists()){
TextDB.saveProfessors(filename, new ArrayList());
}
The PrintWriter will create the file for you, even though nothing is written to it (like with this empty list).
In your main you are firstly reading the file and then write it: if the file doesn't exist it will throw you the exception. Probably, the first time you ran it, the file was present (maybe you have write the code to write the file first and then you have launch it).
so, two solutions...
First: change the order of your main.
public static void main(String[] aArgs) {
TextDB txtDB = new TextDB();
String filename = "professor.txt";
try {
Professor p1 = new Professor("Joseph", "jos#ntu.edu.sg", 67909999);
// al is an array list containing Professor objs
al.add(p1);
// write Professor record/s to file.
TextDB.saveProfessors(filename, al);
// read file containing Professor records.
ArrayList al = TextDB.readProfessors(filename);
for (int i = 0; i < al.size(); i++) {
Professor prof = (Professor) al.get(i);
System.out.println("Name " + prof.getName());
System.out.println("Contact " + prof.getContact());
}
} catch (IOException e) {
System.out.println("IOException > " + e.getMessage());
}
}
Second: check if the file exist or not and then skip the read of it if it doesn't
public static void main(String[] aArgs) {
TextDB txtDB = new TextDB();
String filename = "professor.txt";
try {
//check if the file exist
File oFile = new File(filename);
if(oFile.exist()) {
// read file containing Professor records.
ArrayList al = TextDB.readProfessors(filename);
for (int i = 0; i < al.size(); i++) {
Professor prof = (Professor) al.get(i);
System.out.println("Name " + prof.getName());
System.out.println("Contact " + prof.getContact());
}
}
Professor p1 = new Professor("Joseph", "jos#ntu.edu.sg", 67909999);
// al is an array list containing Professor objs
al.add(p1);
// write Professor record/s to file.
TextDB.saveProfessors(filename, al);
} catch (IOException e) {
System.out.println("IOException > " + e.getMessage());
}
}
UPDATE after comment:
public static void main(String[] aArgs) {
TextDB txtDB = new TextDB();
String filename = "professor.txt";
try {
//check if the file exist
File oFile = new File(filename);
if(!oFile.exist()) {
oFile.mkdirs(); //optional
oFile.createNewFile();
}
// read file containing Professor records.
ArrayList al = TextDB.readProfessors(filename);
for (int i = 0; i < al.size(); i++) {
Professor prof = (Professor) al.get(i);
System.out.println("Name " + prof.getName());
System.out.println("Contact " + prof.getContact());
}
Professor p1 = new Professor("Joseph", "jos#ntu.edu.sg", 67909999);
// al is an array list containing Professor objs
al.add(p1);
// write Professor record/s to file.
TextDB.saveProfessors(filename, al);
} catch (IOException e) {
System.out.println("IOException > " + e.getMessage());
}
}
I am writing a program for a user to add a string to an ArrayList then display it.
It doesn't work and it seems there is a problem with compareTo().
Here is my code:
public class database {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static String country[] = new String[100];
static String capital[] = new String[100];
static double population[] = new double[100];
static List<String> countriesList = Arrays.asList(country);
public static void main(String args[]) throws IOException {
country[0] = "Barbados";
country[1] = "France";
country[2] = "Nigeria";
country[3] = "USA";
country[4] = "Japan";
capital[0] = "Bridgetown";
capital[1] = "Paris";
capital[2] = "Abuja";
capital[3] = "Washington";
capital[4] = "Tokyo";
population[0] = 65.3;
population[1] = 315.8;
population[2] = 170.1;
population[3] = 2840;
population[4] = 126.7;
public static void searchCountry() throws IOException {
Scanner in = new Scanner(System.in);
String output;
int size, i;
System.out.println("Search Country:");
output = br.readLine();
boolean found = false;
for (i = 0; i < country.length; i++)
if (output.compareTo(country[i]) == 0) {
found = true;
break;
}
if (found)
System.out.println(output + " is found at index " + i);
else
System.out.println(output + "Country not found, choose Add country to add it");
public static void listCountry() throws IOException {
for (String c : countriesList) {
if (!=null)
System.out.println(c);
}
}
}
There is also a problem with the null at the end of my code.
While writing code, you should better start from the beginning. i.e.
First, write class name and make sure it there is no problem with brackets
public class MyClass{
}
Then, write main method in it.
public class MyClass{
public static void main(String[] args){
}
}
Then, write your methods, and test it in main method.
public class MyClass{
public void mymethod(){
//do something
System.out.println("say something");
}
public static void main(String[] args){
MyClass mc = new MyClass();
mc.mymethod();
}
}
If you try to write everything in one shotm it wont work and if you are not expert it would be hard for you to solve problem.
You can't write a method in a method. Close the brackets of main() before you open the brackets of searchCountry()
You don't check anything against being null. Maybe you mean if(c != null)
Just write it this way and you should be fine:
public class database {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static String country[] = new String[100];
static String capital[] = new String[100];
static double population[] = new double[100];
static List<String> countriesList = Arrays.asList(country);
public static void main(String args[]) {
country[0] = "Barbados";
country[1] = "France";
country[2] = "Nigeria";
country[3] = "USA";
country[4] = "Japan";
capital[0] = "Bridgetown";
capital[1] = "Paris";
capital[2] = "Abuja";
capital[3] = "Washington";
capital[4] = "Tokyo";
population[0] = 65.3;
population[1] = 315.8;
population[2] = 170.1;
population[3] = 2840;
population[4] = 126.7;
searchCountry();
listCountry();
}
public void searchCountry() throws IOException {
Scanner in = new Scanner(System.in);
String output;
int size, i;
System.out.println("Search Country:");
output = br.readLine();
boolean found = false;
for (i = 0; i < country.length; i++)
if (output.compareTo(country[i]) == 0) {
found = true;
break;
}
if (found)
System.out.println(output + " is found at index " + i);
else
System.out.println(output + "Country not found, choose Add country to add it");
}
public void listCountry() {
for (String c : countriesList) {
if (c!=null)
System.out.println(c);
}
}
}
You forgot the c in c != null. You cannot define methods inside of methods in java. Also, use the equals method when testing forString equality, ie if (output.equals(country [i])).