Java - Using variable from another class as method argument - java

In my Main class I have this piece of code:
UUID uniqueID;
public void createEmployee(){
uniqueID = UUID.randomUUID();
// ...
}
In my class Corporation there's a method called promoteEmployee, which should receive the uniqueID as parameter. Is that possible, and when yes, how?
public void promoteEmployee(uniqueID){
// it doesn't recognize uniqueID as argument
}
I also have the method sortEmployees, which sorts the ArrayList alphabetically, and if two names are equal, the employee with a higher salary should be printed out first. It sorts the List alphabetically, but doesn't check if the salary is bigger. What do I need to change?
ArrayList<Employee> employees = new ArrayList<Employee>();
public void sortEmployees(){
Collections.sort(employees, (p1, p2) -> p1.name.compareTo(p2.name));
for(Employee employee: employees){
Comparator.comparing(object -> employee.name).thenComparingDouble(object -> employee.grossSalary);
System.out.println("ID: " + employee.ID + END_OF_LINE + "Name: "+employee.name + END_OF_LINE + "Salary: " + employee.grossSalary);
System.out.println(""); // just an empty line
}
}

Change the method to be valid java code
public void promoteEmployee(UUID uniqueID){
but as it even seems to be a field, why pass the value at all?
As for sorting see
Implementing Java Comparator

one passes variables from one class to another's methods by using the classname.method(arg) syntax.
public class JavaTeachMe2018
{
//variable in other class to be passed as a method argument
public static int startID = 0;
public static void main(String[] args)
{
// we are passing startID to anouther class's method
String[] currentEmployees = Corporation.createEmployee(startID);
System.out.println("Welcome " + currentEmployees[1] + " to the company as employee number " + currentEmployees[0]);
}
}// end class teachme
here is the second class
import java.util.Scanner;
public class Corporation
{
public static int createId(int startID)
{
// create unique id
int uniqueID = startID + 1;
return uniqueID;
}
public static String[] createEmployee(int startID)
{
// assign a variable to the return of the createId call
int employeeNumber = createId(startID);
System.out.println("Your assigned employee number is " + employeeNumber);
// get employee name
Scanner stdin = new Scanner(System.in);
System.out.print(" Enter Your Name : ");
String employeeName = stdin.nextLine();
String employees[] = {Integer.toString(employeeNumber), employeeName};
return employees;
}
}

Related

Print a specific cell from a string array

I've created a class that includes people data named "Datiutente" and an object based on that class named "du". Every person has a name and a surname (with the set/get methods).
I want to create a system that can provide the user information on a specific person based on the position which they are stored in the array.
I tried using a variable named vd to ask the user which person wanted to visualize based on the position that a person gained in the array (inserted in the for cycle), but when I try to print with vd it just prints "Name: null". Same if I change "vd" to "1". It always prints "Null".
(Yes, I tested this when I already inserted some data.)
Here's the full code:
package appartamento;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Appartamento {
public static void main(String[] args) throws IOException {
InputStreamReader input = new InputStreamReader(System.in);
BufferedReader keyb = new BufferedReader(input);
boolean attiva = true;
do {
System.out.println("what do you want to do?");
System.out.println("1 - check for a person");
System.out.println("2 - Add person");
int choice = Integer.parseInt(keyb.readLine());
Datiutente du[] = new Datiutente[10];
if (choice == 2){
System.out.println("How many people?");
int hm = Integer.parseInt(keyb.readLine());
for (int i=0;i<hm;i++){
du[i] = new Datiutente();
System.out.println("insert name:");
du[i].setName(keyb.readLine());
System.out.println("insert surname");
du[i].setSurname(keyb.readLine());
}
}
if (choice == 1){
System.out.println("which person are you searching?");
int vd = Integer.parseInt(keyb.readLine());
System.out.println("position: " + i);
System.out.println("Name: "+ du[i]);
System.out.println("Surname: " + du[i]);
}
} while (attiva = true);
}
}
and the class "Datiutente":
package appartamento;
public class Datiutente {
private String name;
private String surname;
private String codfis;
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
public void setSurname(String surname){
this.surname = surname;
}
public String getSurname(){
return surname;
}
}
In every iteration you define the Datiutente du[] = new Datiutente[10];, so du is reset to {null,...,null} and the data saved in the previous iteration are replaced;
Try to define the array before the loop statement.
I found a way here:
You need to insert values on object creation, you can also use hashmaps
hashmap will benefit you more I think.
Code sample to fix your stuff.
class GFG {
public static void main(String args[]){
// Declaring an array of student
Student[] arr;
// Allocating memory for 2 objects
// of type student
arr = new Student[2];
// Initializing the first element
// of the array
arr[0] = new Student(1701289270, "Satyabrata");
// Initializing the second element
// of the array
arr[1] = new Student(1701289219, "Omm Prasad");
// Displaying the student data
System.out.println(
"Student data in student arr 0: ");
arr[0].display();
System.out.println(
"Student data in student arr 1: ");
arr[1].display();
}
}
class Student {
public int id;
public String name;
// Student class constructor
Student(int id, String name)
{
this.id = id;
this.name = name;
}
// display() method to display
// the student data
public void display()
{
System.out.println("Student id is: " + id + " "
+ "and Student name is: "
+ name);
System.out.println();
}
}

It says "syntax error, insert 'VariableDeclarator'"

I am very new to programming and have started java this week. I am learning about object-orientation. Here is my problem:
public class Person
{
int age = 0;
String name = "John Doe";
void display{
System.out.println(name + " is " + age + " years old. ");
}
}
public class Driver
{
public static void main(String[] args)
{
Person mark = new Person();
mark.age = 25;
mark.name = "Mark";
display;
}
}
But it keeps saying
syntax error, insert 'VariableDeclarator'
Follow the instructions of your IDE.
the method display is part of the class Person and must have the correct syntax(visibility - return type - name - parameters).
you have to call the display method from the created Person object mark. Otherwise the method would not be resolvable for the compiler.
And last but not least... you have to create your own class for Person because two public classes are not possible in one source file or you have to reduce the visibility of the Driver class.
package de.db.ri.as.gleisansagen.evaluator;
public class Person {
int age = 0;
String name = "John Doe";
void display() {
System.out.println(name + " is " + age + " years old. ");
}
}
class Driver {
public static void main(String[] args) {
Person mark = new Person();
mark.age = 25;
mark.name = "Mark";
mark.display();
}
}
Dont'code your own syntax program first learn java syntax then start coding
https://docs.oracle.com/javase/specs/
public class Person {
int age = 0;
String name = "John Doe";
void display() {
System.out.println(name + " is " + age + " years old. ");
}
}
public class Driver {
public static void main(String[] args) {
Person mark = new Person();
mark.age = 25;
mark.name = "Mark";
mark.display();
}
}

Program Output Issue

I apologize for the lengthy submission but I am having some difficulty with getting this program to work correctly.
There is another Driver program that runs this one and it requires me to print out the name, level, supplies, etc., of a Magician (given certain parameters).
However, when I use the toString() method to print out the String. I continuously get a
"null" response for my name/level/supplies. My numbers also seem to not update.
Could someone take a look and see what I am doing wrong?
I just can't seem to make the program pick up the Magician parameters.
public class Magician
{
private String name, level, supplies;
private int galleons;
private double health;
public Magician(String initialValues)
{
double health = 1000;
int galleons = 200;
initialValues = name + "#" + level + "#" + supplies;
}
public String toString()
{
return "Name: " + name+
"Level: " + level +
"Galleons: " + galleons +
"Health: " + health +
"Supplies: " +supplies;
}
}
This is the beginning of the Driver program that I can not get to print out:
public class MagicAndMalice
{
public static void main (String[] args)
{
Magician harry = new Magician("Harry Potter#apprentice#Owl#Wand");
System.out.println(harry); // test toString() method
System.out.println("------------------------\n\n");
}
}
First, you are declaring health and galleons again. You should not declare them again, just assign the values:
health = 1000;
galleons = 200;
Also, it seems like you are confused about assignment. If you want to assign some value to name, level and supplies, you have to do:
name = ...;
level = ...;
supplies = ...;
If initialValues will contain a string like "a#b#c" and you want to assign each "part" to those variables, you can use String#split():
String[] parts = initialValues.split("#");
name = parts[0];
level = parts[1];
supplies = parts[2];
But I would really recommend you to read a book or follow some tutorials of Java, so you get the basics first.
You are missunderstanding the value assignment thing in Java. You won't need a separator like #, but if you do, you would need to e.g. substr the given String in the constructor.
Here's a short (untested) version, that should clarify what I mean:
public class Magician {
private String name, level, supplies;
private int galleons;
private double health;
public Magician(String name, String level, String supplies) {
health = 1000;
galleons = 200;
this.name = name;
this.level = level;
this.supplies = supplies;
}
// Let's do some Constructor overloading here
public Magician(String initialValueString) {
String[] initialValues = initialValueString.split("#");
this(initialValues[0], initialValues[1], initialValues[2]);
}
public String toString() {
return "Name: " + name +
"Level: " + level +
"Galleons: " + galleons +
"Health: " + health +
"Supplies: " + supplies;
}
}
public class MagicAndMalice {
public static void main (String[] args) {
// Method one
Magician harry = new Magician("Harry Potter", "apprentice", "Wand");
System.out.println(harry);
System.out.println("------------------------\n\n");
// Method two
Magician ron = new Magician("Ron Weasley#apprentice#Owl");
System.out.println(ron);
System.out.println("------------------------\n\n");
}
}
And if you want to have more values than just one in the supplies field, have a look at Array or try to split/substr the values with some regular expressions.
Hope that helped to get some clearer about the variable assignment in Java.
When you create object as
Magician harry = new Magician("Harry Potter#apprentice#Owl#Wand");
only double health = 1000; & int galleons = 200; get initialled as some value.
When you call toString() method then
public String toString()
{
return "Name: " + name+
"Level: " + level +
"Galleons: " + galleons +
"Health: " + health +
"Supplies: " +supplies;
}
the value null for some field is returned because it is not initialized at all.
I think it might make more sense to change your constructor to take separate arguments instead of one string that has to be split up.
public Magician(String name, String levels, String supplies, int gallons, double health) {
this.name = name;
this.levels = levels;
...
}
Notice the prefix "this." which prevents name conflicts between the member variables of the class and the parameters passed to the constructor.

Setting Constructor Teller in Main() to call specific accounts in a method

In this code I am making a Bank Account of sorts. It has a basic BankAccount that has variables Name and id. It has a savings account that has interest and a checking account with a credit line. Both of those classes extends to the BankAccountInfo class.
In the Teller class I have a constructor Teller with a name and date processed that is set in the Main(). I have a method called setUpAccts() that includes the accounts I have created so far, the checking, savings and two basic bankaccounts.
In the Main() I want to be be able to have multiple tellers calling specific accounts.
For example, I want Teller John to only call acct1, which would be the checking account. Then I want another teller, Kate, to only call acct2, the savings account and it's content.
As it stands I only have a single Teller calling every single account in the setUpAccts() method.
Here is the Teller code.
EDIT: Sorry for having a horrible description, I hope the new one makes my problem more clear.
class Teller
{
String name;
String dateProcessed;
int random;
public Teller(String n, String dP)
{
name = n;
dateProcessed = dP;
System.out.println("Teller:" + " " + name + " " + "This transaction will process:" + " " + dateProcessed);
}
public void setUpAccts()
{
CheckingAccount acct1 = new CheckingAccount("Dylan Kuchar", 11, "Checking");
//acct1.setCheckingAccount("Dylan", "11", "Checking", acct1.getOverdraft());
acct1.printCheckingAccount();
acct1.setBalance(250);
//acct1.printBalance();
acct1.withdraw(120.5);
//acct1.printBalance();
SavingsAccount acct2 = new SavingsAccount("Emily Doe", 2, "Savings");
acct2.printSavingsAccount();
acct2.setBalance(225.5);
acct2.InterestBalance();
acct2.withdraw(500);
BankAccountInfo acct3 = new BankAccountInfo();
acct3.BankAccountInfo("Dylan", 11);
acct3.printBankAccountInfo();
acct3.setBalance(150);
acct3.deposit(20);
acct3.printBalance();
BankAccountInfo acct4 = new BankAccountInfo();
acct4.BankAccountInfo("Emily", 2);
acct4.printBankAccountInfo();
acct4.setBalance(650);
acct4.withdraw(150);
acct4.printBalance();
}
public static void main(String args[])
{
Teller t = new Teller("John", "Today");
t.setUpAccts();
}
}
Well, the simple way is simply making a teller a specific type on initialization. So your code would change to:
class Teller
{
String name;
String dateProcessed;
Boolean Savings;
int random;
public Teller(String n, String dP, Boolean Savings)
{
name = n;
dateProcessed = dP;
this.Savings = Savings;
System.out.println("Teller:" + " " + name + " " + "This transaction will process:" + " " + dateProcessed);
}
then you just change your setUpAccts class to only deal with one Person. and place a if else to see if the teller is dealing with savings or checking. prolly not the best, but its what came to mind.
Edit:
What you can do is create a Class called Account, CheckingAccount and Savings Account would inherit from this class. You can then do this:
class Teller
{
Account acct;
String name;
String dateProcessed;
int random;
public Teller(Account act, String dP)
{
acct=act;
name = acct.getname();
dateProcessed = dP;
System.out.println("Teller:" + " " + name + " " + "This transaction will process:" + " " + dateProcessed);
}
public void acctStuff()
{
if(acct instenceof checkingAccount)
{ //do checking stuff}
else { //do savings stuff}
}
let me know if I missed something or if something doesnt make sense

Version 2.0 (adding Queries now)

I am writing a program that will read a file and extract the data for each student. I did this successfully with a while loop and input.next(). However, I need to pass the variables into a collection to record each students data, so for each loop I want to add the 4 variables (id, first, last, year) to the collection again. I should note that the collection has to be in a different class and that I will have to be able to search through this collection to find, for example, all students graduating this year.
If anyone could point me in the right direct in regard to storing the variables in a collection, which is in a different class, for each loop.
I know this is a basic question but I am very new to Java so I appreciate everyone’s help!
The first class is
import java.util.*;
import java.io.*;
import java.lang.*;
public class ProcessRecords {
public static void AskUser()
throws Exception {
Scanner preference = new Scanner(System.in);
//Creating a new scanner will allow us to gather user input
boolean flag=true;
//I will use this for my while loop
while (flag) {
System.out.println("What type of Search would you like to run?\n 1)Search for all students\n 2) Search for students graduating in a specific year\n 3)Search for students whose last name begins with a certain string\n");
int searchType=preference.nextInt();
//This variable will store what type of query the user would like to run
switch(searchType) {
case 1:
System.out.println("Gathering Records for all students\n");
//Call Query Method in the Query Class to return all students in the colletion
case 2
System.out.println("What graduation year would you like to search for? \n");
String yearsearch=preference.next();
//Call Query Method to return students who are graduating in the specified year
//Pass the "yearsearch" variable to the Query class to run the search
case 3:
System.out.println("What string would you like to search for? \n");
String lstsearch=preference.next();
//Call Query Method in the Query Class to return students who have the string in their last name
//I need to pass the "lstsearch" variable to the Query class to search through last names
}
}
}
public static void main(String[] args)
throws Exception
{
Scanner input = new Scanner(new File("students.txt"));
//This will import the file
input.nextLine();
//This will skip the headers in the file
System.out.println("Processing file now...");
//Let the user know that the file is being processed
int id;
String last;
String first;
int year;
int i=1;
// Declare variables that we will extract from the file
//Now we will being processing the file with a while loop
List<StudentRecord> studentRecords = new ArrayList<StudentRecord>();
while(input.hasNext())
{
id=input.nextInt();
last=input.next();
first=input.next();
year=input.nextInt();
StudentRecord record = new StudentRecord(id, last, first, year);
studentRecords.add(record);
System.out.println(id + " " + last + " " + first + " " + year + "\n");
}
System.out.println(" You have successfully read and printed from the file!");
for (StudentRecord s : studentRecords)
System.out.println(s.toString());
}
}
The next Class is
public class StudentRecord{
public int id;
public String last;
public String first;
public int year;
public StudentRecord(int d, String lt, String ft, int yr){
id=d;
last=lt;
first=ft;
year=yr;
}
public String toString()
{
return id + " " + last + " " + first + " " + year;
}
}
Thanks!
Change the second class:
public class StudentRecord
{
public int id;
public String last;
public String first;
public int year;
public StudentRecord(int d, String lt, String ft, int yr)
{
id=d;
last=lt;
first=ft;
year=yr;
}
public string toString()
{
return id + " " + last + " " + first + " " + year;
}
}
The method is called constructor and you can create instances of this class using it.
In your second class, while running through the loop, you can create new StudentRecord object with actual values for each entry by passing parameters to the constructor:
List<StudentRecord> studentRecords = new ArrayList<StudentRecord>();
while(input.hasNext())
{
id=input.nextInt();
last=input.next();
first=input.next();
year=input.nextInt();
StudentRecord record = new StudentRecord(id, last, first, year);
studentRecords.Add(record);
System.out.println(id + " " + last + " " + first + " " + year + "\n");
}
The ArrayList will serve you as a storage of all StudentRecord objects.
If you override the toString method of your StudentRecord object (as I did above), you can print all student records to the console in a loop:
for (StudentRecord s : studentRecords)
System.out.println(s.toString());
Is there anything wrong with making an ArrayList of StudentRecord objects?
public class StudentRecord {
public int id;
public String last;
public String first;
public int year;
public StudentRecord(int id, String last, String first, int year) {
this.id = id;
this.last = last;
this.first = first;
this.year = year;
}
}
Then right after you grab the values from a file:
ArrayList<StudentRecord> studentRecords = new ArrayList<StudentRecord>();
//...
id = input.nextInt();
last = input.next();
first = input.next();
year = input.nextInt();
studentRecords.add(new StudentRecord(id, last, first, year));
//...

Categories