I'm new to Java. How do you add String data into an Object "myData" and print out the contents of it in main?
public class myData {
static String[] myArray = new String[] { "Mimi Rudolph", "minirudolph" };
public static String[] cutName(String string) {
return string.split(" ");
}
String[] fullName = cutName(myArray[0]);
String skype = myArray[1];
String github = null;
Object myData = new Object();
public myData(String[] fullName, String skype, String github) {
this.fullName = fullName;
this.skype = skype;
this.github = github;
}
public static void main(String[] args) {
Object myData = new Object();
}
}
#Tai, I think you're missing some concepts in your code.
Once Java is an Object Oriented Programming language, you should avoid using the static in your methods when you want to have a new instance of a class.
To call methods with static, you don't need a new instance of an object (can call it as MyData.cutName, for example.
On the other hand, constructors will be accessed when you create a new instance of your object.
I believe you can get rid of the arrays, but I kept it in your cutName method.
You could have something like this.
public class MyData {
private String fullname;
private String skype;
private String github;
public MyData(String fullname, String skype, String github) {
this.fullname = fullname;
this.skype = skype;
this.github = github;
}
public String getFullname() {
return this.fullname;
}
public String getSkype() {
return this.skype;
}
public String getGithub() {
return this.github;
}
public String[] cutName(String string) {
return string.split(" ");
}
#Override
public String toString() {
return "Fullname: " + this.fullname + "; Skype: " + this.skype + "; Github: " + this.github;
}
public static void main(String[] args) {
MyData myData = new MyData("Mimi Rudolph", "minirudolph_skype", "minirudolph_githnub");
System.out.println("First name: " + myData.cutName(myData.getFullname())[0]);
System.out.println("Last name: " + myData.cutName(myData.getFullname())[1]);
System.out.println(myData);
}
}
The output would be:
First name: Mimi
Last name: Rudolph
Fullname: Mimi Rudolph; Skype: minirudolph_skype; Github: minirudolph_githnub
Having the attributes in your class and setting it from the new instance will help you to have reusability.
Hope it helps.
I think you are looking for something like this:
public class MyData {
private static final String[] myArray = new String[]{"Mimi Rudolph", "minirudolph"};
String[] fullName = cutName(myArray[0]);
String skype = myArray[1];
String github = null;
Object myData = new Object();
private static String[] cutName(String string) {
return string.split(" ");
}
public MyData(String[] fullName, String skype, String github) {
this.fullName = fullName;
this.skype = skype;
this.github = github;
}
public static void main(String[] args) {
MyData myData = new MyData(myArray, "Skype string goes here", "githun string goes here");
System.out.println(myData.fullName);
System.out.println(myData.github);
System.out.println(myData.skype);
}
}
You need to simply create an instance of your class myData as next:
public static void main(String[] args) {
myData myData = new myData(myArray, "skype", "github");
...
}
To print its content you could override the method toString() for example like this:
#Override
public String toString() {
return "myData{" +
"fullName=" + Arrays.toString(fullName) +
", skype='" + skype + '\'' +
", github='" + github + '\'' +
", myData=" + myData +
'}';
}
Then you will be able to print its content using System.out.println(myData).
So the final code would look like this:
public class myData {
...
#Override
public String toString() {
...
}
public static void main(String[] args) {
myData myData = ...
System.out.println(myData);
}
}
Usually you can add string to object by the following simple example:
String a = "abc";
Object b = a;
System.out.println(b);
If you want to assign a complete String array to myData Object, then you need to do the following:
Object[] myData = new Object[myArray.length];
for(int i=0;i<myArray.length;i++){
myData [i] = myArray[i];
System.out.println("MyData Object Array holding strings data: "+myData[i]);
}
In you main method, you need to change object to object of Arrays first:
From - Object myData = new Object();
TO: Object[] myData = new Object[myArray.length];
Related
I'm writing a simple code to show various details about a person. I've used arrays to create name.
When I try to run my code the location/ directory for name comes out as [Ljava.lang.String;#1f32e575.
My code runs results are:
Name
ii
jj
[Ljava.lang.String;#1f32e575 // code to remove
My code:
public static String[] name() {
System.out.println("Name");
n = new String[]{ "ii", "jj" };
for (int i = 0; i < n2.length; i++) {
System.out.println(n[i]);
}
}
Here, is your fixed code:
import java.util.ArrayList;
class Detail {
private String name;
private String nationality;
private static String[] hobby2;
public Detail() {
}
public String getName() {
return name = "A";
}
public String getNationality() {
return nationality = "abc";
}
public void setInfo(String name, String nationality) {
this.name = name;
this.nationality = nationality;
}
public static void setHobbies() {
hobby2 = new String[] { "ii", "jj" };
System.out.println("Hobbies");
for (int i = 0; i < hobby2.length; i++) {
System.out.println("\t" + hobby2[i]);
}
}
public static void setWishes() {
System.out.println("Wishes");
ArrayList<String> allWishes = new ArrayList<String>();
allWishes.add("aa");
allWishes.add("bb");
allWishes.add("cc");
allWishes.add("dd");
for (String i : allWishes) {
System.out.println("\t" + i);
}
}
public void displayDetail() {
DOB d = new DOB();
System.out.println("Name: " + getName());
System.out.println("Nationality: " + getNationality());
System.out.println("Date of birth: " + d.dateString(1, "Jan", 1000));
setHobbies();
setWishes();
}
}
class DOB {
public String dateString(int day, String month, int year) {
String dob = (day + " " + month + ", " + year);
return (dob);
}
}
class Test {
public static void main(String[] args) {
MyInfo my = new MyInfo();
my.displayDetail();
}
}
The very first value you don't want was the object ID, you simply can't return the values of an object. If you want to see the values then you have to override the toString() method.
The second value was visible just because you returned the list. If you were using print() inside your method then there was no need to return it.
Tips: You need to get a better understanding of getter and setter methods because you have messed up the entire concept in your code. Your blank constructor is not needed. Rather, you should initialize all the fields (class variables of Detail class) in the constructor.
Remove System.out.println in displayDetail() method as below,
setHobbies();
setWishes();
I'm trying to add order1 object to orderList in the Customer class, but it's not working. The toString() method returns zero items in the ArrayList. Does anyone have any idea of what else I can try doing instead?
public class Customer {
private ArrayList<Order> orderList;
private int numberOfOrders = 0;
public Customer(String name, Order firstElementInList) {
this(name);
this.orderList.add(0, firstElementInList);
}
public void setNumberOfOrders() {
this.numberOfOrders = orderList.size();
}
public String toString() {
return name + numberOfOrders;
}
}
public class Main {
static Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
Order order1 = new Order( "bob", 1.1 );
Customer bob = new Customer( "Bobby Shmurda ", order1 );
System.out.println(bob.toString());
}
}
A String Object gets added to ArrayList and when toString() is invoked should return the length of the ArrayList.
Because your list is yet to be created as you have not created its object.
Use below code to create your list.
private ArrayList<Order> orderList = new ArrayList<>();
public class Customer {
private List<Order> orderList;
private int numberOfOrders = 0;
public Customer(String name, Order firstElementInList) {
this(name);
if(orderList == null) {
orderList = new ArrayList<Order>();
}
this.orderList.add(0, firstElementInList);
}
public void setNumberOfOrders() {
this.numberOfOrders = orderList.size();
}
public String toString() {
return "The length of the orderList: " + orderList != null ? orderList.size() : 0;
}
}
public class Main {
static Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
Order order1 = new Order( "bob", 1.1 );
Customer bob = new Customer( "Bobby Shmurda ", order1 );
System.out.println(bob.toString());
}
}
I am trying to write a program which sorts name by it's last name, first name when "sort" condition is applied. The input will be provided from command line. I have started this way but have no idea how to make it work.
Input: sort "john main" "rob class" "bob ram"
Output: class,rob main,john ram,bob
public static void main(String[] args)
{
String[] args_name = new String[args.length-1];
System.arraycopy(args, 1, args_name, 0, args.length-1);
if(args[0].equals("sort"))
{
String firstName = name.substring(args_name,name.indexOf(" "));
String lastName = name.substring(name.indexOf(" ")+1);
String slst = lastName + ", " + firstName;
Arrays.sort(slst);
for (String s: slst) System.out.print(s);
}
}
Try using a Comparator to sort your input. I removed your args-related code for the sake of simplicity. You will still need to re-add it properly.
Required Imports
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
The Name
class Name{
public static final String FULL_NAME_DELIMITER = " ";
public static final String PRINT_DELIMITER = ", ";
private String firstName;
private String lastName;
public Name(String firstName, String lastName){
this.firstName = firstName;
this.lastName = lastName;
}
public static String[] getName(String fullName){
return fullName.split(FULL_NAME_DELIMITER);
}
public String getLastName(){
return this.lastName;
}
#Override
public String toString(){
return String.join(PRINT_DELIMITER , this.lastName, this.firstName);
}
public void print(){
System.out.println(this);
}
}
The Comparator
class NameComparator implements Comparator<Name>{
#Override
public int compare(Name a, Name b) {
return a.getLastName().compareTo(b.getLastName()); // ASC: a to b or DESC: b to a
}
}
Usage
public class Main {
// Holds the sorted names
private static List<Name> names = new ArrayList<>();
public static void main(String[] args) {
// The input names
String[] input = new String[]{
"john main",
"rob class",
"bob ram"
};
// Prepare list for sorting
String firstName;
String lastName;
String[] completeName;
for (String fullName : input) {
completeName = Name.getName(fullName);
firstName = completeName[0];
lastName = completeName[1];
names.add(new Name(firstName, lastName));
}
// Actually sort
names.sort(new NameComparator());
// Print
names.forEach(System.out::println);
}
}
EDIT
To use the input from the command line, the args parameter is what you want to use.
Usage with Commandline Input
public class Main {
// Holds the sorted names
private static List<Name> names = new ArrayList<>();
public static void main(String[] args) {
// The method (in case something else than "sort" is desired)
String method = args[0];
// Check for valid method
if(!method.equals("sort")) return;
// The input names
String[] input = Arrays.copyOfRange(args, 1, args.length);
// Prepare list for sorting
String firstName;
String lastName;
String[] completeName;
for (String fullName : input) {
completeName = Name.getName(fullName);
firstName = completeName[0];
lastName = completeName[1];
names.add(new Name(firstName, lastName));
}
// Actually sort
names.sort(new NameComparator());
// Print
names.forEach(System.out::println);
}
}
EDIT 2
To use the first name instead of the last name, simply alter the Comparator.
class NameComparator implements Comparator<Name>{
#Override
public int compare(Name a, Name b) {
return a.getFirstName().compareTo(b.getFirstName()); // ASC: a to b or DESC: b to a
}
}
Of course, you would need to adjust the Name class as well, by adding:
public String getFirstName(){
return this.firstName;
}
if i understand your question well here is my code that solving this problem
public static void shortName(String shortName){
System.out.println("please enter yout name : ");
Scanner scanner = new Scanner(System.in);
String fullName = scanner.nextLine();
if( shortName.equals("sort")){
String [] nameArr = fullName.split(" ");
int lastNameIndex = nameArr.length - 1;
String name = nameArr[0] +" "+ nameArr[lastNameIndex];
System.out.println("welcome : "+name);
}
else {
System.out.println("welcome : "+fullName);
}
}
public static void main(String[] args) {
shortName("sort");
}
I'm very new to Java and have been trying to set-up an ArrayList CustomerList that takes object Customer, where Customer has attributes from class IAddress. When calling the .add method in my main code however, I am given a NullPointerException error, which I assume is being given because my method isn't receiving anything to add to the ArrayList. I thought it was an issue with the attributes being initialised to empty strings, but when editing them to contain some information, the error still occured.
The ArrayList CustomerList
public class CustomerList {
public ArrayList<Customer> Clients;
public CustomerList() {
Clients = new ArrayList<>();
}
public void add(Customer src) {
Clients.add(src);
}
public void remove(Customer src) {
Clients.remove(src);
}
public void Display(JTextArea jClientsTextArea) {
for (int i = 0; i < Clients.size(); i++) {
Clients.get(i).Display(jClientsTextArea);
}
}
}
Receives Customer from this class
public class Customer {
private String FirstName;
private String Surname;
private IAddress HomeAddress;
public String DOB;
public Customer() {
FirstName = "";
Surname = "";
DOB = "01/01/1900";
HomeAddress = new IAddress();
public void Display(javax.swing.JTextArea jAddressTextArea) {
jAddressTextArea.setLineWrap(true);
jAddressTextArea.append("First Name: " + FirstName + "\n");
jAddressTextArea.append("Surname: " + Surname + "\n");
jAddressTextArea.append("DOB:" + DOB + "\n");
jAddressTextArea.append("Street: " + HomeAddress.getStreet() + "\n");
jAddressTextArea.append("House Name: " + HomeAddress.getHouseName() + "\n");
jAddressTextArea.append("House Number: " + HomeAddress.getHouseNo() + "\n");
jAddressTextArea.append("Area: " + HomeAddress.getArea() + "\n");
jAddressTextArea.append("Postcode: " + HomeAddress.getPostCode() + "\n");
jAddressTextArea.append("Town: " + HomeAddress.getTown() + "\n");
jAddressTextArea.append("Country: " + HomeAddress.getCountry() + "\n");
}
public void Edit(String strfirstname, String strsurname, String strDOB, String strStreet, String strHouseName, String strHouseNo, String strHouseArea, String strPostCode, String strTown, String strCountry) {
FirstName = strfirstname;
Surname = strsurname;
DOB = strDOB;
HomeAddress.setStreet(strStreet);
HomeAddress.setHouseName(strHouseName);
HomeAddress.setHouseNo(strHouseNo);
HomeAddress.setArea(strHouseArea);
HomeAddress.setPostCode(strPostCode);
HomeAddress.setTown(strTown);
HomeAddress.setCountry(strCountry);
}
}
Which receives attributes from IAddress
public class IAddress {
private String Name;
private String Street;
private String HouseNo;
private String HouseName;
private String Area;
private String PostCode;
private String Town;
private String Country;
public IAddress() {
Name = "";
Street = "";
HouseNo = "";
HouseName = "";
Area = "";
PostCode = "";
Town = "";
Country = "";
}
public void setName(String strName) {
Name = strName;
}
public void setStreet(String strStreet) {
Street = strStreet;
}
public void setHouseNo(String strHouseNo) {
HouseNo = strHouseNo;
}
public void setHouseName(String strHouseName) {
HouseName = strHouseName;
}
public void setArea(String strArea) {
Area = strArea;
}
public void setPostCode(String strPostCode) {
PostCode = strPostCode;
}
public void setTown(String strTown) {
Town = strTown;
}
public void setCountry(String strCountry) {
Country = strCountry;
}
}
I've been banging my head against this problem for hours and am ready for it to be something stupidly simple. Thank you.
In your code above the only reason why calling myCustomerList.add(...) could throw is that myCustomerList itself is null. This is because the Clients inside it is initialized in the constructor, and never set to null again. The value of src does not matter as well - the call to Clients.add(src) would succeed even if src is null.
You need to make sure that in your main you do initialize your customer list, like this:
CustomerList list = new CustomerList();
Two classes have similar fields, but they don't have superclass. In my code : First and Second classes. I need to write method convertToAnother, what will be return object of class resultClassObject with values of fields from object one.
Both classes have Json annotation. That annotation have vaule of property equals name of class in lowercase (in my code class First have className = "first".
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.io.StringReader
public class Solution {
public static void main(String[] args) throws IOException {
Second s = (Second) convertOneToAnother(new First(), Second.class);
First f = (First) convertOneToAnother(new Second(), First.class);
}
public static Object convertOneToAnother(Object one, Class resultClassObject) throws IOException {
try {
ObjectMapper mapper = new ObjectMapper();
String obj = mapper.writeValueAsString(one);
obj = obj.replace("\"className\":\"" + one.getClass().getSimpleName().toLowerCase() + "\"", "\"className\":\"" + resultClassObject.getSimpleName().toLowerCase() + "\"");
return new ObjectMapper().readValue(new StringReader(obj), resultClassObject);
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
#JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property="className")
#JsonSubTypes(#JsonSubTypes.Type(value=First.class, name="first"))
public static class First {
public int i;
public String name;
}
#JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property="className")
#JsonSubTypes(#JsonSubTypes.Type(value=Second.class, name="second"))
public static class Second {
public int i;
public String name;
}
}
Maybe another decision exist?
The only correct way to do that using jackson is to marshall instance to json and then unmarshall. I would recommend to use convertion on the level of java objects - using Dozer: http://dozer.sourceforge.net
I want to offer such a solution, example for class First:
First first = new First();
first.i = 1;
first.name = "first";
Second s = (Second) convertOneToAnother(first, Second.class);
System.out.println(s.name); // first
ObjectMapper mapper = new ObjectMapper();
// here we disable uses annototions, since by the condition of the
// problem, we have two classes have similar fields
mapper.disable(MapperFeature.USE_ANNOTATIONS);
StringWriter writer = new StringWriter();
mapper.writeValue(writer, one);
//writer.toString() == {"i":1,"name":"first"}
mapper.readValue(writer.toString, resultClassObject);
if we don't use method mapper.disable(), we'll have for writer, such string {"className":"first","i":1,"name":"first"}
You can write code like below for model mapping:
public class ModelConverter {
public static void main(String[] args) throws IOException {
Test1 t1 = new Test1();
ObjectMapper mapper1 = new ObjectMapper();
String jsonString = mapper1.writeValueAsString(t1);
System.out.println(jsonString);
Test2 t2 = mapper1.readValue(jsonString, Test2.class);
System.out.println(t2);
}
}
public class Test1 implements Serializable {
private int i = 10;
private String name = "demo1";
private Test3 test3 = new Test3();
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Test3 getTest3() {
return test3;
}
public void setTest3(Test3 test3) {
this.test3 = test3;
}
#Override
public String toString() {
return "test1 [i=" + i + ", name=" + name + ", Test3=" + test3 + "]";
}
}
public class Test2 implements Serializable {
private int i = 11;
private String name = "demo2";
private Test3 test3;
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Test3 getTest3() {
return test3;
}
public void setTest3(Test3 test3) {
this.test3 = test3;
}
#Override
public String toString() {
return "test2 [i=" + i + ", name=" + name + ", Test3=" + test3 + "]";
}
}
public class Test3 implements Serializable {
private int i = 12;
private String name = "demo3";
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return "test3 [i=" + i + ", name=" + name + "]";
}
}
For this kind of task would be right to use object mappers like Dozer (http://dozer.sourceforge.net/)
You can replace value of className without String manipulations
ObjectReader reader = mapper.reader();
JsonNode node = reader.readTree(writer.toString());
((ObjectNode)node).put("className",resultClassObject.getSimpleName().toLowerCase());
Also if you don't know the name of the field where name of the class is stored, but you know it is in the annotations, you can try and get the first field from JsonNode (in your code you assume that the field name is "className", but what if it is not).
ObjectMapper mapper1 = new ObjectMapper();
Map<String, Object> result = mapper1.convertValue(node, Map.class);
String key1 = result.keySet().toArray()[0].toString();
And now you can replace the value for the key1 field, which should be the field where class name is stored.