I don't know is it possible or worst idea ever lol;
however i'm trying to write constructor for my model class which uses String array and automatically bind parameters from it :)
Thank you for wasting your gold time on my poor question :D
here is example:
edited: code and my point is, i create object of this class just giving String[] to constructor .... :(
//Like ---->>>>
public class MemberEducation{
String name;
String surname;
String address;
//empty constructor
public MemberEducation(){
}
//it's for parameters
public MemberEducation(String[] a){
int i=0;
for(String val:a){
my_parameters[i]=a;// my parameters mean surname, name, and address
i++;
}
}
// it's my solution now i'm using, create new object with empty constructor
then set all parameter with String array
public void setAll(String[] a){
this.surname=a[0];
this.name=a[1];
this.address=a[2];
}
Problem
You were assigning String Array where it is expecting a String,Thats where it went wrong.I think you are looking for this
Solution
public class MemberEducation{
String[] arr = new String[10];// just taking size 10 for test
public MemberEducation(String[] a) {
int i = 0;
for (String val : a) {
arr[i++] = val;// arr is an string array
}
}
public static void main(String args[]) {
new MemberEducation(args);
}
}
Related
I'm really new to Java and programming in general (~3 weeks of experience) so sorry if this question is obvious for you guys. I tried searching for answers here but couldn't find any that fit my specific problem. And yeah it's for school, I'm not trying to hide it.
Here I'm supposed to write an object method that returns the string contained in the object oj, in reverse. I do know how to print a string in reverse, but I don't know how I should call the object since the method isn't supposed to have any parameters.
import java.util.Random;
public class Oma{
public static void main(String[] args){
final Random r = new Random();
final String[] v = "sininen punainen keltainen musta harmaa valkoinen purppura oranssi ruskea".split(" ");
final String[] e = "etana koira kissa possu sika marsu mursu hamsteri koala kenguru papukaija".split(" ");
OmaMerkkijono oj = new OmaMerkkijono(v[r.nextInt(v.length)] + " " + e[r.nextInt(e.length)]);
String reve = oj.printreverse();
System.out.println(reve);
}
}
class OmaMerkkijono{
private String jono;
public OmaMerkkijono(String jono){
this.jono=jono;
}
public String printreverse(){
//so here is my problem, i tried calling the object in different ways
//but none of them worked
return reversedstringthatdoesnotexist;
}
}
You just need to add this to your "printreverse" method :
new StringBuilder(this.jono).reverse().toString()
With this, when you call the method with the object "oj":
String reve = oj.printreverse();
After the previous line, "reve" must contain the value of the String reversed.
Olet hyvä, moi moi!
To revers a String use StringBuilder and reverse()
public String printreverse(){
return new StringBuilder(jono).reverse().toString();
}
To access private attributes from outside the class you use what are called accessors and mutators, aka getters and setters.
You just need a basic getter that also reverses the string.
public class MyObject {
private String objectName;
MyObject(String objectName) {
this.objectName = objectName;
}
public String getObjectName() {
return objectName; // returns objectName in order
}
public String getReversedObjectName() {
return new StringBuilder(objectName).reverse().toString();
}
public static void main(String[] args) {
MyObject teslaRoadster = new MyObject("Telsa Roadster");
System.out.println(teslaRoadster.getObjectName());
System.out.println(teslaRoadster.getReversedObjectName());
}
}
Output:
Telsa Roadster
retsdaoR asleT
I need a bit of help here. so i have this. I was basically wondering when you create an array of object of a parent class, then change that object to a child class, can I access the methods of that child class and if not why. thanks for any help.
public class Racer {
private String name;
private int position;
// Constructor
public Racer()
{}
public Racer(String name)
{
this.name = name;
position = 0;
}
public String getName()
{
return name;
}
public int getPosition()
{
return position;
}
public void setPosition(int n)
{
position = n;
}
public void setName(String n){
this.name=n;
}
}
the child class
public class Spartiates extends Racer{
private int energy;
public Spartiates(){
super();
}
public Spartiates(String name){
setName(name);
setPosition(20);
energy=100;
}
public void setEnergy(int energy){
this.energy=energy;
}
public int getEnergy(){
return energy;
}
}
main class
public class demo{
public static void main(String[] args){
Racer [] player = new player[3];
for(int i=0; i<player.length; i++){
player[i] = new Spartiates();
}
System.out.println(player[1].getEnergy());
}
so here the problem the getEnergy method doesn't work so I was wondering why. If anybody can help it would be very much appreciated. thanks
This is discussed here:
Is it possible to call subclasses' methods on a superclass object?
Along with all the reasons why doing something like this is probably never a good idea :).
You'll have to cast it to an instance of the subclass. If you plan on having a mixed array of object instances you'd need to first check the type:
System.out.println(((Racer)player[1]).getEnergy());
You need either define the function in the superclass or cast the object to the subclass.
If you intend the array to hold ONLY elements of the subclass Spartiates, then declare it as such.
Otherwise, if it needs to hold objects of both type, there only way to do this is to check with instanceof.
if (player[1] instanceof Spartiates)
System.out.println(((Spartiates)player[1]).getEnergy());
else
// handle other types
The reason energy is 0 is because you are calling your empty (no arg) constructor:
player[i] = new Spartiates();
which does not initialize the energy variable (so it will be 0 by default). You only set the variable to 100 in the constructor which takes in a String, namely here:
public Spartiates(String name){
setName(name);
setPosition(20);
energy=100;
}
So either call that constructor in the for loop with some string as an argument, or call your setEnergy() setter with some value after creating the object with the empty constructor.
Also, this is wrong:
Racer [] player = new player[3];
It should read:
Racer [] player = new Racer[3];
or:
Racer [] player = new Spartiates[3];
I wanted to create array of an objects. There will be many user objects and I want to keep these user objects in an array. I have a class called Data. I tried and searched a lot but couldn't find the solution. When user enters a new name the names of all objects changes with the given name, and at last when i print all the names it prints the last entered name for several times. Here is my code, it will be much helpful you to understand:
testClass.java
public class testClass {
public static void main(String[] args) {
mainScreen();
}
public static void mainScreen(){
Scanner scan = new Scanner(System.in);
System.out.println("1) Add a new user:");
int choice = scan.nextInt();
switch(choice){
case 1:
System.out.println("Enter name:");
String name = scan.next();
Data.users[Data.count] = new Data(name);
mainScreen();
break;
case 2:
for(int i =0; i<=Data.count; i++){
System.out.println(Data.users[i].name);
}
break;
}
}
}
Data.java
public class Data {
public static Data[] users = new Data[600];
public static String name;
public static int count = 0;
public Data(String name) {
users[count].name = name;
count++;
}
}
I want that every object will have unique name, id, phone number, etc.. Does anybody have a suggestion for me?
Because name is static field of your Data class like count and users.
Remove static modifier from name field.
One solution is to remove the static modifier from name field in Data:
public static Data[] users = new Data[600];
public static int count = 0;
public String name;
public Data(String name) {
this.name = name;
Data.count++;
}
Also modify your for loop, because you'll get a NullPointerException, remove equals from the condition:
for(int i =0; i<Data.count; i++){
First you need to correct your Object structure
you have defined a class Data which contains a static array of Data Class itself
I prefer to have data class as:
class Data {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
create a array of Data class in your testClass
create new Data Object for each input and assign the name to the newly created Object using setName
maintain the count variable in testClass. Increment it each time when you get a new input and use count variable to assign newly created Object to the Data array
I have two methods, the first one creates a string, then I want to use that string in the second method.
When I researched this, I came across the option of creating the string outside of the methods, however, this will not work in my case as the first method changes the string in a couple of ways and I need the final product in the second method.
Code:
import java.util.Random;
import java.util.Scanner;
public class yaya {
public static void main(String[] args) {
System.out.println("Enter a word:");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
Random ran = new Random();
int ranNum = ran.nextInt(10);
input = input + ranNum;
}
public void change(String[] args) {
//more string things here
}
}
Create an instance variable:
public class MyClass {
private String str;
public void method1() {
// change str by assigning a new value to it
}
public void method2() {
// the changed value of str is available here
}
}
You need to return the modified string from the first method and pass it into the second. Suppose the first method replaces all instances or 'r' with 't' in the string (for example):
public class Program
{
public static String FirstMethod(String input)
{
String newString = input.replace('r', 't');
return newString;
}
public static String SecondMethod(String input)
{
// Do something
}
public static void main(String args[])
{
String test = "Replace some characters!";
test = FirstMethod(test);
test = SecondMethod(test);
}
}
Here, we pass the string into the first method, which gives us back (returns) the modified string. We update the value of the initial string with this new value and then pass that into the second method.
If the string is strongly tied to the object in question and needs to be passed around and updated a lot within the context of a given object, it makes more sense to make it an instance variable as Bohemian describes.
Pass the modified string in the second method as an argument.
create a static variable used the same variable in both the method.
public class MyClass {
public string method1(String inputStr) {
inputStr += " AND I am sooo cool";
return inputStr;
}
public void method2(String inputStr) {
System.out.println(inputStr);
}
public static void main(String[] args){
String firstStr = "I love return";
String manipulatedStr = method1(firstStr);
method2(manipulatedStr);
}
}
Since you mentioned that both methods should be able to be called independently, you should try something like this:
public class Strings {
public static String firstMethod() {
String myString = ""; //Manipulate the string however you want
return myString;
}
public static String secondMethod() {
String myStringWhichImGettingFromMyFirstMethod = firstMethod();
//Run whatever operations you want here and afterwards...
return myStringWhichImGettingFromMyFirstMethod;
}
}
Because both of these methods are static, you can call them in main() by their names without creating an object. Btw, can you be more specific about what you're trying to do?
I have two classes. In the first one, I used the Scanner to retrieve the user's name and then store it in a String called name. Then say, I start a new class, and want to print that came out, how do I go about it. So I just wrote up this code as an example, so you can get an idea of what I'm trying to ask. I'll post both classes.
import java.util.Scanner;
public class One {
public static void main(String[] args) {
String name;
String start;
Scanner input = new Scanner(System.in);
System.out.println("Hello, what is your name?");
name = input.nextLine();
System.out.println("Hello "+name+", welcome! To ocntinue, please hit any key.");
start = input.nextLine();
if(start != null){
Two object = new Two();
}
}
}
Second class.
public class Two {
public Two() {
System.out.println("Ok "+One.name+", lets start!");
}
}
So, you will probably be doing something like this: -
class One
{
private String name = "bob";
public String getName()
{
return name;
}
public static void main(String [] args)
{
One one = new One();
Two two = new Two(one);
// You could also just pass an r-value to Two, as in, Two(new One()) if you
// never require 'one' again
}
}
class Two
{
public Two(One one)
{
System.out.println("Ok " + one.getName() + ", lets start!");
}
}
What is going on?
Creating two classes in your main entry point method.
Passing the instance of One to the constructor of Two
Two then calls getName()
You could, as others have suggested, pass a string as the constructor; alternatively, you could do both if required as Java supports overloading methods see
Recommendations
Take a look at http://docs.oracle.com/javase/tutorial/java/javaOO/methods.html for overriding methods so that you may see how to pass both a string and an object reference by value. What you are doing right now is passing the object reference of one by value. It may not be needed or you may want to provide restrictions using an interface, see http://docs.oracle.com/javase/tutorial/java/concepts/interface.html
Use the constructor to pass the values
public class Two {
private String value;
public Two(String a){
this.value=a;
System.out.println("Ok "+value+", lets start!");
}
//getter and setters
}
Then while creating the instance use that constructor
Two object = new Two(name);
pass your value to the Two class constructor.
if(start != null){
Two object = new Two(start );
}
and
public Two(String s){
System.out.println("Ok "+s+", lets start!");
}
To make your code compile, move the String name variable into a static field:
public class One {
public static String name;
public static void main(String[] args){
// Note: The "name" variable is no longer defined here
String start; // etc
// rest of code the same
}
}
I'm not going to tell you this is good code design, but it does what you asked.
You will also do like this
public class One {
private String name;
public void setName(String name){
this.name = name;
}
public String getName(){
retrun this.name;
}
public static void main(String[] args){
String name;
String start;
Scanner input = new Scanner(System.in);
System.out.println("Hello, what is your name?");
name = input.nextLine();
System.out.println("Hello "+name+", welcome! To ocntinue, please hit any key.");
start = input.nextLine();
if(start != null){
Two two = new Two();
two.printName(this);
}
}
class Two{
public void printName(One one){
System.out.println("" + one.getName() );
}
}