Words Counter using Dictionary - java

For homework I have to implement a Words Counter using a Dictionary.I have an inner class named Couple
protected class Couple
{ public Coppia(String key, Integer value)
{ setKey(key);
setValue(value);
}
public String toString()
{ return String.format("%-15s", key) + " | " + value; }
public String getKey()
{ return key; }
public Integer getValue()
{ return value; }
public void setKey(String key)
{ this.key = key; }
public void setValue(Integer value)
{ this.value = value; }
//campi di esemplare
private String key;
private Integer value;
}
}
I created the class WordsCounter with put,find,remove methods
class WordsCounter
{ private Couple [] a;
private int inputSize;
public WordCounter()
{ a=new Couple [10];
inputSize=0;
}
public boolean isEmpty()
{return inputSize==0;}
public int size()
{return inputSize;}
public String toString()
{String s="";
for(int i=0;i<inputSize;i++)
{s=s+a[i].toString()+"\n";
}
return s;
}
public void put(Comparable key, Comparable value)
{if(inputSize==a.length) //resize
{ Coppia [] newA=new Coppia [2*inputSize];
for(int i=0;i<inputSize;i++)
{ newA[i]=a[i];
}
a=newA;
}
for(int i=0;i<inputSize;i++) // if the word is already in, i replace the old value with the new one
{ if(a[i].getKey().equals((String)key))
{ a[i].setValue((Integer)value);
return;
}
}
//otherwise i add the word in the array
a[inputSize++]=new Couple((String)key,(Integer)value);
mergeSort(a,inputSize);
}
public void remove(Comparable key)
{ int pos=binarySearch(a,0,inputSize-1,(String)key);
if(pos<0)
{ throw new MapItemNotFoundException();
}
else
{ a[pos]=a[inputSize-1];
inputSize--;
mergeSort(a,inputSize);
}
}
public int binarySearch(Couple [] a,int start,int end,String k)
{ if(start>end)
return -1;
int mid=(start+end)/2;
if(a[mid].equals(k))
{ return mid;}
else if(k.compareTo(a[mid].getKey())<0)
{ return binarySearch(a,start,mid-1,k);
}
else if( k.compareTo(a[mid].getKey())>0)
{ return binarySearch(a,mid+1,end,k);
}
else return -1;
}
public Comparable find(Comparable key)
{ int pos=binarySearch(a,0,inputSize-1,(String)key);
if(pos<0) // the word isn't inside the array ,so i throw an exception
{ throw new MapItemNotFoundException();
}
else
{ return a[pos].getValue();
}
}
public void mergeSort(Couple [] a,int input)
{ if(input<2)
return;
int mid=input/2;
Coppia [] first=new Coppia [mid];
Coppia [] second=new Coppia [input-mid];
for(int i=0;i<first.length;i++)
{ first[i]=a[i];
}
for(int i=0;i<second.length;i++)
{ second[i]=a[i+first.length];
}
mergeSort(first,mid);
mergeSort(second,input-mid);
merges(a,first,second);
}
public void merges(Couple [] a,Couple [] b,Couple [] c)
{ int i=0;
int k=0;
int j=0;
while(i<b.length&&j<c.length)
{ if(b[k].getKey().compareTo(c[j].getKey())<0)
{ a[i++]=b[k++];
}
else
{ a[i++]=c[j++];
}
}
while(i<b.length)
{ a[i++]=b[k++];
}
while(j<c.length)
{ a[i++]=c[j++];
}
}
The main class is
public class ContatoreParoleTester
{
public static void main(String[] args)
{
FileReader read=null;
try{ read=new FileReader(in.nextLine());
}
catch(IOException e)
{
}
Scanner c=new Scanner(read);
WordCounter parole=new WordCounter();
while(c.hasNextLine())
{ Scanner token=new Scanner(c.nextLine());
token.useDelimiter("[^A-Za-z0-9]+");
while(token.hasNext())
{
String tok=token.next();
tok=tok.toLowerCase();
try{
Comparable n= parole.find(tok); // i find the word ,if it isn't inside (the method throw an exception message) i catch the exception and i insert the word in the array with value=1; else i insert it in the array with the new value
parole.put(tok,(Integer)n+1);
}
catch(MapItemNotFoundException e)
{ parole.put(tok,1);}
}
}
System.out.println(parole);
}
}
When I print the counter the variable "value" doesn't seem to update, in fact i got something like this :
word1::1
word2::1
word3::1
etc.
I think that the update method doesn't work well, but I don't know why!:(
Could anyone help me please?
Thanks

Your binary search doesn't work... It only ever returns -1. I know this because it if ever did, this line in main: parole.put(tok,(Integer)n+1); would create a ClassCastException

Related

How to create generic code for objects of different types

I have an entity that has as children several lists of objects that, although they have different classes, all have the order attribute, in several parts I end up with repeated code, for example in one part I need to order the lists by that attribute and I cannot simplify because they are of different type.
The relevant part of the entity is this:
contenido={
"educaciones":[
{
...
"orden":0
},{
...
"orden":1
}
],
"experiencias":[
{
...
"orden":0
},{
...
"orden":1
}
]
},
...
The code I would like to simplify:
if(tipo.equals("experiencias")){
List<Experiencia> iterable=contenido.getExperiencias();
for(int i = 0; i < iterable.size(); i++){
iterable.get(i).setOrden( orden.get(i) ); //orden = [0,3,5,...]
}
iterable.sort((it1,it2)-> it1.getOrden().compareTo(it2.getOrden()));
}else if(tipo.equals("educaciones")){
List<Educacion> iterable=contenido.getEducaciones();
for(int i = 0; i < iterable.size(); i++){
iterable.get(i).setOrden( orden.get(i) );
}
iterable.sort((it1,it2)-> it1.getOrden().compareTo(it2.getOrden()));
}else if...
Is there a way to create a code that is more generic and supports different objects?
Create an interface for the methods that are common between all you classes:
interface HasOrden {
int getOrden();
void setOrden(int i);
}
Each of your classes needs to implement HasOrden.
Then you can declare sortOrden function:
import java.util.ArrayList;
import java.util.List;
interface HasOrden {
int getOrden();
void setOrden(int i);
}
class Experiencia implements HasOrden {
private final String name;
int orden;
public Experiencia(String name) {
this.name = name;
}
#Override
public int getOrden() {
return orden;
}
#Override
public void setOrden(int i) {
orden = i;
}
public String toString() {
return name;
}
}
public class Eg {
static void sortOrden(List<? extends HasOrden> l, List<Integer> order) {
if (l.size() != order.size()) {
throw new RuntimeException("length mismatch");
}
for (int i = 0; i < l.size(); i++) {
l.get(i).setOrden(order.get(i));
}
l.sort((it1,it2)-> Integer.compare(it1.getOrden(), it2.getOrden()));
}
public static void main(String[] args) {
List<Experiencia> items = new ArrayList<>(List.of(new Experiencia("a"), new Experiencia("b")));
List<Integer> order = List.of(2,1);
sortOrden(items, order);
System.out.println(items);
}
}
You can call sortOrden on any list of HasOrden instances.
you can try to create a List<?> - list with a dynamic type outside of your if else block and move your duplicated code outside too and at the end of the if else block. In addition, you have to create a common class or some interface for your classes, which holds all the common field you needed
public class Main {
public static class Something {
private Integer sth;
public Integer getSth() {
return sth;
}
public void setSth(Integer sth) {
this.sth = sth;
}
}
public static class ThisClass extends Something {
private Integer num;
public ThisClass(Integer num) {
this.num = num;
}
public Integer getNum() {
return num;
}
public void setNum(Integer num) {
this.num = num;
}
}
public static class ThatClass extends Something {
private String str;
public ThatClass(String str) {
this.str = str;
}
public String getStr() {
return str;
}
public void setNum(String str) {
this.str = str;
}
}
public static List<? extends Something> sortList(Class<?> itemClass, List<? extends Something> list)
throws Exception {
for(int i = 0; i < list.size(); i++){
list.get(i).setSth(i);
}
list.sort((it1,it2)-> it1.getSth().compareTo(it2.getSth()));
return list;
}
public static void main(String[] args) {
System.out.println("Hello World");
List<? extends Something> someList = new ArrayList<>();
boolean check = true;
if(check) {
someList = Arrays.asList(new ThisClass(1),new ThisClass(1),new ThisClass(1),new ThisClass(1));
} else {
someList = Arrays.asList(new ThatClass("a"), new ThatClass("a"),new ThatClass("a"),new ThatClass("a"));
}
try {
someList = sortList(ThisClass.class, someList);
for(int i = 0; i < someList.size(); i++){
System.out.println(someList.get(i).getSth());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

Method return new object - Java

I wondering why does this code run this way.
In this example, the print output is 4. I was thinking that if the method2 were to return a new object should it not be 3 instead?
Hopefully someone can tell me what is happening. Thanks in advance!
public class Test {
public static void main(String[] args) {
Test test = new Test();
test.method1();
}
private void method1() {
try {
TempItem item = new TempItem(5);
method2(item);
System.out.println(item.getValue());
} catch (Exception e) {
System.out.println("Error");
}
}
private TempItem method2(TempItem item) {
item.setValue(4);
return new TempItem(3);
}
class TempItem {
int value = 2;
public TempItem(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
}

Why i can't create TreeSet object from file?

class Color implements Comparable<Color>{
private long RValue;
private long GValue;
private long BValue;
public long mix;
public Color() {
this.RValue=0;
this.GValue=0;
this.BValue=0;
this.mix=0;
}
public Color(long c) {
this.RValue=c;
this.GValue=c;
this.BValue=c;
this.mix=c;
}
private void calcMix() {
this.mix=256*256*this.RValue+256*this.GValue+1*this.BValue;
}
public long getRValue() {
return this.RValue;
}
public long getGValue() {
return this.GValue;
}
public long getBValue() {
return this.BValue;
}
public void setRValue(long RValue) {
this.RValue=RValue;
calcMix();
}
public void setGValue(long GValue) {
this.GValue=GValue;
calcMix();
}
public void setBValue(long BValue) {
this.BValue=BValue;
calcMix();
}
public String toString() {
return this.RValue+" "+this.GValue+" "+this.BValue+" "+this.mix;
}
public boolean equals(Object r) {
if(r==this)
return true;
if(r==null)
return false;
if(r.getClass()!=this.getClass())
return false;
Color color=(Color) r;
if(this.RValue!=color.RValue || this.GValue!=color.GValue || this.BValue!=color.BValue)
return false;
return true;
}
public int compareTo(Color c) {
if(this.mix<c.mix)
return -1;
else if(this.mix==c.mix)
return 0;
else
return 1;
}
}
class ColorRectangle extends Color implements Comparable<Color>{
private int iX1,iY1,iX2,iY2;
public ColorRectangle() {
super();
iX1=0;
iY1=0;
iX2=0;
iY2=0;
}
public ColorRectangle(int iX1,int iY1,int iX2,int iY2,long color) {
super(color);
this.iX1=iX1;
this.iY1=iY1;
this.iX2=iX2;
this.iY2=iY2;
}
public int getIX1() {
return iX1;
}
public int getIY1() {
return iY1;
}
public int getIX2() {
return iX2;
}
public int getIY2() {
return iY2;
}
public void setIX1(int iX1) {
this.iX1=iX1;
}
public void setIY1(int iY1) {
this.iY1=iY1;
}
public void setIX2(int iX2) {
this.iX2=iX2;
}
public void setIY2(int iY2) {
this.iY2=iY2;
}
public int calcArea() {
return ((Math.max(this.iX1, this.iX2)-Math.min(this.iX1, this.iX2))*
(Math.max(this.iY1, this.iY2)-Math.min(this.iY1, this.iY2)));
}
public int calcPerimeter() {
return (2*(Math.max(this.iX1, this.iX2)-Math.min(this.iX1, this.iX2))+
2*(Math.max(this.iY1, this.iY2)-Math.min(this.iY1, this.iY2)));
}
public int compareTo(ColorRectangle r) {
if(this.calcArea()<r.calcArea())
return -1;
else if(this.calcArea()==r.calcArea())
return 0;
else
return 1;
}
public String toString() {
return iX1+" "+iY1+" "+iX2+" "+iY2+" "+mix;
}
public boolean equals(ColorRectangle r) {
if(!(r instanceof ColorRectangle))
return false;
ColorRectangle rect=r;
return (this.calcArea()==rect.calcArea() && this.getRValue()==rect.getRValue()
&& this.getGValue()==rect.getGValue() && this.getBValue()==rect.getBValue());
}
public void translateX(int iPoints) {
this.iX1+=iPoints;
this.iX2+=iPoints;
}
public void translateY(int iPoints) {
this.iY1+=iPoints;
this.iY2+=iPoints;
}
public void translateXY(int iPoints) {
this.translateX(iPoints);
this.translateY(iPoints);
}
public boolean isInside(int ptX,int ptY) {
if(ptX>iX1 && ptX<iX2 && ptY>iY1 && ptY<iY2)
return true;
return false;
}
public ColorRectangle unionRect(ColorRectangle r) {
int x1=Math.min(Math.min(this.iX1, this.iX2), Math.min(r.getIX1(),r.getIX2()));
int x2=Math.max(Math.min(this.iX1, this.iX2),Math.max(r.getIX1(), r.getIX2()));
int y1=Math.min(Math.min(this.iY1, this.iY2), Math.min(r.getIY1(),r.getIY2()));
int y2=Math.max(Math.min(this.iY1, this.iY2),Math.max(r.getIY1(), r.getIY2()));
long color=256*256*this.getRValue()+256*this.getGValue()+1*this.getBValue();
return new ColorRectangle(x1,x2,y1,y2,color);
}
public ColorRectangle intersectionRect(ColorRectangle r) {
int x1=Math.min(this.iX1,r.iX2);
int x2=Math.max(this.iX1,r.iX2);
int y1=Math.min(this.iY1, r.iY2);
int y2=Math.max(this.iY1, r.iY2);
long color=256*256*this.getRValue()+256*this.getGValue()+1*this.getBValue();
return new ColorRectangle(x1,x2,y1,y2,color);
}
}
class RectangleCollection{
private SortedSet recSet;
public RectangleCollection(String fileName) throws IOException{
try {
RandomAccessFile file=new RandomAccessFile(fileName,"r");
String line="";
String[] info=new String[5];
recSet=new TreeSet<ColorRectangle>();
while((line=file.readLine()) != null && line.length()>0 ) {
info=line.split(" ");
recSet.add(new ColorRectangle(Integer.parseInt(info[0]),
Integer.parseInt(info[1]),Integer.parseInt(info[2]),Integer.parseInt(info[3]),
Long.parseLong(info[4])));
}
file.close();
}
catch(FileNotFoundException e) {
System.out.println(e.getMessage());
}
}
public void print() {
Iterator<RectangleCollection>iterator=recSet.iterator();
while(iterator.hasNext()) {
System.out.println(iterator.next()+" ");
}
}
}
This is my main function:
public static void main(String[] args)throws IOException {
RectangleCollection recCol=new RectangleCollection("rects.txt");
recCol.print();
}
So i have this code in java and the class RectangleCollection.
My task is to create interface SortedSet of type TreeSet which will be for storing ColorRectangle objects. ColorRectangle class has 5 data members: x1,x2,y1,y2,color.
I have to make explicit constructor with name -> filename from which i will read ColorRectangle objects which i will add in TreeSet.
and this is my texfile rects.txt:
-10 -10 6 10 255
-1 -1 10 6 255
-2 -2 10 6 255
*-3 -1 10 6 255
-1 -1 10 6 255
Qhen i debug it, the print function shows me only the first line from the textfile. Can you tell me how to fix it?

I'm trying to find the sum of the objects that are defined as numbers

I'm doing an exercise, in which I have to create the method add, however due to p and v being defined as objects, I'm having a hard time figuring out how I can define this method in the syntax I've been given in the exercise (I'm only allowed to change the methods).
I would like to add the two inputs 5 and 17 so that it returns 22. I've done a lot of research into other questions where I've seen them write it as Positiv(p + v) but this doesn't quite work.
public class Positiv {
public static void main(String[] args) {
try {
Positiv p = new Positiv(5);
Positiv v = new Positiv(17);
p.add(v);
System.out.println(p.get());
} catch (Exception e) {
e.printStackTrace();
}
}
private int n;
public Positiv(int n) {
if (n < 0) { throw new IllegalArgumentException("exception");
}
this.n = n;
}
public static Positiv add(Positiv v)
{
return new Positiv(n + v);
}
public int get() {
return n;
}
}
In your add method:
public static Positiv add(Positiv v)
{
return new Positiv(n + v);
}
You return a whole new Positiv object. However (correct me if I'm wrong) it looks as if you just want to add the two n fields. You can do this by adding this.get to v.get:
public void add(Positiv v)
{
this.n += v.get();
}
Which will return 22
Tutorial for this
public class HelloWorld{
public static void main(String []args){
Numbers a = new Numbers(5);
Numbers b = new Numbers(10);
int num1 = a.getN();
int num2 = b.getN();
System.out.println(addTwoNumbers(num1, num2));
}
public static int addTwoNumbers(int a, int b) {
return a + b;
}
}
class Numbers {
private int n;
public Numbers(int n) {
this.n = n;
}
public int getN() {
return n;
}
}

What is wrong with this code? It won't run

public class StackSimple{
private long capacity=1000;//maximum size of array
private int idx_top;
private Object data[];
public StackSimple(int capacity)
{
idx_top=-1;
this.capacity=capacity;
data = new Object[capacity];
}
public boolean isEmpty(){
return(idx_top<0);
}
public boolean isFull(){
return(idx_top>=capacity-1);
}
public int size()
{
return idx_top+1;
}
public boolean push(Object x){
if (isFull()){
throw new IllegalArgumentException("ERROR:Stack Overflow.Full Stack");
}
else
{`enter code here`data[++idx_top]=x;
return true;
}
}
public Object pop(){
if(isEmpty())
throw new IllegalArgumentException("ERROR:Stack Underflow.Empty Stack.");
else{
return data[idx_top--];
}
}
public Object top(){
if (isEmpty())
throw new IllegalArgumentException("ERROR:Stack Underflow.Empty Stack.");
else{
return data[idx_top];
}
}
public void print()
{`
for (int i=size()-1;i>=0;i--)
System.out.println(data[i]);
}
}
public class Stack_Exercise {
public static void main(String[] args) {
StackSimple s = new StackSimple(capacity:3);//error shows here
s.push(x:"books");`enter code here`
s.push(x:"something");
s.push(x:"200");
s.print();
System.out.println("Size=" +s.size());
}
}
Why doesn't this work?
Why does it say invalid statement while creating the StackSimple object? The problem is in the main class while running it. There are errors while pushing the elements.
Error while compiling
When passing parameters to a function you just pass the values.
In your case not StackSimple(capacity:3) but just StackSimple(3)
First question, which version of Java are you using.
Second, in Java you should be passing as a variable instead of StackSimple(capacity:3). Change your main method to below, here is my recommendation:
StackSimple s = new StackSimple(3);
s.push("books");
s.push("something");
s.push("200");
s.print();
System.out.println("Size=" +s.size());
You are not at all pushing the value in the stack, your pusch function is not working as it is expected to work.
Here is the correct program.
class StackSimple {
private long capacity = 1000;// maximum size of array
private int idx_top;
private Object data[];
public StackSimple(int capacity) {
idx_top = -1;
this.capacity = capacity;
data = new Object[capacity];
}
public boolean isEmpty() {
return (idx_top < 0);
}
public boolean isFull() {
return (idx_top >= capacity - 1);
}
public int size() {
return idx_top + 1;
}
public boolean push(Object x) {
if (isFull()) {
throw new IllegalArgumentException("ERROR:Stack Overflow.Full Stack");
} else {
data[++idx_top] = x;
return true;
}
}
public Object pop() {
if (isEmpty())
throw new IllegalArgumentException("ERROR:Stack Underflow.Empty Stack.");
else {
return data[idx_top--];
}
}
public Object top() {
if (isEmpty())
throw new IllegalArgumentException("ERROR:Stack Underflow.Empty Stack.");
else {
return data[idx_top];
}
}
public void print() {
for (int i = size() - 1; i >= 0; i--)
System.out.println(data[i]);
}
}
public class test {
public static void main(String[] args) {
StackSimple s = new StackSimple(3);// error shows here
s.push("books");
s.push("something");
s.push("200");
s.print();
System.out.println("Size=" + s.size());
}
}

Categories