Error Reading Files to Store their Data in an Array - java

The program that I am writing is in Java. I am attempting to make my program read the file "name.txt" and store the values of the text file in an array.
So far I am using a text file that will be read in my main program, a service class called People.java which will be used as a template for my program, and my main program called Names.java which will read the text file and store its values into an array.
name.txt:
John!Doe
Jane!Doe
Mike!Smith
John!Smith
George!Smith
People.java:
public class People
{
String firstname = " ";
String lastname = " ";
public People()
{
firstname = "First Name";
lastname = "Last Name";
}
public People(String firnam, String lasnam)
{
firstname = firnam;
lastname = lasnam;
}
public String toString()
{
String str = firstname+" "+lastname;
return str;
}
}
Names.java:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Names
{
public static void main(String[]args)
{
String a = " ";
String b = "empty";
String c = "empty";
int counter = 0;
People[]peoplearray=new People[5];
try
{
File names = new File("name.txt");
Scanner read = new Scanner(names);
while(read.hasNext())
{
a = read.next();
StringTokenizer token = new StringTokenizer("!", a);
while(token.hasMoreTokens())
{
b = token.nextToken();
c = token.nextToken();
People p = new People(b,c);
peoplearray[counter]=p;
++counter;
}
}
}
catch(IOException ioe1)
{
System.out.println("There was a problem reading the file.");
}
System.out.println(peoplearray[0]);
}
}
As I show in my program, I tried to print the value of peoplearray[0], but when I do this, my output reads: "null."
If the program were working corrrectly, the value of peoplearray[0] should be, "John Doe" as those are the appropriate values in "names.txt"
Is the value of peoplearray[0] supposed to be null?
If not, what can I do to fix this problem?
Thanks!

The order of your arguments is wrong:
StringTokenizer token = new StringTokenizer("!", a);
According to API constructor
public StringTokenizer(String str, String delim)
use
StringTokenizer token = new StringTokenizer(a,"!");

Related

Why does Player name get printed twice by my code?

Main Class
package main;
import static org.junit.Assert.*;
import java.util.ArrayList;
import org.junit.Test;
import lib.Die;
import lib.Name;
import lib.PairOfDice;
import lib.Player;
public class PlayerAppTest {
/* Please note - when we come to mark the solution to this unit test we will change the input
* data set for the players added to the list to ensure the solution works dynamically based
* upon any given data set and is not hardcoded in any way.
*/
#Test
public void testExecute() {
ArrayList<Player> players = new ArrayList<>();
players.add(new Player(new Name("Joe", "Bloggs"), new PairOfDice()));
players.add(new Player(new Name("Fred", "Jones"), new Die()));
players.add(new Player(new Name("Nila", "Singh"), new PairOfDice(new Die(5), new Die(5))));
String result = PlayerApp.execute(players, "Cassie Downturn");
String expectedResult = "cassie, DOWNTURN\nnila, SINGH\n";
assertEquals("The string returned should match the expected result (run 1)", expectedResult, result);
/* Test with a second set of input data */
ArrayList<Player> players2 = new ArrayList<>();
players2.add(new Player(new Name("David", "Blunt"), new PairOfDice()));
players2.add(new Player(new Name("Tim", "Jonas"), new Die(5)));
players2.add(new Player(new Name("Remi", "Patel"), new Die()));
String result2 = PlayerApp.execute(players2, "Cassie Downturn");
String expectedResult2 = "cassie, DOWNTURN\ntim, JONAS\nremi, PATEL\n";
assertEquals("The string returned should match the expected result (run 2)", expectedResult2, result2);
}
}
Hello, this is the JUnit test which I have to pass, below is the code that I have written in my main package;
JUnit Test Class
package main;
import java.util.ArrayList;
import lib.Player;
public class PlayerApp {
public static String execute(ArrayList<Player> players, String fullName) {
players.get(0).setFullPlayerName(fullName);
fullName = "";
for (int i = 0; i <players.size(); i ++) {
if (players.get(i).getName().getFirstName().toLowerCase().contains("a") || players.get(i).getName().getFamilyName().toUpperCase().contains("a")) {
fullName = players.get(i).getName().getFirstName().toLowerCase() + ", " + players.get(i).getName().getFamilyName().toUpperCase() + "\n";
}
System.out.println(fullName);
}
return fullName;
}
}
This is the code in my main package, I am trying to print out the names which contain a char "a" in the first name, the first name should be lowercase and the family name should be uppercase. It should print out
cassie, DOWNTURN
nila, SINGH which is the names with a new line between them, however, when i print it, it prints the following;
cassie, DOWNTURN
cassie, DOWNTURN
nila, SINGH
I am confused as to why cassie, DOWNTURN has been printed twice as i cannot find the error in my code, any help would be greatly appreciated, thank you.
You will print it even if the if doesn't match as it's outside the if-statement. Move it inside instead.
for (int i = 0; i <players.size(); i ++) {
if (players.get(i).getName().getFirstName().toLowerCase().contains("a") || players.get(i).getName().getFamilyName().toUpperCase().contains("a")) {
fullName = players.get(i).getName().getFirstName().toLowerCase() + ", " + players.get(i).getName().getFamilyName().toUpperCase() + "\n";
System.out.println(fullName);
}
}
Your print statement is not conditional and will always execute, move it inside the if. You're printing twice as your are not changing the value in fullName if the if condition does not evaluate as true. Further your family name comparison will always be false as you're comparing upper and lower case.
Your code can also be tided up and made easier to read:
for(Player player : players){
if(player.getName().getFirstName()).toLowerCase().contains("a")||player.getName().getFamilyName().toUpperCase.contains("A"))){
String fullName = players.get(i).getName().getFirstName().toLowerCase() + ", " + players.get(i).getName().getFamilyName().toUpperCase() + "\n";
System.out.println(fullname);
}
}

I have to determine from a string the starting and arrival cities

I have the following code which, by means of a keyboard input, gives me the start and arrival .. the start is determined according to the "da" proposition, while the arrival determines it according to the preposition "a" so I'm fighting now is: I want to get the start and the arrival even if I change the order of the propositions .. you know how I could proceed ..
this is the OUTPUT I get :
I want to go from ostuni to trapani
Partenza :ostuni
Arrivo :trapani
but if I wrote like this:
I want to go to ostuni by trapani
I would like to print the same start and finish correctly ..that is
Patenza :trapani
Arrivo :ostuni
Is this processing possible?
thanks a lot for the attention! Good day
package eubot.controller;
import eubot.intent.Intent;
public class EubotEngine {
public Intent getIntent(String stringInput) {
String str1 = "";
String str2 = "";
Intent dictionary = null;
for (String str3 : Intent.keyWord) {
if (stringInput.contains(str3)) {
//System.out.println("La stringa contiene : " + str3);
int indice1 = stringInput.indexOf(str3) + str3.length();
String splittable =
stringInput.substring(indice1,stringInput.length()).trim();
String splittable2[] = splittable.split(" ");
int index = 0;
for (String str : splittable2) {
str = splittable2[index +1];
str1 = str;
System.out.println("Partenza :" + str1);
break;
}
String splittable3[] = splittable.split(" ");
for(String str : splittable3) {
str = splittable3[index + 3];
str2 = str;
System.out.println("Arrivo :" + str2);
break;
}
index++;
dictionary = new Intent();
dictionary.setTesto(stringInput);
}
}
return dictionary;
}
}
package eustema.eubot.intent;
public class Intent {
public String testo;
public String getTesto() {
return testo;
}
public void setTesto(String testo) {
this.testo = testo;
}
public static String[] keyWord = { "devo andare", "voglio andare", "vorrei andare", "devo recarmi"};
public static String[] parameter = { "bari", "roma", "milano","pisa","firenze","napoli","como","torino" };
}
package eustema.eubot.main;
import java.util.Scanner;
import eustema.eubot.controller.*;
import eustema.eubot.intent.*;
public class Test {
public static void main(String[] args) {
System.out.println("<<-|-|-|-|-|-|-|-|-|<<<BENVENUTO IN EuBoT>>>|-|-|-|-|-|-|-|-|->>");
EubotEngine controller = new EubotEngine();
Scanner input = new Scanner(System.in);
String string;
while (true) {
string = input.nextLine();
Intent intent = controller.getIntent(string);
}
}
}
I know this will not be considered a good answer:)
This is non-trivial to solve by means of imperative programming. The reason is there are many forms in which one can express the same intent. Things like filler words, synonyms, inversions and in general things you did not think about could disrupt your algorithm.
Of course it depends on the level of accuracy you want to achieve. If you are happy that this will not work for all cases, you could always put in conditions like:
if (arr[index-1] == "from") setStart(arr[index]);
if (arr[index-1] == "to") setDestination(arr[index]);
Google, Amazon and Apple are battling to improve this sort of human-computer interaction, but they are using a more mathematical/statistical approach through machine learning.
So, if you're looking for state of the art:
Main search terms: context-free grammars.
Other key words: Markov models, Information extraction, vector space models, tf-idf

Read text file to arrayList and sort

This is a snippet of my txt file "Q.txt".
12.54778255173505 : ^FinishedLine
15.416218875438748 :
^FinishedLine
16.245508427720914 : ^FinishedLine
9.595696051997852 : &^FinishedLine
11.971100145959943 : ! '^FinishedLine
11.678678199807727 : " $^FinishedLine
14.905855346233682 : # %^FinishedLine
15.98343143372184 : $ "^FinishedLine
16.053542916378102 : % #^FinishedLine
I need to sort my text file "Q.txt" which contains a double and a string.
It has been separated using " : " and at the end of each phrase there is ("^FinishedLine"). When I run this, all it is coming up with is a "NumberFormatException: empty string" error.
public class Sorting {
public static void sort() throws IOException {
Scanner s = new Scanner(new File("Q.txt"));
ArrayList<Qpair> set = new ArrayList<>();
String line = "";
while (s.hasNext()) {
String[] parts = line.split(" : ");
set.add(new Qpair(Double.parseDouble(parts[0]), parts[1]));
s.useDelimiter("^FinishedLine");
}
s.close();
System.out.println(set);
}
private static class Qpair{
private double d;
private String s;
public Qpair(double d, String s){
this.d = d;
this.s = s;
}
public double getDouble(){
return d;
}
public String getString(){
return s;
}
}
private static class QpairCompare implements Comparator<Qpair>{
public int compare(Qpair x, Qpair y){
return (int) (x.getDouble() - y.getDouble());
}
}
}
As far as I can see: You are setting line to the empty string. You enter the while loop without changing line. You split this empty string at :. I admit I had to try it out to be sure: it yields an array of 1 element, an empty string. You try to parse this empty string from the array as a double.
And you tell us you get NumberFormatException: empty string. Sounds like agreement to me.
I hope you can figure out what code line is missing and where you should insert it?

Java append instances of a String to a String which separated by commas

So I have a string variable which is meant to hold names of cars separated by commas.
String cars = "";
What I want to do is append cars to this string. The way a new car would be added:
String newCar1 = "Mini";
String newCar2 = "LandRover";
appendToCars(newCar1);
appendToCars(newCar2);
Then currently I have this, which I primarily need help with.
public void appendToCars(String newCar)
{
cars = cars + "," + newCar;
}
So output should be:
Mini,LandRover
but it's:
[,]Mini
Been racking my brain about this for hours figuring out how to do it, but I just can't get the result I actually want.
Im also using a JUnit test for this which reads :
#Test
public void testAppendToCars() {
System.out.println("appendToCars");
String newCar1 = "Mini";
String newCar2 = "LandRover";
String expResult = newCar1 + "," + newCar2;
testDel.appendToCars(newCar1);
testDel.appendToCars(newCar2);
String result = testDel.getCars();
assertEquals("Delivery notes incorrectly stored", expResult, result);
I think you just have a variable scope issue. This example uses your code but takes the scope into consideration:
public class temp {
static String cars = "";
public static void appendToCars(String something)
{
if (cars.equals("")){
cars = something;
}
else {
cars= cars + "," + something;
}
}
public static void main(String[] args){
String newcar1 = "Mini";
String newcar2 = "LandRover";
appendToCars(newcar1);
appendToCars(newcar2);
System.out.println(cars);
}
}
This class will return the following:
Mini,LandRover

Use JDT to get full method name

I am new to eclipse plugin development and I am trying to convert a IMethod to a string representation of the full method name. I.E.
my.full.package.ClassName.methodName(int param, String string)
so far I have had to hand roll my own solution. Is there a better way?
private static String getMethodFullName(IMethod iMethod)
{
String packageString = "[Default Package]";
try {
IPackageDeclaration[] declarations = iMethod.getCompilationUnit().getPackageDeclarations();
if(declarations.length > 0)
{
packageString = declarations[0].getElementName();
}
} catch (JavaModelException e) {
}
String classString = iMethod.getCompilationUnit().getElementName();
classString = classString.replaceAll(".java", "");
String methodString = iMethod.getElementName() + "(";
for (String type : iMethod.getParameterTypes()) {
methodString += type + ",";
}
methodString += ")";
return packageString + "." + classString + "." + methodString;
}
You can get the Fully qualified name for the type using
method.getDeclaringType().getFullyQualifiedName();
This is probably easier than accessing the package from the compilation unit. The rest of you function looks correct.
One small point: you should use StringBuilder to build up the string instead of adding to a standard String. Strings are immutable so addition creates loads of unrecesary temparary objects.
private static String getMethodFullName(IMethod iMethod)
{
StringBuilder name = new StringBuilder();
name.append(iMethod.getDeclaringType().getFullyQualifiedName());
name.append(".");
name.append(iMethod.getElementName());
name.append("(");
String comma = "";
for (String type : iMethod.getParameterTypes()) {
name.append(comma);
comma = ", ";
name.append(type);
}
name.append(")");
return name.toString();
}
Thanks to iain and some more research I have come up with this solution. It seems like something like this should be built into the JDT....
import org.eclipse.jdt.core.Signature;
private static String getMethodFullName(IMethod iMethod)
{
StringBuilder name = new StringBuilder();
name.append(iMethod.getDeclaringType().getFullyQualifiedName());
name.append(".");
name.append(iMethod.getElementName());
name.append("(");
String comma = "";
String[] parameterTypes = iMethod.getParameterTypes();
try {
String[] parameterNames = iMethod.getParameterNames();
for (int i=0; i<iMethod.getParameterTypes().length; ++i) {
name.append(comma);
name.append(Signature.toString(parameterTypes[i]));
name.append(" ");
name.append(parameterNames[i]);
comma = ", ";
}
} catch (JavaModelException e) {
}
name.append(")");
return name.toString();
}
I am not sure it would take into account all cases (method within an internal class, an anonymous class, with generic parameters...)
When it comes to methods signatures, the classes to look into are:
org.eclipse.jdt.internal.corext.codemanipulation.AddUnimplementedMethodsOperation
org.eclipse.jdt.internal.corext.codemanipulation.StubUtility2
You need to get the jdt.core.dom.IMethodBinding, from which you can extract all what you need.
If you have a MethodInvocation, you can:
//MethodInvocation node
ITypeBinding type = node.getExpression().resolveTypeBinding();
IMethodBinding method=node.resolveMethodBinding();

Categories