Java calling value from a method - java

first of all sorry for my english it is not perfect.
I got a little problem (for me a huge problem) in java.
package test;
import java.util.Scanner;
public class adress {
String adress;
String city;
int postcode;
String ergebnis;
public void setadress(String adress)
{
this.adress = adress;
}
public String getadress()
{
return adress;
}
public void setcity(String city)
{
this.city = city;
}
public String getcity()
{
return city;
}
public void setpostcode(int postcode)
{
this.postcode = postcode;
}
public int getpostcode()
{
return postcode;
}
public void output (String adress, String city, int postcode) {
Scanner a = new Scanner (System.in);
System.out.println("How much values?");
int b = a.nextInt();
int [] c = new int [b];
for (int i=0; i<c.length; i++) {
Scanner input = new Scanner (System.in);
System.out.println("Adress?");
String temp = input.nextLine();
setadresse(temp);
Scanner input3 = new Scanner (System.in);
System.out.println("City?");
String temp2 = input3.nextLine();
setcity(temp2);
Scanner input4 = new Scanner (System.in);
System.out.println("Postcode?");
int temp3 = input4.nextInt();
setpostcode(temp3);
this.adress = adress;
this.city = city;
this.postcode = postcode;
System.out.println("Adress: "+adress+"City"+city+"postcode"+postcode);
}
}
}
Now, i want to save the values in a new class in a array
package test;
public class save {
adress [] saver = new adress[10];
public adressenpool (String adress, String city, int postcode){
for(int i =0; i<10;i++)
saver[i] = ????? ; //i have tried several things here, but it will not work. i know it is just a little problem but i can't get it the mistake
}
}
}
How can i get the values from address class an copy it as an array in the saver class?

It looks like you are attempting to put 10 objects of class address in an object of class save, as opposed to just the information within address. This is generally a good idea so I encourage you to continue.
In order to create the address within method adressenpool you need to use its constructor. At present class address only had a default constructor, which creates an effectively empty address. I would add a new constructor that fully creates the object
public class adress {
String adress;
String city;
int postcode;
String ergebnis;
public adress(String adress, String city, int postcode, String ergebnis){
this.adress=address;
this.city=city;
this.postcode=postcode;
this.ergebnis=ergebnis;
}
//you can have several constructors so you can keep the empty constructor if you want to set the elements piece by piece
public adress(){
}
......
other methods as before
}
Having added the constructor you can now make addresses easily
public adressenpool (String adress, String city, int postcode,String ergebnis){
saver[0] = new adress(adress, city, postcode,ergebnis);
}
However, your method adressenpool only contains enough information to create 1 adress. You may wish to set which index to save it at. Or you may want to change from an array to an arraylist so you can just add new adress as you go.
public adressenpool (String adress, String city, int postcode,String ergebnis, int index){
saver[index] = new adress(adress, city, postcode,ergebnis);
}
Notes
Classes always start with an uppercase letter. Objects with
lowercase. So it should be class Save and class Address
For loops (and if statements) without braces are considered a dangerous thing to do. Always include {} with your loops even if it contains a single statement. So
for(int i =0; i<10;i++){
saver[i] new Adress(adress, city, postcode,ergebnis);
}

I think you should be more specific of what you want to do exactly.
Your first class has 4 members (3 String and 1 int) and you want to save the values from address class as an array in the saver class? What do you mean by the last one?
I am guessing you need to fill each address instance in the array you define (saver) by calling the appropriate setters. (You haven't defined setadresse() by the way). This can be done in a loop for example.
Also this is not very straight forward: //i have tried several things here, but it will not work. What have you tried and did not work?
Of course you need a main() function also to run your program.
I hope that helped a bit...

This will solve the issue
package temp;
import java.util.Scanner;
public class adress {
String adress;
String city;
int postcode;
String ergebnis;
public void setadress(String adress)
{
this.adress = adress;
}
public String getadress()
{
return adress;
}
public void setcity(String city)
{
this.city = city;
}
public String getcity()
{
return city;
}
public void setpostcode(int postcode)
{
this.postcode = postcode;
}
public int getpostcode()
{
return postcode;
}
public void setAddress () {
Scanner input = new Scanner (System.in);
System.out.println("Adress?");
String temp = input.nextLine();
setadress(temp);
Scanner input3 = new Scanner (System.in);
System.out.println("City?");
String temp2 = input3.nextLine();
setcity(temp2);
Scanner input4 = new Scanner (System.in);
System.out.println("Postcode?");
int temp3 = input4.nextInt();
setpostcode(temp3);
}
#Override
public String toString() {
// TODO Auto-generated method stub
return "Adress: "+adress+"City"+city+"postcode"+postcode;
}
}
And the second class
package temp;
import java.util.Scanner;
public class save {
adress [] saver;
public save(){
saver = new adress[10];
}
public void adressenpool(){
Scanner a = new Scanner (System.in);
System.out.println("How much values?");
int b = a.nextInt();
adress address1 = null;
for (int i=0; i<b; i++) {
address1 = new adress();
address1.setAddress();
this.saver[i] = address1;
}
}
public static void main(String[] args) {
save saveTemp = new save();
saveTemp.adressenpool();
for(int i=0; i<2; i++){
System.out.println(saveTemp.saver[i].toString());
}
}
}

Related

How can we create an instance for a nested class in array of objects in java?

import java.util.Arrays;
import java.util.Scanner;
public class employee{
public String name;
public class employee_address{
String street_name;
String city;
String zipcode;
String state;
String country;
}
public static void main(String []args){
Scanner user_input = new Scanner(System.in);
int no_of_employees = user_input.nextInt();
employee[] employees_list = new employee[no_of_employees];
for(int i = 0;i < no_of_employees;i++){
employees_list[i].name = user_input.nextLine();
employees_list[I].employee_address = // this is it ?
}
}
}
In the code above I do understand that the employee_address is a class and can't be accessed
directly without an instance being created like in the code, that makes no sense. but how can I create an instance of the employee_address class that is associate with each employee.
like in the code above 'employee_address' is associated with every employee but how can the class 'employee_address' be initialised and how can I set the street_name, city and the rest of the members in the address class. any ideas would be appreciated.
You can't directly create an instance of inner class, the reason because since it is the property of another instance we always need to use it though the instance of parent variable.
Let's say you have a class, which have two propeties:
public class Employee {
public String name;
public EmployeeAddress emAddress;
}
to access emAddress you need to use through the instance of Employee class, for example -
Employee object = new Employee();
EmployeeAddress empAdd = object.new EmployeeAddress();
Full code:
public class Employee {
public String name;
public EmployeeAddress emAddress;
public class EmployeeAddress {
String street_name;
String city;
String zipcode;
String state;
String country;
public String getStreet_name() {
return street_name;
}
public void setStreet_name(String street_name) {
this.street_name = street_name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getZipcode() {
return zipcode;
}
public void setZipcode(String zipcode) {
this.zipcode = zipcode;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
#Override
public String toString() {
return "EmployeeAddress [street_name=" + street_name + ", city=" + city + ", zipcode=" + zipcode
+ ", state=" + state + ", country=" + country + "]";
}
}
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
int no_of_employees = user_input.nextInt(); // let's say no_of_employees = 1
Employee[] employees = new Employee[no_of_employees];
for (int i = 0; i < no_of_employees; i++) {
Employee object = new Employee();
object.setName("Virat Kohli");
EmployeeAddress empAdd = object.new EmployeeAddress();
empAdd.setCity("New Delhi");
empAdd.setCountry("India");
empAdd.setState("Delhi");
empAdd.setStreet_name("Chandni Chalk");
empAdd.setZipcode("741124");
object.setEmAddress(emAddress);
employees[i] = object;
}
System.out.println(employees[0]);
user_input.close();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public EmployeeAddress getEmAddress() {
return emAddress;
}
#Override
public String toString() {
return "Employee [name=" + name + ", emAddress=" + emAddress + "]";
}
public void setEmAddress(EmployeeAddress emAddress) {
this.emAddress = emAddress;
}
}
I have modified your code to sonar standard.
Below code uses Java naming conventions (which your code does not).
Notes after the code.
import java.util.Scanner;
public class Employee {
private String name;
private EmployeeAddress address;
public class EmployeeAddress {
String streetName;
String city;
String zipcode;
String state;
String country;
}
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
int noOfEmployees = userInput.nextInt();
Employee[] employeesList = new Employee[noOfEmployees];
for (int i = 0; i < noOfEmployees; i++) {
employeesList[i] = new Employee();
employeesList[i].name = userInput.nextLine();
EmployeeAddress employeeAddress = employeesList[i].new EmployeeAddress();
employeesList[i].address = employeeAddress;
employeesList[i].address.streetName = userInput.nextLine();
}
}
}
An inner class is a normal class. It is not a member of its enclosing class. If you want class Employee to have an [employee] address, as well as a [employee] name, you need to add another member variable to class Employee whose type is EmployeeAdress.
Employee[] employeesList = new Employee[noOfEmployees];
The above line creates an array but every element in the array is null. Hence you need to first create a Employee object and assign it to an element of the array. Hence the following line in my code, above:
employeesList[i] = new Employee();
Since EmployeeAddress is not a static class, in order to create a new instance, you first need an instance of the enclosing class, i.e. Employee. Hence the following line in the above code.
EmployeeAddress employeeAddress = employeesList[i].new EmployeeAddress();
Since all your code is in class Employee, in method main you can directly access the members of both class Employee and EmployeeAddress. Nonetheless you need to be aware of the different access modifiers in java.
A few hints:
stick to naming conventions: class names in Java start with capital letters
use (class) definitions before using them (collect them at the top if not inconventient)
if you are sure you want to use inner classes, set them static, unless you want them to be entangled in generics.
Usually normal classes in each their own file are a lot more flexible and far easier to use
if you use objects that only carry public data, try to use final keyword and initialize them ASAP
use proper objects first, and after finishing them assign them to arrays. avan better would be the use of ArrayList and the like
if Employee contains EmployeeAddress, it should initialize it if conventient. so an object is always responsible for its own stuff
Use try/resrouce/catch
scanner.nextInt() can be problematic with newline/line breaks. For user input better readLine() and parse input
Code:
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Scanner;
public class Employee {
static public class EmployeeAddress {
public final String street_name;
public final String city;
public final String zipcode;
public final String state;
public final String country;
public EmployeeAddress(final Scanner pScanner, final PrintStream pOutPS) {
street_name = readLine(pScanner, pOutPS, "Please enter Street Name:");
city = readLine(pScanner, pOutPS, "Please enter City Name:");
zipcode = readLine(pScanner, pOutPS, "Please enter Zip Code:");
state = readLine(pScanner, pOutPS, "Please enter State:");
country = readLine(pScanner, pOutPS, "Please enter Country:");
}
}
static public String readLine(final Scanner pScanner, final PrintStream pOutPS, final String pPrompt) {
pOutPS.print(pPrompt);
final String value = pScanner.nextLine();
pOutPS.println();
return value;
}
static public int readInt(final Scanner pScanner, final PrintStream pOutPS, final String pPrompt) {
return Integer.parseInt(readLine(pScanner, pOutPS, pPrompt));
}
public final String name;
public final EmployeeAddress address;
public Employee(final Scanner pScanner, final PrintStream pOutPS) {
name = readLine(pScanner, pOutPS, "Please enter Employee Name: ");
System.out.println("Name: " + name);
address = new EmployeeAddress(pScanner, pOutPS);
}
public static void main(final String[] args) {
try (final Scanner user_input = new Scanner(System.in);
final PrintStream output = System.out;) {
final int no_of_employees = readInt(user_input, output, "Please enter number of users: ");
final Employee[] employees_list = new Employee[no_of_employees]; // either this line
final ArrayList<Employee> employees = new ArrayList<>(); // or this line
for (int i = 0; i < no_of_employees; i++) {
output.println("Creating user #" + (i + 1) + "...");
final Employee newEmployeeWithAddress = new Employee(user_input, output);
employees_list[i] = newEmployeeWithAddress; // either this line
employees.add(newEmployeeWithAddress); // or this line
}
}
}
}

design a user command and multiple inputs

I am a JAVA beginner, and I've done some research. It turned out there is no such a way to deal with this problem. I'm assigned to design a prompt command with multiple data inputs, with only one scanner object.
Now, I've already achieved the following:
Set an array for saving the NimPlayer object.
Set the NimPlayer class for creating a unique NimPlayer object.
Set the counter, used as an index.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print('$');
String input = in.next();
// initialize an array
NimPlayer [] playerList = new NimPlayer[10];
// create a position in the array
int addUserCount = 0;
if (input.equals("addplayer")) {
String userName = in.next();
String familyName = in.next();
String givenName = in.next();
addUserCount +=1;
playerList[addUserCount] = new NimPlayer(userName, familyName, givenName);
}
public class NimPlayer {
String userName;
String familyName;
String givenName;
public NimPlayer(String userName,String surName, String givenName) {
this.userName = userName;
this.familyName = surName;
this.givenName = givenName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public void setFamilyName(String familyName) {
this.familyName = familyName;
}
public void setGivenName(String givenName) {
this.givenName = givenName;
}
public String getUserName() {
return userName;
}
public String getfamilyName() {
return familyName;
}
public String getGivenName() {
return givenName;
}
}
the goal is to design like this:
addplayer userName,familyName,givenName
So, that's why I use next() to identify the first word, and space is the default delimiter.
I am not sure how to do next. What should I do to add a feature that separates the inputs using ",".
Any help is appreciated.
You can read lines with Scanner.nextLine(). Here is an example how you can type "username, surname, givenname" in one line and get splitted by String.split(",").
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String line = s.nextLine();
String[] splittedLine = line.split(",");
for(int i = 0; i < splittedLine.length; i++) {
System.out.printf("splitted line: %d. %s \n", i, splittedLine[i].trim());
}
}
Input:
name, surename, username
Output:
splitted line: 1. name
splitted line: 2. surename
splitted line: 3. username

How to create an Arraylist with an object inside a class in java

The exercise is to have a class named Tenant that will be used to store values of tenants for an apartment. In the main class Prog2 I am trying to create an ArrayList that can hold 4 different values, all regarding the tenant class, which are - the tenant's name, apartment number, initial first payment, and monthly payment. I want to be able to print these values out in separate lines that will provide all 4 pieces of information per tenant - followed by a blank line, and then the same 4 pieces of information for another tenant if there is another one. I can get the program to prompt the questions correctly, but then all I get are nulls and 0's printed out (see below at comment). I appreciate all the help - I'm not the best at this.
// this class is the tenant class that passes all the tenant's
information
public class Tenant {
private String firstName;
private String lastName;
private String aptNumber;
private double yearlyRent;
private String fullName;
private double firstPayment;
private double monthlyPayment;
public Tenant(String name, String aptNum, double fPayment, double
mPayment){
name = fullName;
aptNum = aptNumber;
fPayment = firstPayment;
mPayment= monthlyPayment;
}
public Tenant() {
}
public void setFirstName(String name) {
firstName = name;
}
public void setLastName(String lName) {
lastName= lName;
}
public void setAptNumber(String apt) {
aptNumber = apt;
}
public void setRent(double rent) {
yearlyRent = rent;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getAptNumber() {
return aptNumber;
}
public double getRent() {
return yearlyRent;
}
public double getFirstPayment() {
double monthlyRent = yearlyRent/12;
firstPayment = monthlyRent * 3;
return firstPayment;
}
public double getmonthlyPayment() {
double firstAndLast = yearlyRent/12;
monthlyPayment = (yearlyRent - firstAndLast)/11;
return monthlyPayment;
}
public String getFullName(){
fullName = firstName + " " + lastName;
return fullName;
}
}
// The below class contains the main method
public class Prog2 {
public static double getDouble(Scanner scan) {
System.out.println("Enter yearly rent:");
while (!scan.hasNextDouble()) {
scan.next();
System.out.println("Error: please enter a numeric
value");
}
return scan.nextDouble();
}
public static void main(String[] args) {
Tenant tnt = new Tenant();
Scanner scan = new Scanner(System.in);
System.out.println("Enter number of tenenats:");
int numTenants = scan.nextInt();
ArrayList<Tenant> list = new ArrayList<Tenant>();
for (int i = 0; i<numTenants; i++) {
System.out.println("Enter first name:");
tnt.setFirstName(scan.next());
System.out.println("Enter last name:");
tnt.setLastName(scan.next());
System.out.println("Enter apt number:");
tnt.setAptNumber(scan.next());
tnt.setRent(getDouble(scan));
list.add(new Tenant(tnt.getFullName(), tnt.getAptNumber(),
tnt.getFirstPayment(), tnt.getmonthlyPayment()));
}
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i).getFullName());
System.out.println(list.get(i).getAptNumber());
System.out.println(list.get(i).getFirstPayment());
System.out.println(list.get(i).getmonthlyPayment());
System.out.println();
}
}
}
// this prints out:
null null
null
0.0
0.0
null null
null
0.0
0.0
The issue is with the first constructor in the Tenant class. Remember that the = operator assigns the value of the right operand to the variable in the left operand. In your case the code should look like this:
public Tenant(
String name,
String aptNum,
double fPayment,
double mPayment)
{
fullName = name;
aptNumber = aptNum;
firstPayment = fPayment;
monthlyPayment = mPayment;
}
What I typically do with constructors is name the parameters after the field, then on the left side of the field assignments use this to refer to the field as opposed to the parameter. This ends up looking much clearer:
public Tenant(
String fullName,
String aptNumber,
double firstPayment,
double monthlyPayment)
{
this.fullName = fullname;
this.aptNumber = aptNumber;
this.firstPayment = firstPayment;
this.monthlyPayment = monthlyPayment;
}
this can be tricky to use but this is an example where it can clear things up.
Many things are wrong with your code .
Constructor of
public Tenant(String name, String aptNum, double fPayment, double
mPayment){
name = fullName;
aptNum = aptNumber;
fPayment = firstPayment;
mPayment= monthlyPayment;
}
here your not just assigning null values to your function parameeters, instead of assigning values to your class fields from function parameters.
Also, when you are calling function getFullName() , it will return null as firstName and lastName fields are not initialized.
So, you need to modify your constructor to -
public Tenant(String firstNamename, String lastName, String aptNum, double fPayment, double
mPayment){
this.firstName = firstNamename;
this.lastName = lastName;
this.aptNumber = aptNum;
this.firstPayment = fPayment;
this.monthlyPayment = mPayment;
this.fullName = getFullName();
}
also in for loop , you need to change
list.add(new Tenant(tnt.getFullName(), tnt.getAptNumber(),
tnt.getFirstPayment(), tnt.getmonthlyPayment()));
to -
list.add(new Tenant(tnt.getFirstName(),tnt.getLastName(), tnt.getAptNumber(),
tnt.getFirstPayment(), tnt.getmonthlyPayment()));

When using a for loop to add objects to an array, the last object that is added is used for all instances

Ive been trying to use a for loop to add instances of a driver to a driver array. Each driver has 3 basic variables that are gathered through the for loop. When the loop runs though, the details of the last driver are stored in all of the indexes of the array! I want to get it so that i can add each individual driver to the array.
public static void addDriver(Driver[] d) { //method using for loop to add drivers
for(int i = 0; i < d.length; i++ ) {
String name, DOB, occupation;
System.out.println("Please Enter Driver Name");
name = kb.nextLine();
System.out.println("Please Select Driver Occupation");
System.out.println("1: Chauffeur" + "\n2: Accountant");
int choice = kb.nextInt();
kb.nextLine();
if (choice == 1) {
occupation = "Chauffeur";
} else {
occupation = "Accountant";
}
System.out.println("Please Enter Driver D.O.B");
DOB = kb.nextLine();
d[i] = new Driver(name, occupation, DOB);
}
}
any and all help greatly appreciated!
edit...
here is the code from the main method, i get the size of the array from a separate method called driverNum.
public static void main(String[] args) {
int drivers = driverNum(); //Setting size of the array
Driver[] d = new Driver[drivers]; //creating new array using number of drivers to be insured
addDriver(d); //calling method to add drivers to array
for(int x = 0; x < d.length; x++)
{
System.out.println(d[x].toString());
}
}
here is the Driver class that i have been using...
public class Driver {
static String name, occupation, DOB;
public Driver()
{
name = "";
occupation = "";
DOB = "";
}
public Driver(String name, String occupation, String DOB)
{
this.name = name;
this.occupation = occupation;
this.DOB = DOB;
}
public void setName(String name)
{
this.name = name;
}
public String getName(Driver d)
{
return name;
}
public void setOccupation(String occupation)
{
this.occupation = occupation;
}
public String getOccupation()
{
return occupation;
}
public void setDOB(String DOB)
{
this.DOB = DOB;
}
public String getDOB()
{
return DOB;
}
public String toString()
{
String s;
s = "Name: " + name;
s = s + "\nOccupation: " + occupation;
s = s + "\nDOB: " + DOB;
return s;
}
}
Ive been scratching my head over this for a while now, because i thought it was correct. Thanks for the help so far!
In your Driver class, you defined your three global variables, name, occupation, and D.O.B as static. This means that whenever you change the value of that variable, it will change everywhere in the program, even if you create multiple instances of that class. Just take out the static declaration and that should solve your problem.

How to add an integer to my arraylist?

I currently have my code set up so a student's name and subject is added to my arraylist, and then printed when user is done. How ever as I'm not wanting to add a string now, I want to add a student number, i'm unfamiliar with how to go about this. I have tried replacing set with add, and string with int, but to no prevail.
Here is my main code
import java.util.*;
public class StudentData
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
ArrayList<Student> studentList = new ArrayList<Student>();
String yesNo = "true";
do
{
System.out.println("Enter student's name: ");
String name = in.next();
System.out.println("Enter student's subject: ");
String subject = in.next();
System.out.println("Enter student's number: ");
int number = in.nextInt();
Student s = new Student(name,subject,number);
s.setName(name);
s.setSubject(subject);
s.Number.add(number);
studentList.add(s);
do
{
System.out.println("Would you like to enter data for another student? Yes/No ");
yesNo = in.next();
}
while (!yesNo.equalsIgnoreCase("YES") && !yesNo.equalsIgnoreCase("NO"));
}
while (yesNo.equalsIgnoreCase("YES"));
for(int i = 0; i < studentList.size(); i++)
{
System.out.println(studentList.get(i).getName());
System.out.println(studentList.get(i).getSubject());
}
}
}
and
class Student
{
private String studentName;
private String studentSubject;
public Student(String name, String subject, int number )
{
setName(name);
setSubject(subject);
Number.add(number);
}
public String getName()
{
return studentName;
}
public void setName(String name)
{
studentName = name;
}
public String getSubject()
{
return studentSubject;
}
public void setSubject(String subject)
{
studentSubject = subject;
}
public int getNumber()
{
return studentNumber;
}
public void Number.add(int number)
{
studentNumber = number;
}
}
As you are storing Student objects in your list you are also storing the member variables of each object as you entered them. So no different approach needs to be taken to store an integer.
You can declare your private int studentNumber; in your student class, add a getter and a setter for it and then modify your constructor so that setStudentNumber(number); would work in the same way as setting your two Strings up.
Then to iterate through your list you could make use of the 'enhanced-for' syntax instead of a plain old for loop, meaning:
for (Student s : studentList) {
System.out.println(s.getName());
System.out.println(s.getSubject());
System.out.println(s.getStudentNumber());
}
Hope that this helps, if you need anything more just give me a shout below.

Categories

Resources