I have a problem with this code. My purpose is to create a Dictionary that counts the frequency of a word in a text, using an Array of Objects (I can't use Hash Map or something else). I created a class Pair that contains the couple (word,count).
public class Pair
{ public String word;
public int count;
public Pair(String word,int count)
{this.word=word;
this.count=count;
}
public String getWord()
{return word;}
public int getCount()
{return count;}
public void addCount()
{count++;}
public String toString()
{ return getWord()+" "+getCount();}
}
And the class Dict that creates an Array of object using the Pair class
public class Dict
{ private Pair [] a;
private int inputSize;
public Dict()
{a=new Pair[10];
inputSize=0;
}
public void insert(Pair x)
{ if(a.length==inputSize)
{ Pair newA []=new Pair [2*inputSize];
for(int i=0;i<inputSize;i++)
{ newA[i]=a[i];
}
a=newA;
}
for(int i=0;i<inputSize;i++) // i check if x is already in the array if i find it i replace it otherwise i add it in the array
{ if(a[i].getWord().equals(x.getWord()))
{a[i]=x;
}
}
a[inputSize++]=x;
}
public Pair find(Pair x) // if i don't find x return null
{ for(int i=0;i<inputSize;i++)
{ if(a[i].getWord().equals(x.getWord()))
{return a[i];}
}
return null;
}
public String toString()
{String s="";
for(int i=0;i<inputSize;i++)
{ s=s+a[i].toString()+'\n';
}
return s;
}
}
After I created the test class with the main method
import java.util.*;
import java.io.*;
public class MyDict
{public static void main(String [] args)
{ Dict d=new Dict();
Scanner c=new Scanner(System.in);
while(c.hasNext())
{String s=c.next();
Pair p=new Pair(s,1); // create a new pair
Pair previous=d.find(p);
if(previous!=null) //if the pair is already in the stack i add 1 to the counter otherwise i insert it in the array
{p.count++;}
else
{d.insert(p);}
s="";
}
System.out.println(d);
}
}
But it doesn't work, in particular the variable "count" doesn't grow.
For example, if I write "how how are are you you " I get:
how 1
are 1
you 1
Can anyone help me please?
Change p.count++ to previous.count++.
Otherwise you never change the count of the existing Pairs.
Pair p=new Pair(s,1);
Pair previous=d.find(p);
if(previous!=null) {
previous.count++;
} else {
d.insert(p);
}
Related
I am trying to write a method that search an ArrayList of a particular word and then prints the location of all of the occurrences of the word.
Here is what I have, it works fine until I enter the word I want to search but then it prints nothing:
import java.util.ArrayList;
import java.util.Scanner;
public class W7E2 {
public static void main(String[]args) {
System.out.println("Please anter words: ");
Scanner sc = new Scanner(System.in);
String []w = sc.nextLine().split(" ");
ArrayList<Words> word = new ArrayList<Words>();
for(int i=0; i<w.length; i++) {
word.add(new Words(w[i]));
}
System.out.println(word);
System.out.println("Please enter the word you want to search: ");
String search = sc.nextLine();
for(Words ws: word) {
if(ws.equals(search)) {
System.out.println(ws.getLocation());
}
}
}
static class Words{
private String wor;
private static int number = -1;
public Words(String wor) {
this.wor = wor;
number++;
}
public int getLocation() {
return number;
}
public String toString() {
return wor;
}
}
}
In your if statement to see if the ArrayList contains the word you have:
if(ws.equals(search)) {
System.out.println(ws.getLocation());
}
But ws is a Word object and unless you override the equals() method, it will never equal the String object. You need to do something like:
if(ws.getwor().equals(search)) {
System.out.println(ws.getLocation());
}
This is assuming that you create a get method for wor.
Besides GBlodgett's answer,the number in class Word is static,so each Word instance will have a same number,you need to use a no-static variable to store the location
static class Words{
private String wor;
private static int number = -1;
private int location;
public Words(String wor) {
this.wor = wor;
number++;
location = number;
}
public int getLocation() {
return location;
}
public String toString() {
return wor;
}
}
Your code should be like this :
for(Words ws: word) {
if(ws.toString().equals(search)) { //to change
System.out.println(ws.getLocation());
}
}
ws is the object of Words class, you have to change it to toString()
What you should do is instead of
ws.equals(search)
you need to add
ws.toString().equals(search)
as you return the word from the
toString()
method in the Words Class.
So the code should look something like this,
for(Words ws: word) {
if(ws.toString().equals(search)) {
System.out.println(ws.getLocation());
}
}
I am new with java and I need to save the content of a stack of objects into an array which will have an array attribute and also the array attribute has an array attribute I know it kind complicated but I need to do that because it's looks like a table. Anyway, this is my code
//First class
public static class classA //inner
{ public char sy;
public ArrayList <Integer> arrystateA;
public classA()
{ sy='0';
arrystateA= new ArrayList <Integer>();} }
//The second class
public static class ArrayofclassA// meddile
{ int num;
public ArrayList <classA> arrystateB;
public ArrayofclassA()
{ arrystateB=new ArrayList < classA>();
num=-1;}
public void creatrans(classA z)
{ arrystateB.add(z);
} }
and this the main code
classA temp2=new classA();
ArrayofclassA temp3 = new ArrayofclassA();
ArrayList<ArrayofclassA> NFAtranstable=new ArrayList<ArrayofclassA>();
while(!reslt.empty()){
temp=reslt.pop();
for (int i=0;i<NFAtranstable.size();i++)
{temp3=NFAtranstable.get(i);
if (temp3.num==temp.s_to)
{
if(temp3.arrystateB.get(i).sy==temp.t_sym)
{
temp3.arrystateB.get(i).arrystateA.add(temp.s_to);
match=true;
}else
{temp2.sy=temp.t_sym;temp2.arrystateA.add(temp.s_to);
temp3.creatrans(temp2);
match=true;
}
}
}
if(!match)
{
temp2.sy=temp.t_sym;
temp2.arrystateA.add(temp.s_to);
temp3.num=temp.s_from;
temp3.arrystateB.add(temp2);
NFAtranstable.add(temp3);
}
match=false;
}
for(int i=0;i<NFAtranstable.size();i++)
{
System.out.print(NFAtranstable.get(i).num+" ");
for(int j=0;j<NFAtranstable.get(i).arrystateB.size();j++)
{
System.out.println(NFAtranstable.get(i).arrystateB.get(j).sy+" ");
for(int k=0;k<NFAtranstable.get(i).arrystateB.get(j).arrystateA.size();k++)
{
System.out.print(NFAtranstable.get(i).arrystateB.get(j).arrystateA.get(k));
}
}
}
}
the problem that when I print the content of the array 'NFAtranstable' it's gives me duplicate results like it just save the same valus, it's been about 8 hours and I couldn't find the problem =(
So I'm taking a basic course in Java at university. I'm trying to create a class Bachelorstudents containing an arraylist of class Bachelorstudent (respectively plural and singular of "bachelorstudents" in english) which contains a HashMap of course (key) and marks (value).
My problem is the infamous "non-static method cannot be referenced from a static context".
"Bachelorstudent"-class:
public class Bachelorstudent{
private String navn;
private int studentNummer;
private HashMap<String, Integer> karakterListe = new HashMap<>();
public Bachelorstudent(String navn, Integer studentNummer){
setNavn(navn);
setStudentNummer(studentNummer);
}
public Bachelorstudent(){
}
public void setKarakter(String fagkode, Integer karakter){
karakterListe.put(fagkode, karakter);
}
public HashMap<String, Integer> getKarakter(){
return karakterListe;
}
public int snitt(){
Integer snittKarakter = 0;
int counter = 0;
if(!karakterListe.isEmpty()){
for(Integer karakter : karakterListe.values()){
snittKarakter += karakter;
counter++;
}
}else{
return 6;
}
return snittKarakter /= counter;
}
public int getKarakterer(){
Integer karakterer = 0;
if(!karakterListe.isEmpty()){
for(Integer karakter : karakterListe.values()){
karakterer += karakter;
}
}else{
return 0;
}
return karakterer;
}
public void setNavn(String navn){
this.navn=navn;
}
public String getNavn(){
return navn;
}
public void setStudentNummer(int studentNummber){
this.studentNummer=studentNummer;
}
public int getStudentNummer(){
return studentNummer;
}
}
"Bachelorstudenter"-class:
public class Bachelorstudenter{
private ArrayList<Bachelorstudent> bachelorStudenter = new ArrayList<>();
public Bachelorstudenter(){
}
public void karakterSnitt(){
for(Bachelorstudent bachelorstudenter : bachelorStudenter){
Bachelorstudent student = new Bachelorstudent();
for(Bachelorstudent bachelorstudent : Bachelorstudent.getKarakter()){ //<-- Non-static method error.
}
}
}
public Boolean eksisterer(Bachelorstudent student){
boolean finnes = false;
for(Bachelorstudent bachelorstudent : bachelorStudenter){
if(bachelorstudent.getNavn().equals(student.getNavn())){
finnes = true;
}
}
return finnes;
}
public Boolean nyBachelorstudent(Bachelorstudent student){
if(!eksisterer(student)){
bachelorStudenter.add(student);
return true;
}
else{
System.out.println("Eksisterer i systemet fra før");
return false;
}
}
}
I have tried several things, such as calling an instance of class Bachelorstudent (as seen above), tried inheritance (not sure if I did this right, but what I did didn't work). How can I call on the .getKarakter() method in class Bachelorstudenter?
Edit: Just to clarify. The point of this method is to get the average of every mark of every bachelorstudent. I have a method in Bachelorstudent which does this, but I need the equivalent in Bachelorstudenter, which will find the average of every mark of every course of every student.
You need to use an object to call a non-static method.
In your example, you need to use the object of the current iteration to invoke the method:
for(Bachelorstudent bachelorstudenter : bachelorStudenter){ // Iterate over the bachelorStudenter list.
bachelorstudenter.getKarakter(); // Use the bachelorstudenter of this iteration.
}
I need to take a collection of objects using the CompareTo() command, and then have these stored in a list, and then use the collections.sort() command to sort them alphabetically by last name, then by first name if the last name isn't strong enough, and then print off the entire list at the end.
This is the code I have so far:
package sortlab;
import java.io.*;
import java.util.*;
public class SortLab {
public static void main(String[] args) throws Exception {
File youSaidUseOurRelativeFileNameForStudentData =
new File("C:/My192/SortLabProj/src/sortlab/student.data");
Scanner sc = new Scanner(youSaidUseOurRelativeFileNameForStudentData);
ArrayList<Student> StudentList = new ArrayList<Student>();
while (sc.hasNextLine()) {
Student testStudent = new Student(sc.next(), sc.next(), sc.next());
sc.nextLine();
StudentList.add(testStudent);
}
}
}
And the next class:
package sortlab;
import java.util.*;
class Student implements Comparable<Student> {
private String first;
private String last;
private String address;
public Student(String f, String l, String a) {
first = f;
last = l;
address = a;
}
#Override
public int compareTo(Student other) {
if (last.hashCode() > other.last.hashCode()) return 1;
if (last.hashCode() < other.last.hashCode()) return -1;
if (first.hashCode() > other.first.hashCode()) return 1;
if (first.hashCode() < other.first.hashCode()) return -1;
return 0;
}
}
If you want to compare them ASCIIbetically use the String.compareTo method. It would never occur to me to compare hashCodes.
If you want to ignore case, you can use String.compareToIgnoreCase
First of all I would add getters for first and last name. Then try this code:
#Override
public int compareTo(Student other) {
int result = l.compareTo(other.getLastName());
if (result == 0) {
return f.compareTo(other.getFirstName());
} else {
return result;
}
}
Then add a toString() method to your Student class:
#Override
public String toString() {
return f+" "+l+", "+a;
}
I have 2 classes 'Main' and 'FOR'. From 'Main' I will call method 'display' in class 'FOR'. 'display' will get multiple String values and return it to 'Main' class. Here the returned values must be displayed.
Only one single value is returned. How to get that multiple values returned?
Main.class
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
FOR obj = new FOR();
String str = obj.display();
System.out.print(str);
}
}
FOR.class
public class FOR {
int j=5;
String hi="hi";
String display()
{
for(int i=0;i<j;i++)
{
System.out.print(hi);
// If I use this I will get 5 times hi.. but I dont
/// want like this. I have to return hi String 5times to main and I have to display
/// but should not call 5 times display() too,by calling one time, I have to return
/// 5 time a string to Main class
}
return hi;
}
}
Desired output is to return 5 values from the method 'display'. Here I have to get 5 times HI .. But I am getting only one time .. the comment inline explains in more detail.
You can use List.
Example:
import java.util.List;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
FOR obj=new FOR();
List<String> str= obj.display();
for(String v: str) {
System.out.print(v);
}
}
}
import java.util.List;
import java.util.ArrayList;
List<String> display() {
int j=5;
String hi="hi";
List<String> result = new ArrayList<String>();
for(int i=0;i<j;i++) {
result.add(hi);
}
return result;
}
A slightly different and more complicated approach but is useful in certain situations.
public class Main {
public static void main(String[] args) {
FOR obj = new FOR();
String str = obj.display(new ICallback() {
#Override
public void doSomething(String obj) {
// do whatever you want with this
System.out.println("This is being returned for each execution " + obj);
}
});
System.out.print(str);
}
public static interface ICallback
{
void doSomething(String obj);
}
public static class FOR {
int j = 5;
String hi = "hi";
String display(ICallback callback) {
for (int i = 0; i < j; i++) {
callback.doSomething(hi);
}
return hi;
}
}
}