Here is a small program which adds and print out workers. When calling a method to print I receive an output with identical elements as many times as the number of elements I have added. I cant understand where is my mistake.
public class Radnik {
static List<Radnik> workers = new ArrayList<>();
private String name;
public static void main (String []args) {
Radnik.add();
for(Radnik r : workers) {
System.out.println(r);
}
}
public static void add () {
String name;
String answer;
do {
Scanner s = new Scanner(System.in);
System.out.println("name");
name = s.next();
Radnik f = new Radnik();
workers.add(f);
System.out.println("More");
answer = s.next();
} while (answer.equals("yes"));
}
}
You never set the name to a Radnik.
I would add the constructor Radnik(String name) to initialize name and also add an getter and setter.
System.out.println(r) will only print nonsense because it calls Object.toString(). You have to override toString() or call another method to output something meaningful.
public class Radnik {
static List<Radnik> workers = new ArrayList<>();
private String name;
public Radnik(String name) {
this.name = name;
}
public String getName() {
return name;
}
#Override
public String toString() {
return "Radnik=[name=\""+name+"\"]";
}
public static void main (String []args) {
Radnik.add();
for(Radnik r : workers) {
System.out.println(r);
}
}
public static void add () {
String name;
String answer;
do{
Scanner s = new Scanner(System.in);
System.out.println("name");
name = s.next();
Radnik f = new Radnik(name);
workers.add(f);
System.out.println("More");
answer = s.next();
} while (answer.equals("yes"));
}
}
public class MainClass{
private static List<Radnik> workers = new ArrayList<>();
public static void main (String []args) {
new MainClass().add();
for(Radnik r : workers) {
System.out.println(r.getName());
}
}
public void add () {
String name;
String answer;
do{
Scanner s = new Scanner(System.in);
System.out.println("name");
name = s.next();
Radnik f = new Radnik();
f.setName(name);
workers.add(f);
System.out.println("More");
answer = s.next();
} while (answer.equals("yes"));
}
public class Radnik {
private String name;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
}
Related
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
}
}
}
}
import java.util.ArrayList;
import java.util.Scanner;
public class Student {
static String studentNum;
static int age;
static String Name;
Student(int Age, String Name){
this.Name = Name;
this.age = Age;
}
public static String input_read() {
Scanner sc = new Scanner(System.in);
if (sc.hasNext()) {
studentNum = sc.next();
} else {
sc.close();
}
return studentNum;
}
public static int setAge() {
System.out.println("Enter the age of the Student");
return Integer.valueOf(input_read());
}
public static String setName() {
System.out.println("Enter the name of the Student");
return input_read();
}
public static int getAge() {
return age;
}
public static String getName() {
return Name;
}
public static void main(String[] args) {
ArrayList<Student> ar = new ArrayList();
for (int i=0; i<2; i++) {
Student s1= new Student(setAge(), setName());
ar.add(s1);
}
for (Student each :ar){
System.out.println(each.getName());
System.out.println(each.getAge());
}
}
}
I am new guy in Java. I created a program to add student age and name. This program output is printing only last object 2 times. It is not printing all the objects in the list. Anybody know why?
You should remove the keyword static from your member variables.
That is causing them to be shared across all instances.
See here: What does the 'static' keyword do in a class?
I'm learning about constructors, but the videos that I've watched don't seem to help and everything I find on google seems to describe it in an advanced way.
I want to write a simple program which takes two inputs, a name (String) and an id (integer) and then just outputs it as "id" - "name". So for example:
01 - hello
This is the program that I'm trying to fix:
import java.util.Scanner;
public class ConstructorTest {
public static void main(String[] args) {
ConstructorTest();
toString(null);
}
//Constructor
public ConstructorTest(){
Scanner name = new Scanner(System.in);
Scanner id = new Scanner(System.in);
}
// Method
public String toString(String name, int id) {
System.out.print(id + " - " + name);
return null;
}
}
The errors that I get, are saying that my methods and constructors are undefined.
A constructor creates ("constructs") a new object. You can then call methods against that object.
Here's a simple object:
public class MyObject {
private int id;
private String name;
public MyObject(int id, String name) {
this.id = id;
this.name = name;
}
// Other methods here, for example:
public void print() {
System.out.println(id + " " + name);
}
}
You would call this constructor like this:
MyObject thing = new MyObject(1, "test");
And then you could call its method like this:
thing.print();
So for your example, what you'd do in your main method is first prompt the user for id and name, then create an object using a constructor, and then call a method on the constructor.
public class ConstructorTest {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// get the id and name from the scanner (I would suggest using prompts)
String name = in.nextLine();
int id = in.nextInt();
// create an object:
ConstructorTest myObject = new ConstructorTest(id, name);
// call the method:
String myString = myObject.toString();
// print the result:
System.out.println(myString);
}
// private variables, effectively the "properties" stored by the object:
private int id;
private String name;
// constructor:
public ConstructorTest(int id, String name) {
this.id = id;
this.name = name;
}
// method
#Override // because this is a method in java.lang.Object and we're overriding it
public String toString() {
return id + " - " + name;
}
}
Try this:
import java.util.Scanner;
public class ConstructorTest {
private int id;
private String name;
public static void main(String[] args) {
String name = args[0];
int id = Integer.valueOf(args[1]);
ConstructorTest ct = new ConstructorTest(name, id);
System.out.println(ct);
}
public ConstructorTest(String n, int i) {
this.id = i;
this.name = n;
}
// Method
public String toString() {
return String.format("%d - %s", id, name);
}
}
Never, ever put I/O in a constructor.
Hi so I have a project for college where I need to build a chat in java that to work only in on computer where you execute the code and you give the name of the two users and a translation value but I am having a problem with the way they want me to do it since I cant use super, arrays , extends, or inherences I am having a problem how it currently is I my Main like this
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Chat ch = null;
boot(in, ch);
menu(in, ch);
}
public static Chat boot (Scanner in, Chat ch){
String name1;
String name2;
int transvalue = 0;
System.out.print("Username 1:");
name1=in.nextLine();
do{
System.out.print("Username 2:");
name2=in.nextLine();
if (name1.equals(name2)){
System.out.println("Names can't be equal");
}
}while(name1.equals(name2));
do{
System.out.print("Translation Value:");
transvalue=in.nextInt();
in.nextLine();
if (transvalue<1 || transvalue>26){
System.out.println("Value Can only be between 0 and 26");
}
}while(transvalue<1 || transvalue>26);
return new Chat(name1,name2,transvalue);
}
So this show be adding the info I put in to my class Chat
public class Chat {
private static final int id1 = 1;
private static final int id2 = 2;
private Users u1;
private Users u2;
private Conversation conv;
public Chat(String name1, String name2, int transvalue){
u1 = new Users(id1,name1);
u2 = new Users(id2,name2);
conv = new Conversation(transvalue);
}
public static int getId1() {
return id1;
}
public static int getId2() {
return id2;
}
public Users getU1() {
return u1;
}
public void setU1(Users u1) {
this.u1 = u1;
}
public Users getU2() {
return u2;
}
public void setU2(Users u2) {
this.u2 = u2;
}
public Conversation getConv() {
return conv;
}
public void setConv(Conversation conv) {
this.conv = conv;
}
}
but when I add the info and try to return it like for example:
System.out.print(ch.getU1());
or
System.out.print(ch.getU1().getName());
I am getting a null am I doing something wrong?
public class Users {
private int id ;
private String name;
private String mess;
public Users(int id,String name){
this.id=id;
this.name=name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
Can anyone find or point out what I'm doing wrong
Thank you in Advance to all that take the time to Help
This is not supposed to be a client class. I'm just making a class for others to use. I'm using this for a Highschool. For example i have classes for the address, teacher, students, principal, roomnumber, etc..But its not compiling for some odd reason. I believe its because I'm not declaring a field but not sure.
import java.io.*;
public class HighSchool {
// Constructors
public HighSchool() { }
public HighSchool(String title, String teacher, int roomNumber, String period, String[] students, String address, String subjects ) {
this.title = title;
this.teacher = teacher;
this.roomNumber = roomNumber;
this.period = period;
this.String[] students = students;
this.String address =a ddress;
this.String subjects = subjects;
}
public class Classcourse (String title, String teacher, int roomNumber, String period, String[] students, String address, String subjects
private String period;) {
public String gettitle() {
return title;
}
public void settitle(String title) {
this.title = title;
}
public String getteacher() {
return teacher;
}
public void setteacher(String teacher) {
this.teacher = teacher;
}
public int getroomNumber() {
return roomNumber;
}
public void setroomNumber (int roomNumber) {
this.roomNumber = roomNumber;
}
public String getperiod() {
return getperiod();
}
public void setperiod (String period) {
this.period = period;
}
public String[] getstudents () {
return students[];
}
public void setstudents[] (String[] students
private String address;) {
this.students = students;
}
public String getaddress() {
return address;
}
public void setaddress (String address) {
this.address = address;
}
public String getsubjects() {
return subjects;
}
public void setsubjects (String subjects) {
this.subjects = subjects;
}
}
// modifier method
public void addstudents(String students) {
String[] newstudents = new String[students.length + 1];
for (int i = 0; i < students.length; i++) {
newstudents[i] = students[i];
}
newstudents[students.length] = student;
students = newstudents;
}
public boolean isInClass(String students) {
for (int i = 0; i < students.length; i++) {
if (students[i].equals(students)) {
return true;
}
}
return false;
}
// static creator method
public static HighSchool readFromInput() throws IOException {
BufferedReader kb = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a HighSchool title: ");
HighSchool newHighSchool = new HighSchool(kb.readLine());
String students = null;
do {
System.out.print("Enter a student, or press Enter to finish: ");
students = kb.readLine();
if (students != null){
newHighSchool.addstudents(students);
}
} while (students != null);
return newHighSchool;
}
// Variables (Fields)
private String title;
private String[] students;
}
In addition, you wrote something that doesn't make sense from the point of view of Java Compiler:
private String period;) {
- probably remove ")".
The second thing:
Take a look on the declaration of class Classcourse.
It rather sounds wrong, although it can be an issue of this site's editor or something...
An "overall" hint - java has a very "intelligent" compiler in the most of the cases it can say what's wrong exactly with your code, so, assuming you're a newbie in Java, try to understand what compiler says to you.
Good luck!
Some things I noticed about the code:
public String getperiod() {
return getperiod();
}
This code will cause a endless loop when you call this function.
private String address;) {
this.students = students;
}
The compiler will give an error about the ";)". Change it to "()" to fix this.
Furthermore, you should really tell us more about the errors it's giving you. We can't help you if you don't give us the compiler errors.