I need some help with this java code, i seem to get stuck at the object vara var = new vara("banan","12.5","5"). I thought since i created a constructor in class vara with three arguments String,double and int it would be fine to call for them in the test class and get the result i want but i get an error stating that constructor vara in class vara cannot be applied to given types. And it says it requires a string, a double and an int. But i have provided these so what is the problem?? id be thankful for any kind of help, im stuck with this for 4 days now and i just cant see any light in the tunnel.
import java.lang.String;
public class Vara {
//Deklarerar variabler
private String name;
private double price;
private int antal;
//tildela konstruktorer för de deklarerade variablerna
public Vara (String name, int antal, double price) {
this.name = name;
this.antal = antal;
this.price = price;
} // slut constructor
public void setName(String name) {
this.name = name; }
public void setPrice (double price) {
this.price = price; }
public void setAntal (int antal) {
this.antal = antal; }
public String getName() {
return this.name;}
public double getPrice() {
return this.price; }
public int getAntal() {
return this.antal; }
}
//testklassen ska stå som en egen klass
class Test {
public void main(String[] args){
}
Vara var = new Vara("Banan","12.5","5") {
#Override
public void setName(String name) {
var.setName("Banan");
}
#Override
public void setPrice (double price) {
var.setPrice("12.5");
}
#Override
public void setAntal (int antal) {
var.setAntal("5");
System.out.println("Namnet är " +var.getName() +" priset är " +var.getPrice() +" och antalet är "+var.getAntal() );// här slutar system.out
}// slut main
}
// slut Test klass
You are invoking the constructor with wrong parameters :
Vara var = new Vara("Banan","12.5","5")
is not what your constructor expects :
public Vara (String name, int antal, double price)
You are passing three String literal to the constructor when it expects a String,int,double in specified order. Anything enclosed in "" is a String literal.
Replace with :
Vara var = new Vara("Banan",5,12.5);
"Banan" ---> It is a String literal.
12.5 ---> double by default , 12.5f is float.
5 ---> int by default , 5l is long.
You need to do the same thing while invoking the setter methods.
Please note that you are calling your constructor with 3 String parameters:
Vara var = new Vara("banan", "12.5", "5");
As you have only defined a constructor which takes a String, an int and a double you have to remove the quotation marks:
Vara var = new Vara("banan", 12.5, 5);
Also this will not work as you now supply a double to the int parameter and vice versa. So either you have to change your constructor to
public Vara (String name, double price, int antal)
or change your call to
Vara var = new Vara("banan", 5, 12.5);
Remove the double quotes from the last two arguments to constructor:
Vara var = new Vara("Banan",5,12.5);
Reason: If you enclose between double quotes then it is treated as String by Java and not double or int. And as your constructor does not accept three String arguments it gives error.
Same is the issue with the setter methods that you are calling on the var object.
the setAntal(int antal) needs an int argument but you are passing String. Hence remove double quotes while calling setter method too.
var.setAntal(5);
var.setPrice(12.5);
Also when you send the tree arguments to the constructor, then you do not need to call the setter method for setting the same values again.
Running Code:
public class Vara {
//Deklarerar variabler
private String name;
private double price;
private int antal;
//tildela konstruktorer för de deklarerade variablerna
public Vara (String name, int antal, double price) {
this.name = name;
this.antal = antal;
this.price = price;
} // slut constructor
public void setName(String name) {
this.name = name; }
public void setPrice (double price) {
this.price = price; }
public void setAntal (int antal) {
this.antal = antal; }
public String getName() {
return this.name;}
public double getPrice() {
return this.price; }
public int getAntal() {
return this.antal; }
}
//testklassen ska stå som en egen klass
class Test {
public static void main(String[] args){
Vara var = new Vara("Banan",5, 12.5);
System.out.println("Namnet är " +var.getName() +" priset är " +var.getPrice() +" och antalet är "+var.getAntal() );// här slutar system.out
}
}
To point out some errors:
Your main method must be static
main method ended as soon as it starts and code must be inside the main method.
For others compare my code with yours. I would recommend you to see some basic java tutorials.
As you declared constructor of the class as public Vara (String name, int antal, double price) , so at you should call create an object of this class is as follow
Vara var = new Vara("Banan",5,12.5);
Related
I am new to java, and I am trying to create a method to update the instance variable age for my objects. I am getting the code to compile, but I am seeing no change in the age value. This code is part of an assignment, so I cannot change the constructors. The method I wrote to update the age (that doesn't work) is shown below. My entire code is shown below that. I am also curious if there's a way to update/change just one of my objects, but before I do that, I need the method to work for both. Any help writing this method properly would be appreciated!
public void setnewAge(int age) {
dogAge += 1;
this.dogAge = dogAge;
}
Below is my entire code (including the method I wrote to update age).
public class Dog {
//Instance Varibles
private String dogName;
private int dogAge;
private int dogWeight;
//Two Contructors (One Completely Empty)
public Dog() {
}
public Dog(String name, int age, int weight){
dogName = name;
dogAge = age;
dogWeight = weight;
}
//Getters
public String getName() { return dogName;}
public int getAge() { return dogAge;}
public int getWeight() { return dogWeight;}
//Setters
public void setName(String theName) { dogName = theName;}
public void setAge(int theAge) {dogAge = theAge;}
public void setWeight(int theWeight) {dogWeight = theWeight;}
//to(String) method
public String toString() {
return "The dogs's name is " + getName() + ", the dogs's age is " +
getAge() + ", " + "\n" + "the dogs's weight is " + getWeight() + ".";
}
public void setnewAge(int age) {
dogAge += 1;
this.dogAge = dogAge;
}
//Main Method
public static void main(String[] args) {
Dog poodle = new Dog("Bob", 5, 26);
System.out.println(poodle);
Dog lab = new Dog();
lab.setName("Steve");
lab.setAge(8);
lab.setWeight(43);
System.out.println(lab);
}
}
As Tom said, you need to actually call the function in your main function otherwise, there will be no change, and also to refine your code for your setnewAge function, try this:
public void setnewAge() {
this.dogAge = dogAge + 1;
}
Then in the main function call setnewAge() and then print your age to see the results.
Dog poodle = new Dog("Bob", 5, 26);
poodle.setnewAge() ;
I got a product object with two attributes which I want to oberserve with two different oberservers. But if I only change one attribute I also get a notification from the other attribute observer that it got changed. How can I make sure to only get a notification when it really got changed?
import java.util.Observable;
public class Product extends Observable {
private String name;
private double price;
public void setName(String n){
name = n;
this.setChanged ();
this.notifyObservers();
}
public void setPrice(double p){
price = p;
this.setChanged ();
this.notifyObservers();
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
}
public class ObserverDemo {
public static void main(String [] args) throws Exception {
Product p1 = new Product();
p1.addObserver((obj, arg) -> System.out.println("Name was changed to: " + ((Product) obj).getName()+"\n"));
p1.addObserver((ob, arg) -> System.out.println("Price was changed to: " + ((Product) ob).getPrice()+"\n"));
p1.setPrice(1.95);
p1.setName("Milk");
p1.setName("Banana");
p1.setPrice(0.95);
}
}
Any change on the observable class will notify all the registered observer classes. You can use the argument in the notifyObservers method to identify the change and create only one observer object.
import java.util.Observable;
public class Product extends Observable {
private String name;
private double price;
public void setName(String n){
name = n;
this.setChanged ();
this.notifyObservers("Name was changed to " + n + "\n");
}
public void setPrice(double p){
price = p;
this.setChanged ();
this.notifyObservers("Price was changed to " + p + "\n");
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
}
public class ObserverDemo {
public static void main(String [] args) throws Exception {
Product p1 = new Product();
p1.addObserver((obj, arg) -> System.out.println(arg));
p1.setPrice(1.95);
p1.setName("Milk");
p1.setName("Banana");
p1.setPrice(0.95);
}
}
Yes thats what I thought of first, but I am supposed to do it with 2 observers. I have absolutely no idea how to solve that..
I am a java beginner and I am trying to get used to objects. Is there anyway that I can print out the value of a constructor in main? How can I print out the value's Kevin,20? Thanks
public class MainConstructor {
public static void main(String[] args) {
ConstructorClass emp1 = new ConstructorClass("Kevin", 20);
}
}
//Constructor Class
public class ConstructorClass {
private String name;
private int number;
public ConstructorClass(String name, int number) {
this.name = name;
this.number = number;
System.out.println("called");
}
}
Add a toString() method to ConstructorClass:
public String toString() {
return name + "," + number;
}
Then call this from main:
public static void main(String[] args) {
ConstructorClass emp1 = new ConstructorClass("Kevin",20);
System.out.println(emp1.toString());
}
Try using toString() in your class
public String toString() {
return this.name + "," + this.number;
}
and in your main just do emp1.toString(); to print it to your console
Constructor is basically just another method (but for the love of what is holy, never say that during interview or even to your professor) so there is nothing wrong with doing this:
public class ConstructorClass {
private String name;
private int number;
public ConstructorClass(String name, int number) {
this.name = name;
this.number = number;
System.out.println(name+" "+number);
}
}
But this solution is really ugly and kind of "hotfixy". Better solution would be to have constructor to only get the values and have separate method to print what you want:
public ConstructorClass(String name, int number) {
this.name = name;
this.number = number;
}
void printNameAndNumber() {
System.out.println(name+" "+number);
}
And use the class like this in your main
ConstructorClass c = new ConstructorClass("John",85)
c.printNameAndNumber();
Also some people like to handle this by going through hoops and loops and overriding ToString, but that is being too overzealous and there is really no benefit in your case (or any other primitive case).
public ConstructorClass(String name, int number) {
this.name = name;
this.number = number;
System.out.println(name + "," + number);
}
If you want to properly print out those values, you should have getter methods set in your methods
Example below
public String getName(){
return name;
}
public int getNumber(){
return number;
}
Then to print those values, you should then use methods toString() and method print() to display your values
Example
public String toString(){
return getName() + " " + getNumber();
}
public void print(){
System.out.println(toString());
}
Then in the class with the main method, you call your print method for that specific class
Example
ConstructorClass emp1 = new ConstructorClass("Kevin",20);
emp1.print();
Hope this helped, Enjoy :)
Now, here' the problem :
How to add exceptions so that if my value is negative it would return an error.
here's my current code.
public class Account {
String name;
double balance;
public Account()
{
super();
this.name = null;
this.balance = 0;
}
public Account(String n, double b){
name = n;
balance = b;
}
}
did I do things right? so far?
edited to shorten.
1 . Create new Exception class like NegativeBalanceException
2 . Validate balance from the place where you are calling Account(String n, double b). If its -ve then throw NegativeBalanceException and right a catch block to handle it
In my opinion, this is what the exercise wants you to do:
public class Account {
/*
* If you know about private members, declare them private.
* Probably you should because the exercise asks for getter and setter.
*/
/* private */ String name;
/* private */ double balance;
public Account() {
// Useless: Java calls automatically the superclass constructor.
// super();
/*
* These are useless too, because Java initializes the class
* members to 0, false and null.
* However, this is what the exercise is asking you to do.
*/
name = null;
balance = 0;
}
public Account(String name, double balance) {
// take advantage of setters
setName(name);
setBalance(balance);
}
public void setName(String name) { this.name = name; }
public void setBalance(double balance) {
if (balance < 0)
throw new IllegalArgumentException("balance must be non-negative.");
this.balance = balance;
}
public String getName() { return name; }
public double getBalance() { return balance; }
}
You don't need to call super(); in your default constructor since you don't have superclass defined (at least I don't see that it extends something) and this method will call constructor from superclass.
An error points to the word "new" when I try to compile this program. I'm trying to create 2 objects from the carOrder class and I'm havin troubles! I've had this problem with other programs before and I'm not sure why and it's killing me, please help!
import java.text.DecimalFormat;
import java.util.Scanner;
public class CarOrder
private String buyer;
private String carType;
private double cost;
private int quantity;
private boolean taxStatus;
private double discountedCost;
private double taxAmount;
// Default Constructor
public void carOrder()
{
}
// Constructor
public void CarOrder(String buy, String car, double cos, int quan, boolean tax)
{
buyer = buy;
carType = car;
cost = cos;
quantity = quan;
taxStatus = tax;
}
// Sets the company buying cars
public void setBuyer(String buy)
{
buyer = buy;
}
// Sets the car type being purchased
public void setCarType(String car)
{
carType = car;
}
// Sets cost of the cars being purchased
public void setCost(double cos)
{
cost = cos;
}
// Sets the quantity of cars being purchased
public void setQuantity(int quan)
{
quantity = quan;
}
// Sets tax status for the cars
public void setTaxStatus(boolean tax)
{
taxStatus = tax;
}
// Returns name of buyer to user
public String getBuyer()
{
return buyer;
}
// Returns type of car to user
public String getCarType()
{
return carType;
}
// Returns cost to user
public double getCost()
{
return cost;
}
// Returns quantity of cars to user
public int getQuantity()
{
return quantity;
}
// Returns tax status to user
public boolean getTaxStatus()
{
return taxStatus;
}
// Returns discounted cost to user
public double getDiscountedCost()
{
if (quantity > 10)
if (quantity > 20)
discountedCost = cost - cost * .10;
else
discountedCost = cost - cost * .05;
else
discountedCost = cost;
return discountedCost;
}
// Returns tax amount to users
public double getTaxAmount()
{
taxAmount = cost * .0625;
return taxAmount;
}
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
CarOrder speedy = new CarOrder("Speedy Rental", "Mini Cooper", 22150, 15, true);
CarOrder zip = new CarOrder("Zip Car Co.", "Ford Fusion", 27495, 6, true);
System.out.println("Enter first Buyer");
String buyer1 = keyboard.nextLine();
}
}
public void CarOrder(String buy, String car, double cos, int quan, boolean tax)
{
should be
public CarOrder(String buy, String car, double cos, int quan, boolean tax)
{
Constructor's don't have a return type, not even void.
Currently, you have a method named CarOrder in your class as it has a return type as void, which voilates the rules of custructor. If you remove void, then it'd a constructor as it has the same name as your class.
Same applies to your constructor with no-argsaswell.
public void CarOrder()
should be
public CarOrder()
you are missing a "{" right after public class CarOrder ... :)
When you don't declare a constructor, Java provides a default constructor that have no arguments. As you declared CarOrder(String buy, String car, double cos, int quan, boolean tax), the default constructor is not created anymore. You made a method called carOrder, that probably was an attempt to make a constructor with no arguments, but it has two problems:
it has a return type (void) and constructor doesn't have one
the name is different from the class (cardOrder isn't the same as CarOrder, since Java is case sensitive)
If you want to make a new CarOrder() call, just add the following code:
public CarOrder() {
//insert your implementation here
}
A constructor with a return type is treated as a method by the compiler.