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])).
Related
I have this code, it gets the average grade, but I need to export the arraylist Hell to a CSV file. How do I do this?
import java.util.*;
import java.io.*;
import java.io.PrintWriter;
import java.text.*;
public class hello3 {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.printf("Please enter the name of the input file: ");
String input_name = in.next();
System.out.printf("Please enter the name of the output CSV file: ");
String csv_name = in.next();
System.out.printf("Please enter the name of the output pretty-print file: ");
String pretty_name = in.next();
processGrades(input_name, csv_name, pretty_name);
System.out.printf("\nExiting...\n");
}
public static void processGrades (String input_name, String csv_name, String pretty_name)
{
PrintWriter csv = null;
PrintWriter pretty = null;
String[][] data = readSpreadsheet(input_name);
boolean resultb = sanityCheck(data);
int length = data.length;
ArrayList<String> test_avg = new ArrayList<String>();
ArrayList<String> HW_avg = new ArrayList<String>();
ArrayList<String> NAME = new ArrayList<String>();
ArrayList<String> ColN = new ArrayList<String>();
ArrayList<String> Hell = new ArrayList<String>();
for(int row = 1; row<length; row++)
{
String name = data[row][0];
String name2 = data[row][1];
String Name = name+" "+name2;
int test1 = Integer.parseInt(data[row][2]);
int test2 = Integer.parseInt(data[row][3]);
int test3 = Integer.parseInt(data[row][4]);
int Test = (test1+test2+test3)/3;
String Testav = Integer.toString(Test);
int hw1 = Integer.parseInt(data[row][5]);
int hw2 = Integer.parseInt(data[row][6]);
int hw3 = Integer.parseInt(data[row][7]);
int hw4 = Integer.parseInt(data[row][8]);
int hw5 = Integer.parseInt(data[row][9]);
int hw6 = Integer.parseInt(data[row][10]);
int hw7 = Integer.parseInt(data[row][11]);
int HW = (hw1+hw2+hw3+hw4+hw5+hw6+hw7)/7;
int[] trying = {Test, HW};
int low = find_min(trying);
String grade = null;
if(low>=90)
{
grade ="A";
}
if(low < 90&& low>= 80)
{
grade = "B";
}
if(low <80&&low>=70)
{
grade ="C";
}
if(low<70&&low>=60)
{
grade="D";
}
if(low<60)
{
grade = "F";
}
String Lows = Integer.toString(low);
String HWav = Integer.toString(HW);
test_avg.add(Testav);
HW_avg.add(HWav);
NAME.add(Name);
Hell.add(Name);
Hell.add(Testav);
Hell.add(HWav);
Hell.add(Lows);
Hell.add(grade);
System.out.println(Hell);
System.out.printf("\n");
}
}
public static int find_min(int[] values)
{
int result = values[0];
for(int i = 0; i<values.length; i++)
{
if(values[i]<result)
{
result = values[i];
}
}
return result;
}
public static boolean sanityCheck(String[][] data)
{
if (data == null)
{
System.out.printf("Sanity check: nul data\n");
return false;
}
if(data.length<3)
{
System.out.printf("Sanity check: %d rows\n",data.length);
return false;
}
int cols= data[0].length;
for(int row = 0; row<data.length; row++)
{
int current_cols = data[row].length;
if(current_cols!=cols)
{
System.out.printf("Sanity Check: %d columns at rows%d\n", current_cols, row);
return false;
}
}
return true;
}
public static String[][] readSpreadsheet(String filename)
{
ArrayList<String> lines = readFile(filename);
if (lines == null)
{
return null;
}
int rows = lines.size();
String[][] result = new String[rows][];
for (int i = 0; i < rows; i++)
{
String line = lines.get(i);
String[] values = line.split(",");
result[i] = values;
}
return result;
}
public static ArrayList<String> readFile(String filename)
{
File temp = new File(filename);
Scanner input_file;
try
{
input_file = new Scanner(temp);
} catch (Exception e)
{
System.out.printf("Failed to open file %s\n",
filename);
return null;
}
ArrayList<String> result = new ArrayList<String>();
while (input_file.hasNextLine())
{
String line = input_file.nextLine();
result.add(line);
}
input_file.close();
return result;
}
}
Any help would be appreciated. thank you.
Broadly, you need to open a file with the name you require, and a writer in a loop - like this:
File csvFile = new File(csvName);
try (PrintWriter csvWriter = new PrintWriter(new FileWriter(csvFile));){
for(String item : list){
csvWriter.println(item);
}
} catch (IOException e) {
//Handle exception
e.printStackTrace();
}
Obviously you will have to print some commas as required
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;
}
}
I have a list of strings. First element is:
2 helloworld 10173.991234
I've written the code below:
ArrayList<Integer> idList = new ArrayList<Integer>();
for (String s:list){
String subs = s.substring(0,8);
subs = subs.trim();
idList.add(Integer.valueOf(subs));
}
This code shoud parse first id field and add it to arraylist.
But it fails on line idList.add(Integer.valueOf(subs));
Whats the problem? Any help?
Upd:
public class Solution {
public static void main(String[] args) throws Exception {
if (args[0].equals("-c")) {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String fileString = reader.readLine();
reader.close();
Scanner scanner = new Scanner(new File(fileString));
ArrayList<String> list = new ArrayList<String>();
while (scanner.hasNextLine()) {
list.add(scanner.nextLine());
}
String ne = list.get(list.size()-1);
scanner.close();
int maxId;
if (ne.length()>1) {
ArrayList<Integer> idList = new ArrayList<Integer>();
for (String s:list){
String subs = s.substring(0,8);
subs = subs.trim();
idList.add(Integer.parseInt(subs));
}
maxId = idList.get(0);
for (int i:idList){
if (maxId<i){
maxId=i;
}
}
maxId++;
}
else {
maxId = 0;
}
String maxIdString = ""+maxId;
while (maxIdString.length()<8){
maxIdString+=" ";
}
if (maxIdString.length()>8){
maxIdString = maxIdString.substring(0,8);
}
String productName = "";
for (int i = 1; i < args.length-2; i++) {
productName+=args[i]+" ";
}
productName = productName.trim();
while (productName.length()<30){
productName+=" ";
}
if (productName.length()>30)
productName=productName.substring(0,30);
String price = args[args.length-2];
while (price.length()<8){
price+=" ";
}
if (price.length()>8)
price=price.substring(0,8);
String quantity = args[args.length-1];
while (quantity.length()<4){
quantity+=" ";
}
if (quantity.length()>4)
quantity=quantity.substring(0,4);
String outString = maxIdString+productName+price+quantity;
FileOutputStream outputStream = new FileOutputStream(fileString,true);
if (ne.length()>1)
outputStream.write("\r\n".getBytes());
outputStream.write(outString.getBytes());
outputStream.close();
}
}
}
It's the content of the file
2 helloworld 10173.991234
124 helloworld 10173.991234
125 helloworld 10173.991234
Program arguments, for example:
-c helloworld 10173.99 1234
I found what the problem was :) It was in UTF-8 coding. I understood it after starting to use Notepad++ application.
I'm doing a Phone Directory project and we have to read from a directory file telnos.txt
I'm using a Scanner to load the data from the file telnos.txt, using a loadData method from a previous question I asked here on StackOverflow.
I noticed attempts to find a user always returned Not Found, so I added a few System.out.printlns in the methods to help me see what was going on. It looks like the scanner isn't reading anything from the file. Weirdly, it is printing the name of the file as what should be the first line read, which makes me think I've missed something very very simple here.
Console
run:
telnos.txt
null
loadData tested successfully
Please enter a name to look up: John
-1
Not found
BUILD SUCCESSFUL (total time: 6 seconds)
ArrayPhoneDirectory.java
import java.util.*;
import java.io.*;
public class ArrayPhoneDirectory implements PhoneDirectory {
private static final int INIT_CAPACITY = 100;
private int capacity = INIT_CAPACITY;
// holds telno of directory entries
private int size = 0;
// Array to contain directory entries
private DirectoryEntry[] theDirectory = new DirectoryEntry[capacity];
// Holds name of data file
private final String sourceName = "telnos.txt";
File telnos = new File(sourceName);
// Flag to indicate whether directory was modified since it was last loaded or saved
private boolean modified = false;
// add method stubs as specified in interface to compile
public void loadData(String sourceName) {
Scanner read = new Scanner("telnos.txt").useDelimiter("\\Z");
int i = 1;
String name = null;
String telno = null;
while (read.hasNextLine()) {
if (i % 2 != 0)
name = read.nextLine();
else
telno = read.nextLine();
add(name, telno);
i++;
}
}
public String lookUpEntry(String name) {
int i = find(name);
String a = null;
if (i >= 0) {
a = name + (" is at position " + i + " in the directory");
} else {
a = ("Not found");
}
return a;
}
public String addChangeEntry(String name, String telno) {
for (DirectoryEntry i : theDirectory) {
if (i.getName().equals(name)) {
i.setNumber(telno);
} else {
add(name, telno);
}
}
return null;
}
public String removeEntry(String name) {
for (DirectoryEntry i : theDirectory) {
if (i.getName().equals(name)) {
i.setName(null);
i.setNumber(null);
}
}
return null;
}
public void save() {
PrintWriter writer = null;
// writer = new PrintWriter(FileWriter(sourceName));
}
public String format() {
String a;
a = null;
for (DirectoryEntry i : theDirectory) {
String b;
b = i.getName() + "/n";
String c;
c = i.getNumber() + "/n";
a = a + b + c;
}
return a;
}
// add private methods
// Adds a new entry with the given name and telno to the array of
// directory entries
private void add(String name, String telno) {
System.out.println(name);
System.out.println(telno);
theDirectory[size] = new DirectoryEntry(name, telno);
size = size + 1;
}
// Searches the array of directory entries for a specific name
private int find(String name) {
int result = -1;
for (int count = 0; count < size; count++) {
if (theDirectory[count].getName().equals(name)) {
result = count;
}
System.out.println(result);
}
return result;
}
// Creates a new array of directory entries with twice the capacity
// of the previous one
private void reallocate() {
capacity = capacity * 2;
DirectoryEntry[] newDirectory = new DirectoryEntry[capacity];
System.arraycopy(theDirectory, 0, newDirectory,
0, theDirectory.length);
theDirectory = newDirectory;
}
}
ArrayPhoneDirectoryTester.java
import java.util.Scanner;
public class ArrayPhoneDirectoryTester {
public static void main(String[] args) {
//create a new ArrayPhoneDirectory
PhoneDirectory newTest = new ArrayPhoneDirectory();
newTest.loadData("telnos.txt");
System.out.println("loadData tested successfully");
System.out.print("Please enter a name to look up: ");
Scanner in = new Scanner(System.in);
String name = in.next();
String entryNo = newTest.lookUpEntry(name);
System.out.println(entryNo);
}
}
telnos.txt
John
123
Bill
23
Hello
23455
Frank
12345
Dkddd
31231
In your code:
Scanner read = new Scanner("telnos.txt");
Is not going to load file 'telnos.txt'. It is instead going to create a Scanner object that scans the String "telnos.txt".
To make the Scanner understand that it has to scan a file you have to either:
Scanner read = new Scanner(new File("telnos.txt"));
or create a File object and pass its path to the Scanner constructor.
In case you are getting "File not found" errors you need to check the current working directory. You could run the following lines and see if you are indeed in the right directory in which the file is:
String workingDir = System.getProperty("user.dir");
System.out.println("Current working directory : " + workingDir);
You need to also catch the FileNotFoundException in the function as follows:
public void loadData(String sourceName) {
try {
Scanner read = new Scanner(new File("telnos.txt")).useDelimiter("\\Z");
int i = 1;
String name = null;
String telno = null;
while (read.hasNextLine()) {
if (i % 2 != 0)
name = read.nextLine();
else {
telno = read.nextLine();
add(name, telno);
}
i++;
}
}catch(FileNotFoundException ex) {
System.out.println("File not found:"+ex.getMessage);
}
}
You are actually parsing the filename not the actual file contents.
Instead of:
new Scanner("telnos.txt")
you need
new Scanner( new File( "telnos.txt" ) )
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
The following problem appears in my console after I execute the code and introduce the first cota l[i].cota = sc.nextLine();
Exception in thread "main" java.lang.NullPointerException
at exercicio6.introlivros(exercicio6.java:18)
at exercicio6.main(exercicio6.java:9)
can anyone tell me what's the issue?
Here is my code
public class exercicio6 {
public static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
livro l[] = new livro[200];
l = introlivros();
apagarbase(l);
}
public static livro[] introlivros() {
int i = 0;
livro l[] = new livro[200];
do {
System.out.print("Introduza a cota:");
l[i].cota = sc.nextLine();
if (l[i].cota.length() == 0)
break;
do {
System.out.print("Introduza o autor:");
l[i].autor = sc.nextLine();
} while (l[i].autor.length() < 40);
System.out.print("Introduza o titulo:");
l[i].titulo = sc.nextLine();
System.out.println("Introduza a data:");
System.out.println("Dia:");
l[i].data[0] = sc.nextInt();
System.out.println("Mes:");
l[i].data[1] = sc.nextInt();
System.out.println("Ano:");
l[i].data[2] = sc.nextInt();
i++;
} while (i < 200);
return l;
}
public static void remover(livro l[]) {
String cota1 = new String();
boolean verificar = false;
do {
cota1 = sc.nextLine();
if (cota1.length() != 0) {
for (int i = 0; i < 200; i++) {
if (cota1 == l[i].cota) {
l[i].cota = "";
break;
}
if (cota1 != l[i].cota) {
verificar = true;
}
}
}
if (cota1.length() == 0) {
System.out.println("Introduza a cota de novo!");
}
if (verificar == true) {
System.out.println("Esse livro não eciste!");
}
} while (cota1.length() == 0);
}
public static void apagarbase(livro l[]) {
livro p[] = new livro[200];
for (int i = 0; i < 200; i++) {
l[i].cota = null;
l[i].autor = null;
l[i].titulo = null;
l[i].data[0] = 0;
/*
* l[i].data[1]=null; l[i].data[2]=null; l[i].estado[0]=null;
*/
}
}
}
class livro {
String cota = new String();
String autor = new String();
String titulo = new String();
int data[] = new int[3];
char estado[] = new char[1]; // Requisitado R, Livre L, Condicionado C;
}
As stated above - objects are initialized to null
A quick way of populating an array is -
livro l[] = new livro[200];
Arrays.fill(l, new livro());
Here you are instantiating your array:
livro l[] = new livro[200];
However here you are attempting to access an element containing an object that does not exist yet:
l[i].cota = sc.nextLine();
You need to loop through and instantiate a new object at EVERY element. Either use a for loop or Array.fill.