Issue with String as parameter - java

First of, sorry for my bad English.
I'm pretty new to java and we are learning it in School at the moment. In my Program I want to use String as a parameter but when I try to build an object I can't type anything in for the Parameter. Here's my bytecode:
public String gender;
public Waage(String pGender)
{
gender = pGender;
}
As you can see I want the user to type in their gender, the variable gender will then be set to be the same as the parameter pGender. If I want to create an object with Bluej now, I just get the error that it cannot find symbol - variable x (for example female). Could someone please explain to me what I'm doing wrong or how to fix it? Thank you!
Also this is my first question here so if I did any big mistakes just tell me.
Edit:
My full code:
public class Waage
{
public String gender;
public Waage(String pGender)
{
gender = pGender;
}
public void changeGender(String pGender)
{
gender = pGender;
}
public String giveGender()
{
return gender;
}
}
And the Error Message is If I would type in female :
Error: cannot find symbol - variable female

In the constructor,
public Waage(pGender)
{
gender = pGender;
}
pGender is local variable of the constructor, that is taking String argument, and it is missing datatype. Edit that as below and it'll compile.
public Waage(String pGender)
{
gender = pGender;
}

One of the cause is not passing string in double quotes in constructor call.
You must be creating your class's object like this:
Waage waage = new Waage(female);
Either use :
Waage waage = new Waage("female");
or:
String gender = "female";
Waage waage = new Waage(gender);

Related

Trying to learn about getter method and while doing so i am getting error with below java code. can some one correct it and explain

class Source {
public static void main(String[] args) {
// Write code here
Person p1 = new Person(name:"Ankit");
}
public static void printName(Person p){
System.out.println("name is :"+ p.getName());
}
}
class Person {
private String name;
public Person(String name) {
this.name = name;
}
public String getName(){
return this.name;
}
// Declare a getter method here
}
In the above code I'm getting error for line " Person p1 = new Person(name:"Ankit"); " can someone explain why
To the constructor in Person class you can only pass String parameters. Below code, name: is unknown symbol. That is why it gives an error.
Person p1 = new Person(name:"Ankit");
You have to change your code as below.
Person p1 = new Person("Ankit");
Person p1 = new Person("Ankit");
The parameter you have declared for the Person constructor is a String. When you call the constructor you are passing name which is not part of how you declared a Person is constructed. The argument you pass when you say new Person(//some argument) is copied into the parameter it corresponds to in the constructor declaration and used as you have specified there. Since you are assigning a value into a variable of type String you must only pass a String. You may do this by:
1. Passing a String literal as the argument:
2. Passing another variable of type String.
3. Instantiating a new String object in the argument
// First way
Person p1 = new Person("Ankit");
// Second way
String s = "Ankit";
Person p1 = new Person(s);
// Third way
Person p1 = new Person(new String("Ankit"));
In the above code I'm getting error for line " Person p1 = new Person(name:"Ankit"); " can someone explain why
It is because your syntax to invoke the constructor is incorrect. There is no need to indicate the parameter.
Just do it as:
Person p1 = new Person("Ankit");
In case you were wondering how does Java knows which parameter you were referring to when you don't indicate the parameter. It follows the order of the parameters when you create the constructor (same for method invocation):
Let say you have name and nick name (both are String):
//Constructor
//1st param: name
//2nd param: nickName
public Person(String name, String nickName){
this.name = name;
this.nickName = nickName;
}
//Creating Person object
Person p = new Person("Rowan Atkinson", "Bean"); //name:Rowan Atkinson, nickName:Bean
^ ^
// 1st param 2nd param

How to convert a string that a user typed in a dialog box (JOptionPane) into a enum? [duplicate]

This question already has answers here:
How to get an enum value from a string value in Java
(32 answers)
Closed 5 years ago.
I have a enum for gender.
public enum Gender {
Male("M"), Female("F");
private String value;
Gender(String value){
this.value = value;
}
public String getValue() {
return value;
}
}
This enum is a constructor of my class.
class People {
private String name;
private int id;
private int age;
private Gender x;
}
Then I'm trying to create a new object of this class from the user, a user type a name, id, age and gender. I'm using the dialog box JOptionPane.
The line I'm getting a error is this one.
public class AppPeople {
public static void main(String[] args) {
Gender gender1; //I tried declaring String gender1
//To get the answer/input below, but didn't work.
gender1 = JOptionPane.showInputDialog(null, "Type Male or Female");
People p1 = new People(name, id, age, Gender1);
}
}
All the others fields are working from the dialog box, name, id and age. This one that is a enum isn't working. I had to declare id and age string to use it on dialog box, so the answer typed I got into strings variables and converted it to integer, to match the constructor of the class. I tried declaring a new string to get the input from dialog box and convert it to enum but still didn't work. The only field left is this one to convert a string to enum. Does anyone know what can I do to fix or maybe a new solution.
You can use
gender1 = Gender.valueOf(JOptionPane.showInputDialog(null, "Type Male or Female").toUpperCase());
just se method of each enum
Gender.valueOf("yourString")

Should I initialize object values?

The question may sound a bit silly, but should an object class look something like this:
class Book {
String title;
int year;
///so on and so forward
}
or should it look like this?
class Book {
String title = "";
int year = 0;
///so on and so forward
}
i understand that actual values should be set by the constructor (or setValue methods), but should the initial values be null, or 0/"" ?
Edit: Im trying to work with the object values as strings (replacing certain characters, etc), which doesnt work if the value is null; i wasnt sure if i should add an "if" clause or simply initialize values to an empty string
It should look something like this:
public class Book {
private String title;
private int year;
}
public Book(String titleIn, int yearIn) {
title = titleIn;
year = yearIn;
}
And the way you should create the object is:
Book harryPotter = new Book("Harry Potter", 2014);

Integer.toString(argument) or toString(argument)

I've written up some code for a Credit card class, pasted below. I have a constructor that takes in the said variables, and am working on some methods to format these variable's into strings such that the end output will be something along the lines of
Number: 1234 5678 9012 3456
Expiration date: 10/14
Account holder: Bob Jones
Is valid: true
(Won't format correctly - I'm unsure how to do it, would be greatful of someone can edit for me :) )
My question is, in the line
String shortYear = Integer.toString(expiryYear).substring(2,4);
Why won't the following work:
toString(argument).substring(2,4)
I would have imagined it wound have worked (expiryYear is essentially declared as an instance variable of type int). I've consulted my book (The official Java Tutorial also found online), and can't seem to find anything. I didn't even know about Integer.toString, a friend told me about that after trying to play with toString(), so it would be even more greatly appreciated if someone could also tell me where I can find these sorts of methods (I don't think they're in my book)
public class CreditCard {
private int expiryMonth;
private int expiryYear;
private String firstName;
private String lastName;
private String ccNumber;
public CreditCard(int expiryMonth, int expiryYear, String firstName, String lastName, String ccNumber) {
this.expiryMonth = expiryMonth;
this.expiryYear = expiryYear;
this.firstName = firstName;
this.lastName = lastName;
this.ccNumber = ccNumber;
}
public String formatExpiryDate() {
String shortYear = Integer.toString(expiryYear).substring(2, 4);
String expiryDate = expiryMonth + "/" + shortYear;
return expiryDate;
}
public static void main(String[] args) {
CreditCard cc1 = new CreditCard(10, 2014, "Bob", "Jones", "1234567890123456");
System.out.print(cc1.formatExpiryDate());
}
}
Try String.valueOf(expiryYear).substring(2,4)

Dynamic variable names in Java so each new object has separate name

How can I do such a thing?
String N = jTextField0.getText();
MyClass (N) = new Myclass();
Is it even possibe?
Or as my question's explains, how can I just make a method to create a new object of my specified class just with a different name each time I call it.
I really searched everywhere with no luck.
Thanks in Advance
P.S.
I wish you guys can excuse me for not being clear enough, Just to say it as it is, I made a textfield to get the name of someone who wants to make an account, and I made a class named "Customer". and a button named "Add". Now I want every time "Add" is clicked, compiler take what is in my textfield and make an object of the class "Customer" named with what it took from the textfield
It was too hard to read it in comments so I updated my question again, so sorry.
I'm stuck so bad. I suppose my problem is that I didn't "understand" what you did and only tried to copy it. This is what I wrote:
private void AddB0MouseClicked(java.awt.event.MouseEvent evt) {
String name = NameT0.getText();
Customer instance = new Customer(Name);
Customer.customers.add(instance);
and this is my Customer class:
public class Customer{
String name;
public Customer(String name){
this.name = name;
}
public String getName(){
return name;
}
static ArrayList<Customer> customers = new ArrayList<Customer>();
Variable names must be determined at compile time, they are not even part of the generated code. So there is no way to do that.
If you want to be able to give your objects names, you can use
Map<String, MyClass> map = new HashMap<>();
Add objects to the map like this (e.g):
map.put(userInput, new MyClass());
and retrieve objects like this:
MyClass mc = map.get(userInput);
I'm not entirely sure what you mean by...
how can I just make a method to create a new object of my specified
class just with a different name each time I call it
...but if I'm interpreting you correctly, I believe what you're trying to do as make MyClass accept a constructor parameter. You can do:
public class MyClass {
private String name;
public MyClass(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
Then to create a new instance of MyClass, do:
String name = jTextField0.getText();
MyClass instance = new MyClass(name);
instance.getName(); // returns the name it was given
EDIT
Since you've added clarifications in the comments since I first answered this question, I thought I would update the answer to portray more of the functionality that you're looking for.
To keep track of the MyClass instances, you can add them to an ArrayList. ArrayList objects can be instantiated as follows:
ArrayList<MyClass> customers = new ArrayList<MyClass>();
Then for each MyClass instance you wish to add, do the following:
customers.add(instance);
Note that the ArrayList should not be reinstantiated for each instance that you wish to add; you should only instantiate the ArrayList once.

Categories

Resources