I want the out put is like this:
Conan is NOT the same age as Natsu
this output program create the latest parameters.
Natsu is the same age as Natsu.
below is java program that I have made.
Syntax code that I have made
package rawrandomtest;
public class GetSet002 {
private static String name;
private static int age;
public GetSet002(String s, int i){
GetSet002.name = s;
GetSet002.age = i;
}
public String getName(){
return name;
}
public int getAge(){
return age;
}
public void setAge(int x){
GetSet002.age =x;
}
}
Driver Code
package rawrandomtest;
import java.util.Scanner;
public class GetSet002Driver {
public static Scanner input = new Scanner (System.in);
public static void main (String[] args){
GetSet002 p1 = new GetSet002("Conan", 14);
GetSet002 p2 = new GetSet002("Natsu", 18);
if(p1.getAge()==p2.getAge()){
System.out.println(p1.getName()+" is the same age as "+p2.getName());
}else{
System.out.println(p1.getName()+" is NOT the same age as "+p2.getName());
}
}
}
The age is a static variable. You change the value for all instances, every time you set the variable.
GetSet002 p1 = new GetSet002("Conan", 14);
//result: GetSet002 = ("Conan" , 14)
GetSet002 p2 = new GetSet002("Natsu", 18);
//result: GetSet = ("Natsu" , 18);
if(p1.getAge() == p2.getAge())
//is semantically equal to:
if(GetSet002.age == GetSet002.age)
//public accessiblity is only implied for demonstration
Related
How can I make two instances of a class, update the same array from that class? Like here, I want r1 and r2 to update same pendingOrders, so that finally the array is ['yo', 'lo']. That is not happening, the r1 and r2 are making different arrays.
import java.util.ArrayList;
public class Student{
static int enrollmentNumber;
String studentName;
Student(String name){
enrollmentNumber += 1;
studentName = name;
}
public String toString(){
return enrollmentNumber+": "+this.studentName;
}
public static void main(String[] args) {
Student s = new Student("Pam");
System.out.println(s.toString());
Student s1 = new Student("Hellooo");
System.out.println(s1.toString());
Student s2 = new Student("Pam2");
System.out.println(s2.toString());
Robot r1 = new Robot("Bob");
r1.addToQueue("yo");
System.out.println(r1.returnList()); // prints: ['yo']
Robot r2 = new Robot("Rob");
r2.addToQueue("lo");
System.out.println(r2.returnList()); // prints: ['lo']
// But I want it to print ['yo', 'lo']
}
}
class Robot{
public ArrayList<String> pendingOrders = new ArrayList<String>();
String rName;
Robot(String name){
rName = name;
}
public void addToQueue(String s){
pendingOrders.add(s);
}
public ArrayList returnList(){
return pendingOrders;
}
}
Add the static keyword to the pendingOrders in Robot.
Check this guide for more info
I have an issue at TestVolleyTeam.java. I cannot get the list arrays to work, I am honestly confused. I don't really know how to assign the lists with the "for" loop, I have probably made a mistake there.
The code is supposed to show the list of the players by using both the VolleyPlayer class and the VolleyTeam class through the TestVolleyTeam class. Can anyone spot the mistakes I've made?
class VolleyPlayer {
private String name;
private String surname;
private int flnum;
private int height;
public String getName() {
return name;
}
public String getSurname() {
return surname;
}
public int getFlnum() {
return flnum;
}
public int getHeight() {
return height;
}
public VolleyPlayer(String n, String sur, int fl, int h) {
name = n;
surname = sur;
flnum = fl;
height = h;
}
public VolleyPlayer(String n, String sur, int fl) {
this(n, sur, fl, 185);
}
public VolleyPlayer(String n, String sur) {
this(n, sur, 3);
}
public VolleyPlayer(String n) {
this(n, "Brown");
}
}
import java.util.ArrayList;
public class VolleyTeam {
private String teamname;
private String city;
private int year;
private ArrayList<VolleyPlayer> players;
public String getTeamname() {
return teamname;
}
public String getCity() {
return city;
}
public int getYear() {
return year;
}
public ArrayList<VolleyPlayer> getPlayers() {
return players;
}
public void setTeamname(String newTeamname) {
this.teamname = teamname;
}
public void setCity(String newCity) {
this.city = city;
}
public void setYear(int newYear) {
this.year = year;
}
public void setPlayers(ArrayList<VolleyPlayer> newPlayers) {
this.players = players;
}
}
import javax.swing.JOptionPane;
import java.util.Scanner;
import java.util.ArrayList;
public class TestVolleyTeam {
public static void main(String[] args) {
VolleyTeam myObj = new VolleyTeam();
String teamname = JOptionPane.showInputDialog(null, "What is the name of the team?", "Input");
myObj.setTeamname(teamname);
String city = JOptionPane.showInputDialog(null, "What is the city of the team?", "Input");
myObj.setCity(city);
String input = JOptionPane.showInputDialog(null, "What is the foundation year of the team?",
"Input");
int year = Integer.parseInt(input);
myObj.setYear(year);
myObj.getTeamname();
myObj.getCity();
myObj.getYear();
VolleyPlayer first = new VolleyPlayer("Michael", "Scott", 1, 175);
VolleyPlayer second = new VolleyPlayer("Jim", "Halpert", 2, 191);
VolleyPlayer third = new VolleyPlayer("Dwight", "Schrute", 3, 189);
VolleyPlayer fourth = new VolleyPlayer("Darryl", "Philbin", 4, 188);
VolleyPlayer fifth = new VolleyPlayer("Andy", "Bernard", 5, 182);
VolleyPlayer sixth = new VolleyPlayer("Oscar", "Martinez", 6, 173);
VolleyPlayer seventh = new VolleyPlayer("Stanley", "Hudson", 7, 180);
VolleyPlayer eighth = new VolleyPlayer("Kevin", "Malone", 8, 185);
VolleyPlayer ninth = new VolleyPlayer("Creed", "Bratton", 9, 183);
VolleyPlayer tenth = new VolleyPlayer("Toby", "Flederson", 10, 177);
ArrayList<VolleyPlayer> vplist = new ArrayList<VolleyPlayer>();
for (VolleyPlayer volleyPlayer : vplist) {
vplist.add(volleyPlayer);
}
myObj.getPlayers();
myObj.setPlayers(vplist);
ArrayList<VolleyPlayer> vplist2 = volleyTeam.getPlayers();
for (VolleyPlayer volleyPlayer : vplist2) {
vplist2.add(volleyPlayer);
}
volleyTeam.getPlayers();
volleyTeam.setPlayers(vplist2);
JOptionPane.showMessageDialog(null, vplist2, teamname + " " + city + ", " + year,
JOptionPane.INFORMATION_MESSAGE);
}
}
The List is empty when you start, this code
for (VolleyPlayer volleyPlayer : vplist) {
is attempted to loop over an empty List. I think I see what you want, and it can be achieved with something like
List<VolleyPlayer> vplist = new ArrayList<>(Arrays.asList(
first, second, third, fourth, fifth, sixth, seventh, eighth, ninth, tenth));
Then you don't need a loop to add first - tenth to your vplist. Note I changed it the diamond operator <> on construction. And used Arrays.asList to add the elements.
Since you must use a for loop, create an inline array. Like,
for (VolleyPlayer volleyPlayer : new VolleyPlayer[] {
first, second, third, fourth, fifth, sixth, seventh,
eighth, ninth, tenth }) {
I am new in java and I trying to get information
for five students and save them into an array of classes. how can I do this?
I want to use class person for five students whit different informations
import java.io.IOException;
import java.util.*;
public class exam
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
// I want to get and save information in this array
person[] f = new student[5];
}
}
class person defined for get name and family name.
import java.util.*;
public abstract class person {
Scanner scr = new Scanner(System.in);
private String name , fname;
public void SetName() {
System.out.println("enter name and familyNAme :");
name = scr.next();
}
public String getname() {
return name;
}
public void setfname () {
System.out.println("enter familyname:");
fname = scr.next();
}
public String getfname() {
return fname;
}
}
class student that inherits from the class person for get studentID and student Scores .
import java.util.*;
class student extends person {
float[] p = new float[5];
int id , sum ;
float min;
public void inputs() {
System.out.println("enter the id :");
id = scr.nextInt();
}
public void sumation() {
System.out.println("enter points of student:");
sum= 0;
for(int i = 0 ; i<5 ; i++){
p[i]=scr.nextFloat();
sum+=p[i];
}
}
public void miangin() {
min = (float)sum/4;
}
}
So first things first, when creating Java objects, refrain from getting input inside the object so that if you decide to change the way you get input (e.g. transition from command line to GUI) you don't need to modify the Java object.
Second, getters and setters should only get or set. This would save some confusion when debugging since we don't have to check these methods/functions.
So here's the person object:
public abstract class Person {
protected String name, fname;
public Person (String name, String fname) {
this.name = name;
this.fname = fname;
}
public void setName (String name) {
this.name = name;
}
public String getName () {
return name;
}
public void setFname (String fname) {
this.fname = fname;
}
public String getFname () {
return fname;
}
}
And here's the student object (tip: you can make as much constructors as you want to make object creation easier for you):
public class Student extends Person {
private float[] p;
private int id;
public Student (String name, String fname) {
this (name, fname, -1, null);
}
public Student (String name, String fname, int id, float[] p) {
super (name, fname);
this.id = id;
this.p = p;
}
public void setP (float[] p) {
this.p = p;
}
public float[] getP () {
return p;
}
public void setId (int id) {
this.id = id;
}
public int getId () {
return id;
}
public float summation () {
float sum = 0;
for (int i = 0; i < p.length; i++)
sum += p[i];
return sum;
}
public float miangin () {
return summation () / 4.0f;
}
#Override
public String toString () {
return new StringBuilder ()
.append ("Name: ").append (name)
.append (" Family name: ").append (fname)
.append (" Id: ").append (id)
.append (" min: ").append (miangin ())
.toString ();
}
}
And lastly, wherever your main method is, that is where you should get input from. Take note that when you make an array, each index is initialized to null so you still need to instantiate each array index before using. I made a sample below but you can modify it depending on what you need.
import java.util.*;
public class Exam {
Scanner sc;
Person[] people;
Exam () {
sc = new Scanner (System.in);
people = new Person[5];
}
public void getInput () {
for (int i = 0; i < people.length; i++) {
System.out.print ("Enter name: ");
String name = sc.nextLine ();
System.out.print ("Enter family name: ");
String fname = sc.nextLine ();
System.out.print ("Enter id: ");
int id = sc.nextInt (); sc.nextLine ();
System.out.println ("Enter points: ");
float[] points = new float[5];
for (int j = 0; j < points.length; j++) {
System.out.printf ("[%d] ", j + 1);
points[j] = sc.nextFloat (); sc.nextLine ();
}
people[i] = new Student (name, fname, id, points);
}
}
public void printInput () {
for (Person p: people)
System.out.println (p);
}
public void run () {
getInput ();
printInput ();
}
public static void main (String[] args) {
new Exam ().run ();
}
}
Just one last tip, if you ever need dynamic arrays in Java, check out ArrayList.
You can add a class attribute, and then add class information for each student, or you can add a class class, define an array of students in the class class, and add an add student attribute, and you can add students to that class.
First of all, please write class names with capital letter (Student, Exam <...>).
Exam class:
import java.util.Scanner;
public class Exam {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Student[] students = new Student[]{
new Student(),
new Student(),
new Student(),
new Student(),
new Student()
};
for (int i = 0; i < 5; i++) {
students[i].setFirstName();
students[i].setLastName();
students[i].setId();
}
}
}
Person class:
import java.util.Scanner;
public class Person {
String firstName, lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName() {
System.out.println("Type firstName: ");
this.firstName = new Scanner(System.in).next();
}
public String getLastName() {
return lastName;
}
public void setLastName() {
System.out.println("Type lastName: ");
this.lastName = new Scanner(System.in).next();
}
}
Student class:
import java.util.Scanner;
public class Student extends Person{
int id;
public int getId() {
return id;
}
public void setId() {
//Converting String line into Integer by Integer.parseInt(String s)
System.out.println("Type id: ");
this.id = Integer.parseInt(new Scanner(System.in).next());
}
}
I have some problem with my simple code in Java. I want to do aircraft flight search program, but when I leave the variable under the parameter, I get an error:
Airlines.java:14: error: int cannot be dereferenced
String Parameters = flightNumber_go.getParameters();
Anyone have any idea how I could solve this problem?
PS. Sorry for my bad English
import java.util.Scanner;
class Airlines{
public static void main(String args[]) throws Exception{
Flight 524 = new Flight("Moskwa", "Londyn", 140);
Flight 135 = new Flight("Warszawa", "Wroclaw", 60);
Flight 141 = new Flight("Frankfurt", "Rzym", 95);
Scanner flightNumber = new Scanner(System.in);
System.out.println("Enter code of your flight: ");
int flightNumber_go = Integer.valueOf(flightNumber.nextLine());
String Parameters = flightNumber_go.getParameters();
System.out.println(Parameters);
}
}
class Flight{
String departures;
String arrival;
int price;
public Flight(String departures, String arrival, int price){
this.departures = departures;
this.arrival = arrival;
this.price = price;
}
public String getParameters(String ... args){
return "Lot z "+this.departures+" do "+this.arrival+" kosztuje "+this.price;
}
}
To begin with you are misunderstanding how to correctly use an Object as getParameters will only work for the current object, it will not search all the objects you made. You must use a Collection to keep track on all of your objects if you want to find a specific one.
Additionally you should not use variable names to store information, instead store that information inside of the object as an integer.
Here is the modified Flight class:
class Flight {
private String departures;
private String arrival;
private int price;
private int flightNum;
public Flight(String departures, String arrival, int price, int flightNum){
this.departures = departures;
this.arrival = arrival;
this.price = price;
this.flightNum = flightNum;
}
public String getParameters(){
return "Lot z "+this.departures+" do "+this.arrival+" kosztuje "+this.price;
}
public String getDepartures() {
return departures;
}
public String getArrival() {
return arrival;
}
public int getPrice() {
return price;
}
public int getFlightNum() {
return flightNum;
}
public void setDepartures(String departures) {
this.departures = departures;
}
public void setArrival(String arrival) {
this.arrival = arrival;
}
public void setPrice(int price) {
this.price = price;
}
public void setFlightNum(int flightNum) {
this.flightNum = flightNum;
}
}
Note that I added the new parameter, flightNum and made all of your class variables private, with standard getters and setters for access.
Now here is the modified Airlines class that uses an ArrayList to store the Flights:
class Airlines {
public static void main(String args[]) throws Exception{
ArrayList<Flight> flights = new ArrayList<>();
flights.add(new Flight("Moskwa", "Londyn", 140, 524));
flights.add(new Flight("Warszawa", "Wroclaw", 60, 135));
flights.add(new Flight("Frankfurt", "Rzym", 95, 141));
Scanner flightNumber = new Scanner(System.in);
System.out.println("Enter code of your flight: ");
int flightNumber_go = Integer.valueOf(flightNumber.nextLine());
Flight currentFlight = findFlight(flights, flightNumber_go);
System.out.println(currentFlight.getParameters());
}
public static Flight findFlight(ArrayList<Flight> flights, int flightNum) {
for (Flight f : flights) {
if (f.getFlightNum() == flightNum) {
return f;
}
}
//If no flights are found
return null;
}
}
I added a static method called findFlight which takes in the ArrayList and flightNumber you want to find as a parameter, and returns the corresponding Flight. This is done using a simple enhanced for loop. The method will return null if no flight is found, which can modified to return whatever you want for a default case.
Example Run:
Enter code of your flight:
135
Lot z Warszawa do Wroclaw kosztuje 60
Note: It may make sense in your case to use a Map to store the key as the flight number with the Flight as the value which ensures the key is unique and then you do not need flightNumber in the Object itself. This ArrayList is just one way to do it.
I am trying to write a program where I ask to the user how many persons he wants to implement in this world. Afterwards, I would like as many person objects as the user answered. I defined a person class with a person constructor containing all person variables ( + getters/setters). After this, I tried to create a loop to assign values to my variables (most of them happen random). Currently, I set the number of instances I want to create to 20 (arbitrary).
This is my person class
public class Person implements Item {
public static final int MAX_AGE = 70;
public static final int MAX_SEX_APPEAL = 10;
public static final int MAX_AGRESSION_LEVEL = 10;
public static final int MAX_STRENGTH = 10;
private int id;
private int age;
private boolean gender;
private int sexAppeal;
private int agressionLevel;
private int strength;
private boolean isAlive;
public Person (int id, int age, boolean gender, int sexAppeal, int agressionLevel, int strength, boolean isAlive){
this.setId(id);
this.setAge(age);
this.setGender(gender);
this.setSexAppeal(sexAppeal);
this.setAgressionLevel(agressionLevel);
this.setStrength(strength);
this.setAlive(isAlive);
}
void getBorn () {
isAlive = true;
age = 0;
// a new people is born
// age = 0
// other variables: random
}
void die () {
isAlive = false;
// people die when they reach the max age
// people die when being on the same cell as vulcanos
// people can be murdered
// setAlive = false
}
void murder () {
// when 2 people with min agression level on the same land ==> weakest one dies
}
void move () {
// method to make people move
// random (only to adjucant fields)
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public boolean isGender() {
return gender;
}
public void setGender(boolean gender) {
this.gender = gender;
}
public int getSexAppeal() {
return sexAppeal;
}
public void setSexAppeal(int sexAppeal) {
this.sexAppeal = sexAppeal;
}
public int getAgressionLevel() {
return agressionLevel;
}
public void setAgressionLevel(int agressionLevel) {
this.agressionLevel = agressionLevel;
}
public int getStrength() {
return strength;
}
public void setStrength(int strength) {
this.strength = strength;
}
public boolean isAlive() {
return isAlive;
}
public void setAlive(boolean isAlive) {
this.isAlive = isAlive;
}
}
And this is my "test class" where I try to create 20 instances :
import java.util.concurrent.ThreadLocalRandom;
public class test {
public static void main(String[] args) {
for (int i = 0; i < 20; i ++) {
Person person(i) = new Person();
person.setId(i);
person.setAge(ThreadLocalRandom.current().nextInt(0, Person.MAX_AGE + 1));
person.setGender((Math.random() < 0.5));
person.setSexAppeal(ThreadLocalRandom.current().nextInt(0, Person.MAX_SEX_APPEAL + 1));
person.setAgressionLevel(ThreadLocalRandom.current().nextInt(0, Person.MAX_SEX_APPEAL + 1));
person.setStrength(ThreadLocalRandom.current().nextInt(0, Person.MAX_SEX_APPEAL + 1));
person.setAlive(true);
}
}
}
However, I am getting the following error at this line
Person person(i) = new Person();
The constructor Person () is undefined
Type mismatch: cannot convert from Person to int
I understand those errors but I don't know another way to become to the result I want to achieve
You should make a list and just add the created persons to it.
public class test {
public static void main(String[] args) {
List<Person> persons = new ArrayList<>(); // create a list to store the generated persons
for (int i = 0; i < 20; i++) {
Person person = new Person(); // generate a person
person.setId(i);
person.setAge(ThreadLocalRandom.current().nextInt(0, Person.MAX_AGE + 1));
person.setGender((Math.random() < 0.5));
person.setSexAppeal(ThreadLocalRandom.current().nextInt(0, Person.MAX_SEX_APPEAL + 1));
person.setAgressionLevel(ThreadLocalRandom.current().nextInt(0, Person.MAX_SEX_APPEAL + 1));
person.setStrength(ThreadLocalRandom.current().nextInt(0, Person.MAX_SEX_APPEAL + 1));
person.setAlive(true);
persons.add(person); /// add the generated person to the list
}
}
}
Also if you want to call the Person constructor without parameters the class must have a constructor that takes no parameters.
public Person() {}