I'm writing a dictionary for Vietnamese but my Treeset just add 1 object. I've been searching for 2 days but i cant figure it out how. hope you guys help me.
public class Word implements Comparable<Word> {
private static String word_target, word_explain;
public static void setWord_target(String word_target) {
Word.word_target = word_target;
}
public static void setWord_explain(String word_explain) {
Word.word_explain = word_explain;
}
public String getWord_explain() {
return word_explain;
}
public String getWord_target() {
return word_target;
}
#Override
public int compareTo(Word word) {
return this.getWord_target().compareTo(word.getWord_target());
}
}
public class Dictionary {
private TreeSet<Word> words = new TreeSet<Word>();
public TreeSet<Word> getWords() {
return words;
}
}
public class DictionaryManagement {
static Scanner reader = new Scanner(System.in);
public static int numbers;
public static void insertFromCommandline(Dictionary dic) {
numbers = reader.nextInt();
reader.nextLine();
for (int i = 0; i < numbers; i++) {
Word putInWord = new Word();
String en_word, vn_word;
System.out.print("English Word: ");
en_word = reader.nextLine();
putInWord.setWord_target(en_word);
System.out.print("VietNameses Word: ");
vn_word = reader.nextLine();
putInWord.setWord_explain(vn_word);
dic.getWords().add(putInWord);
}
}
}
public class DictionaryCommandline {
private static int num = 1;
public static Dictionary showWord = new Dictionary();
public static void showAllWords() {
System.out.println("No |English |Vietnamese");
for (Word wr : showWord.getWords()) {
System.out.println( num++ + " |" + wr.getWord_target() + " |" + wr.getWord_explain());
}
}
public static void dictionaryBasic() {
DictionaryManagement.insertFromCommandline(showWord);
DictionaryCommandline.showAllWords();
}
}
public class Main {
public static void main(String []args) throws Exception {
DictionaryCommandline.dictionaryBasic();
}
}
Example:
Input:
2
English Word:
house
VietNameses Word:
ngoi nha
English Word:
name
VietNameses Word:
ten
-Actual Output:
No English Vietnam
1 name ten
-Expected Output:
No English Vietnam
1 house ngoi nha
2 name ten
#Huy, note that you are using static variables, try using only instance variables for your Word, instances.
This makes your compareTo method always compare the latest words you inserted because static variables are associated only with a class, representing a single value/instance at a time.
Take a look here for a few more words on static # java
Related
I wanted to create a simple program for user to insert 3 strings to a private string array in a class and then print it back by creating a new object using object reference but I think I am facing problem in the setter/getter.(Pretty new to class and setter/getter) Here is what I have so far:
import java.util.Scanner;
public class Stringtest {
public static void main(String[] args)
{ Scanner input=new Scanner(System.in);
Stringer Strung=new Stringer();
System.out.println("Strings:"+Strung.print());
}
}
class Stringer
{ Scanner input=new Scanner(System.in);
private String[] aa=new String[3];
aa[0]="zero";
aa[1]="one";
aa[2]="two";
Stringer()
{}
{ System.out.println("Please enter 3 strings:");
for(int i=0;i<4;i++)
{
aa[i]=input.next();
}
}
public void setaa(String[] a)
{
aa=a;
}
public String[] getaa()
{
return aa;
}
public void print(String[] a)
{
for(int b=0;b<4;b++)
{
System.out.printf("%s",a[b]);
}
}
}
Due to populating the array while creating a class instance, you don't require any setters. The only getter requires.
Divide the logic from the runner.
Always use array.length() while looping or use a simple for loop otherwise you'll be getting an indexOfBoudException error.
Didn't get why you are using printf() while printing results.
My solution:
import java.util.Scanner;
public class App {
public static void main(String[] args) {
App.run();
}
private static void run() {
Stringer stringer = new Stringer();
stringer.print(stringer.getStrings());
}
}
class Stringer {
private String[] strings = new String[3];
Stringer() {
System.out.println("Please enter 3 strings:");
for (int i = 0; i < 4; i++) {
Scanner scanner = new Scanner(System.in);
strings[i] = scanner.next();
}
}
String[] getStrings() {
return strings;
}
void print(String[] strings) {
System.out.println("Strings are:");
for (String string : strings) {
System.out.println(string);
}
}
}
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 need to know how to fetch the input for the operator for this simple program I am making that does this; the person enters a number, and if it's greater than 10, it displays the message "it worked". Where it says "NEED INPUT" is where I need the system scanner entry to go.
Operators class:
class Classes {
private int Numbers;
public Classes() {}
Classes(String namez) {
Numbers = Numbers;
}
public int getNumbers() {
return Numbers;
}
public void setNumbers(int numberz) {
if((Integer.parseInt(INPUT HERE.getText().toString()) )<=10) {
System.out.print("It worked.");
}
}
}
Main class:
import java.util.Scanner;
public class OneTwoThree {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a number: ");
Classes.Numbers(keyboard.nextLine());
}
}
package mavens.dais.test;
public class ClassesTest {
private int Numbers;
public ClassesTest() {}
ClassesTest(String namez) {
Numbers = Integer.parseInt(namez);
}
public int getNumbers() {
return Numbers;
}
public void setNumbers(int numberz) {
if(numberz > 10){
System.out.print("It is worked.");
}else{
System.out.print("It is not worked.");
}
}
}
package mavens.dais.test;
import java.util.Scanner;
public class OneTwoThre {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a number: ");
new ClassesTest().setNumbers(Integer.parseInt(keyboard.nextLine()));
}
}
Firstly
Classes.Numbers(keyboard.nextLine());
this should be replaced by Classes(keyboard.nextLine()); to begin with, in your class named OneTwoThree
Secondly
Classes(String namez) {
Numbers = Numbers;
}
this seems pretty much wrong.
Should be replaced by something like
Classes(String namez) {
Numbers = Integer.parseInt(namez); //if you are entering integers only through keyboard
}
As far as I could understand your question,
you can go like this then,
Classes(String namez) {
Numbers = Integer.parseInt(namez); //if you are entering integers only through keyboard
performOperation(Numbers);// call a method you want,pass number as arg
}
public static void performOperation(int num){
if(Numbers >10){
//do stuff
}
else{
//else part
}
}
}
Also ,just as a good practice you should name your variable Numbers to number.
I Hope it helped.
You just need to pass the String.
public static void testScanner() {
try (Scanner keyboard = new Scanner(System.in);) {
System.out.print("Enter a number: ");
while (true) {
String input = keyboard.nextLine();
if (input.equalsIgnoreCase("exit")) {
break;
}
Handler.handleInput(input);
}
System.out.println("Done.");
}
}
static class Handler {
public Handler() {
}
public static void handleInput(String input) {
try {
int x = Integer.parseInt(input);
if (x <= 10) {
System.out.println("It worked!");
} else {
System.out.println("Aw, Id didn't work.");
}
} catch (Exception ex) {
System.out.println("Hey, watch it buddy. Don't throw any letters in there, I don't like them.");
}
}
}
I am creating an object of a class from 2 separate classes and both objects are returning different values for the same method. I suspect it may be an issue with the while loop but here are the classes. The main class works, the setup class is the class that is being turned into and object and the game loop class has the object that doesn't return the right values. it returns the values defined at the beginning of setup and not the modified versions.
import java.util.Scanner;
public class MainClass {
static Scanner input = new Scanner(System.in);
//String x = input.nextLine();
public static void main(String[] args)
{
setup setupGov = new setup();
gameLoop gameLoop = new gameLoop();
setupGov.statsSetup();
System.out.println("happyness: " + setupGov.getHappyness() + " money: £" + setupGov.getMoney() + " population: " + setupGov.getPopulation());
gameLoop.loop();
}
}
import java.util.Scanner;
public class setup {
static Scanner input = new Scanner(System.in);
String goverment;
int happyness;
double money;
int population = 1000000;
public setup()
{
}
public void statsSetup()
{
System.out.println("Choose a goverment: 1. democracy 2. monarchy 3. dictatorship");
goverment = input.nextLine();
if (goverment.equals("1"))
{
happyness = 75;
money = 250000.0;
}
else if (goverment.equals("2"))
{
happyness = 50;
money = 500000.0;
}
else if (goverment.equals("3"))
{
happyness = 25;
money = 750000.0;
}
else
{
System.out.println("ENTER A VALID VALUE");
}
}
public int getHappyness()
{
return happyness;
}
public double getMoney()
{
return money;
}
public int getPopulation()
{
return population;
}
}
import java.util.Scanner;
public class gameLoop
{
static Scanner input = new Scanner(System.in);
static int turn = 0;
int happyness;
double money;
int population;
public gameLoop()
{
}
setup setupGov = new setup();
public static void main(String[] args)
{
}
public void loop()
{
while (true)
{
System.out.println("Turn: "+turn);
input.nextLine();
turn++;
}
}
}
You are creating two different instances of class setup. One is created directly in main function and other is created in gameLoop object. They do not share their attributes so methods may return different value. Every time you use 'new' operator, a new instance of class is created with it's own attributes (only static member are shared since static member belongs to class instead of instances). If you want to have same instances you could write:
public class gameLoop
{
static Scanner input = new Scanner(System.in);
static int turn = 0;
int happyness;
double money;
int population;
public gameLoop(setup setupGov)
{
this.setupGov = setupGov;
}
setup setupGov;
public static void main(String[] args)
{
}
public void loop()
{
while (true)
{
System.out.println("Turn: "+turn);
input.nextLine();
turn++;
}
}
}
And in main:
public class MainClass {
static Scanner input = new Scanner(System.in);
//String x = input.nextLine();
public static void main(String[] args)
{
setup setupGov = new setup();
gameLoop gameLoop = new gameLoop(setupGov);
setupGov.statsSetup();
System.out.println("happyness: " + setupGov.getHappyness() + " money: £" + setupGov.getMoney() + " population: " + setupGov.getPopulation());
gameLoop.loop();
}
}
Now both of objects setupGov will be the same instance.
Please note:
It is good practice to have class name written with capitalized first letter eg. GameLoop instead of gameLoop
I don't really understand what you're trying to do or what the question is, but in your main class you have an object with the same exact name of the class.
gameLoop gameLoop = new gameLoop();
I don't know if that's the exact cause of your problem, but I'm almost sure that that isn't supposed to be like that.
Hello So I have a entire class called tractor with different data's stored in it but now I'm suppose to create an object call tractor with a zero parameter constructor but This is the code I have so far and its giving em errors
First off this my Tractor Class which is in a different file:
import java.util.Scanner;
class Tractor
{
private int RentalRate;
private int RentalDays;
private int VehicleID;
private int RentalProfit;
public void setRentalRate(int r)
{
Scanner input = new Scanner(System.in);
System.out.println("What's the Rental Rate?");
int num = input.nextInt();
num = r;
if(r<0 || r >1000)
RentalRate = r;
RentalRate= 1;
}
public int getRentalRate()
{
return RentalRate;
}
public void setVehicleID(int v)
{
Scanner input = new Scanner(System.in);
System.out.println("What's the vehicleID?");
int num1 = input.nextInt();
num1 = v;
if(v<0)
VehicleID = v;
VehicleID = 1;
}
public int getVehicleID()
{
return VehicleID;
}
public void setRentalDays(int d)
{
Scanner input = new Scanner(System.in);
System.out.println("How many rental days?");
int num2 = input.nextInt();
num2 = d;
if(d<0)
RentalDays = d;
RentalDays = 1;
}
public int getRentalDays()
{
return RentalDays;
}
public String toString()
{
String str;
str = "RentalDays:" + RentalDays +"\nRenalRate:" + RentalRate + "\nVehicleID " + VehicleID;
return str;
}
public void RentalProfit(int RentalRate, int RentalDays)
{
RentalProfit = RentalRate * RentalDays;
}
}
import java.util.Scanner;
public class testTractor
{
public static void main(String[] args)
{
public tractor()
{
this.RentalDays = d;
this.RentalRate = r;
this.VehicleID = v;
}
}
}
The error is :
testTractor.java:7: error: illegal start of expression
public tractor()
^
testTractor.java:7: error: ';' expected
public tractor()
^
2 errors
You have compilation errors. You need to first declare the Tractor class then add the constructor inside it. One way to do is declare in a separate file. Also in Java unless you had defined d you couldnt have assigned it. Maybe you wanted to assign the day as a String look in the examples I provide below.
You need to to first create a file call Tractor.java and then define variables there. For example contents of Tractor.java:
public class Tractor {
String rentaldays,someOtherValue;
public Tractor(){
rentaldays ="monday";
someOtherValue="value";
}
//or
public Tractor(String rentalDays){
this.rentaldays = rentalDays;
someOtherValue = "asf";
}
}
Then in your main method You can do Tractor trac = new Tractor(); or Tractor trac = new Tractor("tuesday"); also after that you can print the rentaldays of trac using System.out.println(trac.rentaldays);
From the looks of it you will probably be making a tractor rental system. In that case, rentalDays may be an array of Strings. And then you would have an array of Tractor objects to store in the rental system. You can look at these terms and keywords to point you in the right direction.
You are defining it wrong, define your methods inside class then call them in main() method.
class Test{
public void greeting(){
System.out.print("hello to JAVA..");
}
public static void main(String[] args){
Test testObj = new Test();
testObj.greeting();
}
}
you use an illegal of java syntax, if you already have class tractor in your project. for calling it to in other class, try below code
public class TestTractor(){
Tractor objTractor;
public static void main(String[] args){
//create new tractor object with no parameter
objTractor = new Tractor();
//create new tractor object with parameter
objTractor = new Tractor(parameter here);
//do some action of object here
...........
}
}
//This is just a sample
in your tractor class add below code
public tractor()
{
this.RentalDays = d;
this.RentalRate = r;
this.VehicleID = v;
}
And keep your TestTractor class as
public class TestTractor(){
public static void main(String[] args){
Tractor objTractor = new Tractor();
// objTractor.yourMethodName
}
}