Allocate more than one value to an Array? [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
i'm new to Java and I'm trying to write a code that Scan for some Patients' names, also ask them to enter (y/n) if they are allergicToGluten, and then I print out a list of name of all the patients that are allergicToGluten. I just learnt Arrays but i'm still struggling in assigning many values ( name + y/n ) to an Array. I need your help.
Thank you very much :D

You need to create a class that represents your patient. And then you can have array of patients
public class Patient{
private String name;
private boolean allergicToGluten;
public Patient(String name, boolean allergicToGluten){
this.name = name;
this.allergicToGluten = allergicToGluten;
}
public boolean isAllergicToGluten(){
return allergicToGluten;
}
public String getName(){
return name;
}
}
----
Patient[] patients = new Patient[patientCount];
If you don't know patientCount then you need resizable-array.
ArrayList<Patient> patients = new ArrayList<Patient>();
// ... reading 'name' and 'isAllergic' from input
patients.add(new Patient(name, isAllergic));
And then you can print list of allergic patients
for(p : patients){
if (p.isAllergicToGluten())
System.out.println(p.getName());
}

There is no way to allocate more than one value to an array, but you can make an array of some class with multiple fields in it. For example,
public class Patient {
public String name;
public boolean isAllergic;
public Patient(String name, boolean isAllergic) {
this.name = name;
this.isAllergic = isAllergic;
}
}
public class Patient_Driver {
public static void main(String[] args) {
Patient[] patients = new Patient[] {
new Patient("Steve", true),
new Patient("Mary", false)
};
for (int i = 0; i < patients.length; i++) {
if (patients[i].isAllergic) {
System.out.println(patients[i].name);
}
}
}
}
Output:
Steve

Related

Trouble calling methods from a class/ [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 11 months ago.
Improve this question
Can someone tell me whats wrong with these codes ?
public class Student {
String name;
int roll_no;
public void getDetails(String Name, int roll) {
name = Name;
roll_no = roll;
}
}
and this
public class StudentRun {
Student student = new Student();
String n = "John";
int r = 2;
student.getDetails(n, r);
}
It shows the error:
Multiple markers at this line
on the line where i call the student.getDetails(n,r)
You cannot call a method in a class without it being wrapped in a method.
Your Student class also lacks a constructor (a method that is called when the class is instantiated) and lacks the context of attribute visibility (public/protected/private).
The constructor must call itself as the class, in your case:
public class Student {
protected String name;
protected int roll_no;
public Student(String Name, int roll) {
this.name = Name;
this.roll_no = roll;
}
public String getName() {
return this.name
}
....
}
Once you have structured the class correctly, you need to do the following to instantiate it:
class OtherClass {
public static void main (String[] args) {
student = new Student("John", 42);
System.out.println(student.getName());
}
}
it looks to me you are calling the method without wraping it in a method in your class StudentRun. try using a constructor or some other method to call student.GetDetails
like
void callStudentRun
{
student.Getdetails();
}

making a array of objects that can have variable amount of elements [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I am trying to make a class to handle my user database for a programming school project. This will be using arrays and not arraylist which is a core parameter of the assignment.
public class UserDB {
User[] UserAry;
public UserDB(){
UserAry = new User[0];
}
//admin
public void addUser(String id, String pw, char type){
User[] NewUserAry = new User[UserAry.length+1];
for (int i=0; i<UserAry.length;i++){
NewUserAry[i] = UserAry[i];
}
NewUserAry[NewUserAry.length-1] = new User(id,pw,type);
UserAry = NewUserAry;
}
}
This is the code. I'm worried that if i were to call this in another class, then the array would always be at 0(when i call UserDB) or 1 (when i add a new user it would add one to previous zero) , before the arraysize becomes to zero again since it is initialized as 0.
I do not see any problem with your code. Just for the sake of making it cleaner, I have replaced your for loop with System.arraycopy. Apart from that, I have also replaced the variable names following the naming convention. Given below is the working code:
public class User {
String id,pw;
char type;
public User(String id, String pw, char type) {
super();
this.id = id;
this.pw = pw;
this.type = type;
}
#Override
public String toString() {
return "User [id=" + id + ", pw=" + pw + ", type=" + type + "]";
}
}
public class UserDB {
User[] userAry;
public UserDB() {
userAry = new User[0];
}
public void addUser(String id, String pw, char type) {
User[] newUserAry = new User[userAry.length + 1];
System.arraycopy(userAry, 0, newUserAry, 0, userAry.length);
newUserAry[newUserAry.length - 1] = new User(id, pw, type);
userAry = newUserAry;
}
public void printList() {
for (User user:userAry)
System.out.println(user);
}
}
public class TestUserDB {
public static void main(String[] args) {
UserDB db=new UserDB();
db.addUser("a1", "a", 'a');
db.addUser("a2", "b", 'b');
db.addUser("a3", "c", 'a');
db.addUser("a4", "d", 'b');
db.printList();
}
}
Output:
User [id=a1, pw=a, type=a]
User [id=a2, pw=b, type=b]
User [id=a3, pw=c, type=a]
User [id=a4, pw=d, type=b]

Can't get my method to return anything [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
So, this is a class where I store data from another class called (Name)
the class (Name) got 3 informations. Name (String)/Number List /Adress List I used the last 2 as a List so I can allow multiple adresses/numbers
now the thing is, i can't get my getContact in this code to work, it doesn't return anything, so i thought that i messed up somewhere, checked everything and things were right, so i bypassed toString and printed an object of the type Namebook is my main method and it worked just fine.
public class Namebook {
private ArrayList<Name> contact;
private Name ctc;
public Namebook(){
contact = new ArrayList<Name>();
}
public void addContact(Name name){
this.contact.add(name);
}
public String getContact(){
return String.valueOf(this.contact);
}
#Override
public String toString() {
return String.valueOf(this.contact);
}
}
Class (Name)
public class Name {
private String name;
private List<String> number;
private List<String> Adress;
public Name(String name){
this.name = name;
}
public void addNumber(List<String> num){
this.number = num;
}
public void addAdress(List<String> adress){
this.Adress = adress;
}
public List<String> getNumber(){
return this.number;
}
public List<String> getAdress(){
return this.Adress;
}
public String toString() {
return this.name + " " + getNumber() + " " + getAdress() ;
}
}
Main
public class Main {
Scanner reader = new Scanner(System.in);
public static void main(String[] args) throws Exception {
Name person = new Name("sacha");
ArrayList<String> add = new ArrayList<String>();
ArrayList<String> num = new ArrayList<String>();
add.add("chicago");
num.add("13213223");
person.addNumber(num);
person.addAdress(add);
//System.out.println(person);
Namebook p1 = new Namebook();
p1.addContact(person);
p1.getContact();
}
}
Your toString and getContact methods are identical, and behave identically.
Case 1:
System.out.println(person);
This is short for
System.out.println(person.toString());
Case 2:
p1.getContact();
This is not short for anything. But notice that you do not have a System.out.println statement. That is what prints the output of the method. Without that, nothing is printed. To fix it
System.out.println(p1.getContact());

methods which return the general working experience [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
Can you explain me, how to solve this task as like pseudocode?
I try to write something but not sure about this
Create classes Employee and Manager with methods which return the general
working experience and payment for work done. Give your suggestion about
relations between classes(is-a, has-a, use-a, etc) Find solution for avoiding
of duplicate code. Write well commented code with examples of using these classes.
Wrire code for reading and writing collection of these objects from (into) file.
Find employee with maximal working experience.
Find employee with maximal payment.
Write code for handling the incorrect format of incoming file.
class Employee {
private String name;
private int experience;
private double payment;
// Getters and setters for the 3 attributes
public Employee(String name, int experience, double payment) {
this.name = name;
this.experience = experience;
this.payment = payment;
}
public class Manager extends Employee {
public Manager(String name, int experience, double payment) {
super(name, experience, payment);
}
Manager manager = new Manager("Sue", 23,3500);
Manager manager1 = new Manager("John", 22,3000);
Manager manager2 = new Manager("Q", 12, 3200);
public double maxPayment() {
double maxPayment = 0;
if(manager.getPayment() > manager1.getPayment() && manager.getPayment() > manager2.getPayment()) {
System.out.println(manager.getName());
}
else if(manager1.getPayment() > manager.getPayment() && manager1.getPayment() > manager2.getPayment()) {
System.out.println(manager1.getName());
}
else {
System.out.println(manager2.getName());
}
return maxPayment;
}
}
}
You have to set the methods maxPayment and maxExperience as static because they are not related to a particular instance, you'll need to create in your main method some employee/manager and give them to the method throught a list for ex:
public static double maxPayment(List<Employee> list) {
return list.stream().mapToDouble(Employee::getPayment).max().getAsDouble();
}
public static double maxExperience(List<Employee> list) {
return list.stream().mapToDouble(Employee::getExperience).max().getAsDouble();
}
public static void main(String[] args) {
Manager manager = new Manager("Sue", 23, 3500);
Manager manager1 = new Manager("John", 22, 3000);
Manager manager2 = new Manager("Q", 12, 3200);
Manager employee1 = new Manager("Fred", 2, 3000);
List<Employee> list = new ArrayList<>(Arrays.asList(manager, manager1, manager2,employee1));
System.out.println(Manager.maxPayment(list)); //3500.0
System.out.println(Manager.maxExperience(list)); //23.0
}
The way with for-loop would be :
public static double maxPayment(List<Employee> list) {
double maxPay = 0;
for (Employee e : list)
maxPay = Math.max(maxPay, e.getPayment());
return maxPay;
}

Instantiating two instances of a class [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I have a quick question
Suppose I were to create a data definition class named Campaign
and then I want to make an implementation class
Let's say in this implementation class I have a few variables(campaignName, campaignType, campaignGoal) and some methods (getCampName, getCampType, getCampGoal).
I want to create two different campaigns classes, and then compare their information at the end of the program with a print method.
Would this be a proper way of declaring information for the first campaign:
Campaign campaign1 = new Campaign();
which is in the main method, and then let's say I want to get the name of the first campaign, which is just hardcoded for now
public static String campaign1.getCampName(){
campaign1.setCampName("IT Student Scholarship Fund");
}
I just wanted to know how to do this. Thank you.
getCampName() should look something like:
public String getCampName() { return this.campaignName; }
a then simply
campaign1.getName();
You should stop the practice of putting all of your code in a main method. Instead, instantiate your Campaign instances and call methods on each one using a driver method in your primary class. In addition, you can override the equals() method to do the comparison (or implement Comparator).
public class CampaignTest{
public void runTest(){
Campaign c1 = new Campaign("First Campaign");
Campaign c2 = new Campaign("Second Campaign");
Campaign c11 = new Campaign("First Campaign");
System.out.println("c1==c2: " + c1.equals(c2));
System.out.println("c2==c11: " + c2.equals(c11));
System.out.println("c1==c11: " + c1.equals(c11));
}
public static void main(String... args){
CampaignTest test = new CampaignTest();
test.runTest();
}
private class Campaign{
private String name;
public Campaign(String n){
this.name = n;
}
public String getName(){
return name;
}
#Override
public boolean equals(Object other){
if(other instanceof Campaign && ((Campaign)other).getName().equals(name)){
return true;
}
return false;
}
}
}

Categories