import java.util.Scanner;
class IronMan {
private double totalTime = 3.7;
public IronMan() {
System.out.println("First Constructor running");
}
public IronMan() {
System.out.println("Second Constructor running");
}
}
public class Marathon {
public static void main(String[] args) throws InterruptedException {
IronMan person1 = new IronMan();
Scanner scan = new Scanner(System.in);
System.out.println(
"A triathlon is a challenging task. This program will allow you to know which is the perfect course for you.");
Thread.sleep(3000);
System.out.println("What is your age?");
int age = scan.nextInt();
Thread.sleep(1000);
System.out.println("What is your time for one mile, in minutes?(ex: 5.3 or 6.2");
double time = scan.nextDouble();
Thread.sleep(1000);
System.out.println("How much is your budget?");
double money = scan.nextDouble();
System.out.println(money);
if (money <= 100) {
System.out.println("You can't afford entrance!");
} else if (money > 100) {
if (age < 10) {
System.out.println("You don't qualify!");
} else {
if (time > 10) {
System.out.println("You do not qualify");
} else {
System.out.println("Good! you do qualify");
IronMan person2 = new IronMan();
}
}
}
}
}
I am a bit new to the concept of constructors. I was trying to create the constructor IronMan; however, Eclipse gives me an error message under the word IronMan. It says that "Duplicate method IronMan() in type IronMan". I don't understand why it says the method is duplicated, since it is supposed to be a constructor.
You have two constructors with the same signature (both without parameters). This is not allowed, since there's nothing that distinguishes between the two.
When you write IronMan person1 = new IronMan();, you have no way of specifying which of these two constructors should be invoked, so it's not allowed to have both.
Constructors allow you how to create an instance of an object. You can create ironMan IronMan ironMan = new IronMan() without set ironMan name and age, IronMan ironMan = new IronMan("Brad") this means your ironMan name is brad. IronMan ironMan = new IronMan("Brad", 29) means your ironman name is Brad and his age is 29. if you delete IronMan() constructor, you will enforce to the developer to enter ironMan name(with IronMan(String name)) or name and age (with IronMan(String name, int age)) while creating an instance of IronMan.
public class IronMan {
private String name;
private int age;
public IronMan() {
}
public IronMan(String name) {
this.name = name;
}
public IronMan(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
Related
I'm trying to do homework for my IT classes and we just started programming a bit. We have 2 classes, Main and Okej. It is just a simple code where the getters and setters have to check if the user input the right number. But the IF statements just do not work.
package okej;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner program = new Scanner(System.in);
System.out.println("Please, type your Name.");
String name = program.nextLine();
System.out.println("Please, type your age.");
int age = program.nextInt();
System.out.println("Please, type your weight.");
double weight = program.nextDouble();
Okej you = new Okej(name, age, weight);
System.out.print(you);
}
}
package okej;
import java.util.Scanner;
public class Okej {
String name = "";
int age = 0;
double weight = 0.0;
public Okej(String name, int age, double weight) {
this.name = name;
this.age = age;
this.weight = weight;
}
public String getName() {
return name;
}
public void setName(String name) {
System.out.println("Okay, your name is " + name + ".");
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
if (age > 18) {
if (age < 99) {
this.age = age;
System.out.println("Okay, your age is " + age + ".");
}
}
else {
System.out.println("You have put an invalid age for this program.");
System.out.println("Setting the number to 20.");
this.age = 20;
}
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
if (weight > 30) {
if (weight < 300) {
this.weight = weight;
System.out.println("Okay, your weight is " + weight + ".");
}
}
else {
System.out.println("You have put an invalid weight for this program.");
System.out.println("Setting the number to 50.");
this.weight = 50;
}
}
#Override
public String toString() {
return "Okay, your name is " + name + ", your age is " + age + ", and you weight "+ weight +".";
}
}
It is not working because logic which validates your inputs are inside setters and you are not calling it. You are creating your object through constructor which doesn't execute any validation. You can do one of following:
move validation codes to static method and call it in constructor to validate before assigning values
use builders with validation code inside
create empty object (with default constructor) and use setters to set values which will trigger your validation
...
I am very new to Java and have searched through previously asked questions which haven't helped my issue...
How do I pass the int variable age, and the String name, from the main class to the Person class?
package engineers;
import java.util.Scanner;
public class Engineers {
public static void main(String[] args) {
// TODO code application logic here
Scanner scan = new Scanner(System.in); //declaration and ssignment of scanner
System.out.println("Enter name: "); //name prompt
String name = scan.next(); //reads name input from user
System.out.println("Enter age: "); //age prompt
int age = scan.nextInt(); //reads age input from user
System.out.println("Pay check amount: ");
double salary = scan.nextDouble();
Person person = new Person();
}
private static class Person {
/**
* A default constructor
*/
public Person() {
}
/**
* method for displaying the computation result
*/
double avgSalary = 40000 * Math.sqrt(Math.exp(0.04295 * age + 0.141) );
public void showData(int age, double pay){
System.out.printf( "%s earns $%4.3f for age %3d.\n", name, (pay*Math.sqrt(age)*.15), age);
}//end method showData
}
}
You should use Person constructor like this:
public Person(int age, String name) {
this.age = age;
this.name = name;
}
And add two fields in your Person class, before your constructor:
private int age;
private String name;
Then I am assuming you need to use this variables inside the person class, in order to do this, you can do something like this:
double avgSalary = 40000 * Math.sqrt(Math.exp(0.04295 * this.age + 0.141) );
To reference your variable:
public void showData(){
System.out.printf( "%s earns $%4.3f for age %3d.\n", this.name, (pay*Math.sqrt(this.age)*.15), this.age);
}//end method showData
Finnaly, you need to instantiate your Person object to use it:
Person p = new Person(name, age);
I would also recommend (since you are learning java), to understand the difference between getters/setters and constructor approach: Setter methods or constructors
You mean something like this?
int age;
String name;
class Person(int age, String name) {
this.age = age;
this.name = name;
}
Or (And)
void setAge(int age) {
this.age = age;
}
void setName(String name) {
this.name = name;
}
You would want to define a constructor with any argument another class may need for the most basic functioning.
A Person istance would be initialized with a name and age (even though It would be better to store a birth date and calculate the age against the current date).
To do this, you'd need the class Person to look like this:
public class Person{
private String name;
private Date birthdate;
//Constructor method
public Person(String n, Date bd){
name=n;
birthdate=bd;
}
//Other methods
}
In the main() method, you would then create a new istance of Person, after getting anything needed, like this:
Person p = new(name, date);
I have a question to keyword this and variables scope in methods.
In general I know how to use this keyword, but got confused when observed the same result for all 3 options below into method balance.
The question is, what is the correct implementation of option and why it treats all the options with the same result.
Does it mean that if there is no local variable in the method balance, this keyword is ignored?
Thanks a lot!
option#1
public int balance(int balance) {
this.age = this.age + balance;
return age;
}
option#2
public int balance(int balance) {
age = age + balance;
return age;
}
option#3
public int balance(int balance) {
age = age + balance;
return this.age;
}
Code
package com;
public class Elephant {
private String name;
private int age;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setAge(int age) {
if (age > 0) {
this.age = age;
}
}
public int balance(int balance) {
age = age + balance;
return age;
}
public int getAge() {
return age;
}
public Elephant(String name, int age) {
this.name = name;
if (age > 0) {
this.age = age;
}
}
}
package com;
import java.util.Scanner;
public class MainClass {
public static void main(String arg[]) {
Elephant e1 = new Elephant("Elephant1: ", 7);
System.out.printf("Elephant name: %s age: %s \n", e1.getName(), e1.getAge());
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
e1.balance(i);
System.out.printf("Entered deposit for e1: %d \n", i);
System.out.printf("Balance for e1: %s", e1.getAge());
}
}
Result for all 3 options is the same:
Elephant name: Elephant1: age: 7
11
Entered deposit for e1: 11
Balance for e1: 18
Apart from situations when you need to pass or store a reference to the object from inside its instance method, you need keyword this when resolving an unqualified name requires applying disambiguation rules.
For example, this code needs it:
public void setAge(int age) {
if (age > 0) {
this.age = age;
}
}
Identifier age could refer to the member field age or the parameter age. The compiler applies the rule that parameters and local variables "shadow" fields with identical names to remove ambiguity. That is why you must prefix age with this in the assignment; otherwise, the field wouldn't be assigned.
Your balance method, on the other hand, does not need keyword this at all, because it has no ambiguous name resolutions.
In Java, this is always a reference to the current object. Object properties and methods of the current object can be accessed without explicitly mentioning this. Which one you want to use (with or without mentioning this), is often merely a matter of clarity and coding style guides.
Also see:
What is the accepted style for using the this keyword in Java?
When should I use “this” in a class?
Using the this Keyword (Oracle Java Doc)
I want to change the default constructor (person1) from public to private and then ask the user to input the information instead of the given values.
I have two different classes - Person; which is encapsulated and then PersonTest which tests the information.
class Person {
// Data Members
private String name; // The name of this person
private int age; // The age of this person
private char gender; // The gender of this person
// Default constructor
public Person() {
name = "Not Given";
age = 0;
gender = 'U';
}
// Constructs a new Person with passed name, age, and gender parameters.
public Person(String personName, int personAge, char personGender) {
name = personName;
age = personAge;
gender = personGender;
}
// Returns the age of this person.
public int getAge( ) {
return age;
}
// Returns the gender of this person.
public char getGender( ) {
return gender;
}
// Returns the name of this person.
public String getName( ) {
return name;
}
// Sets the age of this person.
public void setAge( int personAge ) {
age = personAge;
}
// Sets the gender of this person.
public void setGender( char personGender ) {
gender = personGender;
}
// Sets the name of this person.
public void setName( String personName ) {
name = personName;
}
}
import java.util.Scanner;
public class PersonTest {
// Main method
public static void main(String[] args){
// Create first instance of Person class to test the default constructor.
Person person1 = new Person();
// Create a new instance of the Person class.
Person person2 = new Person();
Scanner input = new Scanner(System.in);
// Get the values from user for first instance of Person class.
System.out.println("Person 2 Name: ");
person2.setName(input.nextLine());
System.out.println("Person 2 Age: ");
person2.setAge(input.nextInt());
System.out.println("Person 2 Gender: ");
person2.setGender(input.next().charAt(0));
// Print out the information.
System.out.println("Person 1 Name = " + person1.getName());
System.out.println("Person 1 Age = " + person1.getAge());
System.out.println("Person 1 Gender = " + person1.getGender());
System.out.println("");
System.out.println("Person 2 Name = " + person2.getName());
System.out.println("Person 2 Age = " + person2.getAge());
System.out.println("Person 2 Gender = " + person2.getGender());
System.out.println("");
}
}
One of the main purposes of constructor to be accessible from "outside", so that external classes can instantiate and use your class. You should not make constructor private. It will not be accessible, so main purposes of it will be violated!
If you do not want a default-constructor, simply do not specify one. As soon as you write at least one constructor with paramters, Java does not provide a default-constructor unless you wirte one.
Example:
public class AClass
{
int value = 0;
}
public class BClass
{
int value;
public BClass()
{
value = 0;
}
public BClass(int value)
{
this.value = value;
}
}
This classes have default-constructors and you can write
AClass a = new AClass();
BClass b = new BClass();
to get new instances of this classes.
public class CClass
{
int value;
public CClass(int value)
{
this.value = value;
}
}
This class does not have a default-constructor, since at least one other constructor is specified and no default-constructor is written. Thus
CClass c = new CClass();
will result in a syntax-error.
I've searched, but didn't understand how to incorporate previous answers with my own code. I have an assigment to create a draft of a program for the schools "bank/scholarship"-system. Here we need to create a lot of different methods, that should be called instead of just doing the change directly.
The thing is, I keep getting the error-message in the topic along with a few others, and I don't know how to fix it. I would really appreciate if someone could explain for me how and why to change one of my methods, then I assume I will be able to rewrite all the others myself. Here is my code so far:
class Address
public class Address {
public String street, zip, post;
public Address (String street, String zip, String post) {
this.street = street;
this.zip = zip;
this.post = post;
}
// these are setters (mutators)
public void setStreet (String street) {
this.street = street; }
public void setZip (String zip) {
this.zip = zip; }
public void setPost (String post) {
this.post = post; }
// these are getters
public String getStreet () {
return this.street; }
public String getZip () {
return zip; }
public String getPost () {
return post; }
// methods
//public Address Change(Address newAddress) {
//return newAddress;
//}
// output
public String toString() {
return (street + ", " + zip + ", "+ post); }
}
class Customer
import java.text.DecimalFormat;
public class Customer {
DecimalFormat twoD = new DecimalFormat("0.00");
Address address = new Address("Vik ", "6393 ", "Tomrefjord");
public String name, campus, newCampus, newAddress;
public double loan, increase,decrease,regMaster;
public boolean finished;
public Customer (String name,Address address, String campus, double loan, boolean finished) {
this.name = name;
this.campus = campus;
this.loan = loan;
this.address = address;
this.finished = finished;
}
// these are setters
public void setName (String name) {
this.name = name; }
public void setCampus (String campus) {
this.campus = campus; }
public void setLoan (double loan) {
this.loan = loan; }
public void setFinished (boolean finished) {
this.finished = finished; }
// these are getters
public String getName () {
return name; }
public String getCampus () {
return campus; }
public double getLoan () {
return loan; }
// methods
public void RegMaster () {
this.loan = loan * 0.90;}
//public void changeAddress (Address newAddress) {
//Address.Change(newAddress); }
public double decreaseLoan (double currentBalance, double decrease) {
currentBalance = currentBalance - decrease;
return currentBalance; }
public double getNewLoan (double currentBalance, double newLoan) {
newLoan = currentBalance + newLoan;
return newLoan; }
public String getNewCampus (String newCampus) {
campus = newCampus;
return campus; }
public static boolean Ended () {
return true; }
// output
public String toString() {
return (name + "\t\n" + address + "\t\n" + campus + "\t\n" + twoD.format(loan) + "\t\n" + finished); }
}
class TestCustomer
import java.util.Scanner;
public class TestCustomer {
public static void main (String[] args) {
String student, school, answer, street, zip, post;
double balance, master;
boolean finished = false;
double done = 0; //this is for the loop
Scanner scan = new Scanner(System.in);
// a new student receives a loan
System.out.println("Write your name");
student = scan.nextLine();
System.out.println("Enter your street name and number");
street = scan.nextLine();
System.out.println("What is your zip code?");
zip = scan.nextLine();
System.out.println("What is your post area?");
post = scan.nextLine();
System.out.println("Where do you study?");
school = scan.nextLine();
System.out.println("Input your current loan");
balance = scan.nextDouble();
Address residence = new Address(street, zip, post);
Customer customer = new Customer(student, residence, school, balance, finished);
while(done < 1) { //the variable done will have the value 0 until you are finished.
// change address
System.out.println("Do you wish to change your address? (yes/no)");
answer = scan.nextLine();
if (answer.equalsIgnoreCase("yes")) { //this made it case-insensitive, and now it is not skipping anymore...
System.out.println("Write your street name and house number");
street = scan.nextLine();
System.out.println("Write your zip code");
zip = scan.nextLine();
System.out.println("Write your post area");
post = scan.nextLine();
//Address newAddress = new Address(street, zip, post);
//residence = Customer.changeAddress(newAddress);
}
// increase the loan
System.out.println("Do you want to increase your loan? (yes/no)");
answer = scan.nextLine();
if (answer.equalsIgnoreCase("yes")) {
System.out.println("How much do you need?");
double increaseLoan = scan.nextDouble();
//customer.balance = getNewLoan(customer.balance, moreLoan);
}
// decrease the loan
System.out.println("Do you want to make a downpayment on your loan?");
answer = scan.nextLine();
if (answer.equalsIgnoreCase("yes")) {
System.out.println("How much do you intend to pay?");
double downpayment = scan.nextDouble();
//customer.balance = decreaseLoan(customer.balance, downpayment);
}
// change school
System.out.println("Do you study at the same school? (yes/no");
answer = scan.nextLine();
if (answer.equalsIgnoreCase("no")) {
System.out.println("Write the name of the new school");
school = scan.nextLine(); }
//school.getNewCampus(customer.campus);
// master check
System.out.println("Have you finished your master? (yes/no)");
answer = scan.nextLine();
if (answer.equalsIgnoreCase("yes")) {
customer.finished = Customer.Ended() ; //this will set finished to true, using the method like intended
//customer.balance = Customer.RegMaster(); // dont know how to invoke it... me neither -_-
}
System.out.println("Are you done? yes/no");
answer = scan.nextLine();
if (answer.equalsIgnoreCase("yes")) {
done = 1; } // this adds 1 to the variable done, thus ending the loop.
}
// output
System.out.println("");
System.out.println("The data we have so far is:");
System.out.println(customer);
}}
Here are all three of my classes. Some of the functions are commented away, others are just not working properly (the code is also a little extra messy, I was changing back and forth to try to get it working yesterday). Any help will be appreciated! :)
Okay, from you comment then your problem comes from the (helpfully) commented out lines
//public void changeAddress (Address newAddress) {
//Address.Change(newAddress); }
This is because your Customer done not "have an" Address, you need an address instance and not a String:
private Address address;
public Customer (final Address address) {
this.address = address;
}
I have redacted other variables for clarity. Incidentally I would use a builder pattern rathen than one enormous constructor.
Now that you have an Address in your Customer:
public void changeAddress (Some parameters to change) {
address.setStuff();
}
I would recommend that you read this link about the difference between static and instance variables.