This is my object class
class Baller
{
public String name;
public double height;
public double weight;
public String country;
public Baller()
{
name = "";
height = 0;
weight = 0;
country = "";
}
public Baller(String name1, double height1, double weight1, String country1)
{
}
public String getName()
{
return name;
}
public double getHeight()
{
return height;
}
public double getWeight()
{
return weight;
}
public String getCountry()
{
return country;
}
}
I need to create a arraylist that adds the name, height, weight and country of each player.
This is how i initialized it:
ArrayList<Baller> playersNames = new ArrayList<>();
This is where i add the player information:
System.out.println("What player would you like to add (Enter Name, Height, Weight and Country)");
String name = TextIO.getlnString();
double height = TextIO.getlnDouble();
double weight = TextIO.getlnDouble();
String country = TextIO.getlnString();
players = new Baller(name, height, weight, country);
playersNames.add(players);
This is how i try to print the arraylist
System.out.println("The roster is:"+playersNames);
When I print it out its says: Baller#13bad12
To output the name, use :
System.out.println("The roster is:" + players.getName());
What you need to know with object is that when you try to print them directly, the toString() method will be called.
In the case of your Baller object, it is not defined so the reference is printed. You can override it to output the name if you want :
#Override
public String toString()
{
return this.getName();
}
Then
System.out.println("The roster is:" + players); would work.
Edit : To print all the player values, simply concatenate them to the return String :
#Override
public String toString()
{
return "Name : " + this.getName() + ", Height : " + this.getHeight() + ", Weight : " + this.getWeight() + ", Country : " + this.getCountry();
}
Related
I am having class about java, and There is a assignment that I must do, but I am stuck. lol
This is what she asked:
Write a java blueprint class that models an Airline Reservation and adheres to the following
criteria:
o5 instance variables: first name, last name, flight number, seat number , ticket number
oA default constructor
oA constructor that takes five arguments
oA setter and getter for each field that simply sets and gets the field value.
oA method called “retrieveSeatingClass” which returns a “seating class” for each seat number (use
a switch statement)
▪seats 1-2: First Class
▪seats 3-4: Second Class
▪seats 5-6 Third Class
▪seats 7-8: Fourth Class
I did it. But now in the main class, she wants me to call the result. And I am struggling to do it. Here follows my code.
Entered code here:
public class AirlineReservation {
String firstName;
String lastName;
String flightNumber;
int seatNumber;
int ticketNumber;
public AirlineReservation() {
}
public AirlineReservation(String firstName, String lastName, String flightNumber, int seatNumber,
int ticketNumber) {
this.firstName = firstName;
this.lastName = lastName;
this.flightNumber = flightNumber;
this.seatNumber = seatNumber;
this.ticketNumber = ticketNumber;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setFlightNumber(String flightNumber) {
this.flightNumber = flightNumber;
}
public void setSeatNumber(int seatNumber) {
this.seatNumber = seatNumber;
}
public void setTicketNumber(int ticketNumber) {
this.ticketNumber = ticketNumber;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getFlightNumber() {
return flightNumber;
}
public int getSeatNumber() {
return seatNumber;
}
public int getTicketNumber() {
return ticketNumber;
}
public String retrieveSeatingClass() {
int classNumber = seatNumber;
switch (classNumber) {
case 1:
case 2:
System.out.println("First Class");
break;
case 3:
case 4:
System.out.println("Second Class");
break;
case 5:
case 6:
System.out.println("Third Class");
break;
case 7:
case 8:
System.out.println("Fourth Class");
break;
}
return "seat";
}
import java.util.Scanner;
public class AirlineReservationTestHarness {
public static void main (String[ ]args) {
AirlineReservation passager1 = new AirlineReservation("Raquel","Cristina", "400", 1, 456789);
System.out.println("Passager: " + passager1.getFirstName());
System.out.println("Last name: " + passager1.getLastName());
System.out.println("Flight Number" + passager1.getFlightNumber());
System.out.println("Seat: " + passager1.getSeatNumber());
System.out.println("Your ticket number is: " + passager1.getTicketNumber());
`enter code here` System.out.println("Your data is: " + passager1.getFirstName() + assager1.getLastName() + passager1.getFlightNumber() + passager1.getSeatNumber() + passager1.getTicketNumber() + " and your in a " + );
}
}
In my main, how do I call it for when the seat it 1 it appears First Class?
SQlite Data is not updating into listview. no error showing just not save the edited value. when I click the list view it will open with the inserted value to edit but when I push the update button it won't update. Any Solution for my Problem ??
ListDataActivity.java
listView = findViewById(R.id.listViewId);
loadData();
}
public void loadData() {
//Create an arraylist so that i can load the data to add in the arraylist
ArrayList<String> listData = new ArrayList<>();
Cursor cursor = databaseHelper.showAllData();
//jodi kono cursor e row na thake
if (cursor.getCount() == 0) {
Toast.makeText(getApplicationContext(), "no data is available", Toast.LENGTH_LONG).show();
} else {
while (cursor.moveToNext()) {
listData.add(cursor.getString(1) + " \t " + cursor.getString(2));
}
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.textViewId, listData);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
String selectedValue = adapterView.getItemAtPosition(position).toString();
cursor.moveToPosition(position);
String name = cursor.getString(1);
String surName = cursor.getString(2);
// listData.add(cursor.getString(1) + " \t " + cursor.getString(2));
Intent intent = new Intent(ListDataActivity.this, UpdateActivity.class);
Toast.makeText(getApplicationContext(), "Selected Value : " + selectedValue, Toast.LENGTH_LONG).show();
intent.putExtra("id", id);
intent.putExtra("name", name);
intent.putExtra("surName", surName);
startActivity(intent);
finish();
}
});
UpdateActivity.java
id = getIntent().getExtras().getLong("id");
String name = getIntent().getExtras().getString("name");
String surName = getIntent().getExtras().getString("surName");
updateName.setText(name);
updatePhone.setText(surName);
updateButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
String name = updateName.getText().toString();
String surName = updatePhone.getText().toString();
if(view.getId()==R.id.updatebuttonId){
ListDataActivity.databaseHelper.updateInformation(id,name,surName);
startActivity(new Intent(UpdateActivity.this,ListDataActivity.class));
finish();
}
}
});
DatabaseHelper.Java
public int updateInformation(long id, String name, String surName) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(NAME,name);
contentValues.put(SURNAME,surName);
String whereArgs[] = {""+id};
int count = sqLiteDatabase.update(TABLE_NAME,contentValues,NAME+ "=?",whereArgs);
return count;
}
I believe that your issue is that you are trying to update using a WHERE clause that is effectively saying update the row where the NAME = the id that has been passed (likely to never find such a row).
You need to change the 3rd parameter passed to the update method to be the name of the id column. So you want something like :-
int count = sqLiteDatabase.update(TABLE_NAME,contentValues,ID+ "=?",whereArgs); //<<<<< ID instead of NAME
Note the above assumes that the String Constant ID contains the name of the id column. So you may have to change ID accordingly.
I have to create an appropriate GUI to enter information for at least 10 employee. for each employee i have to enter the following information. employee ID, employee first name, employee last name and yearly salary. besides i have to check for the correctness of the input data. in addition i need to create a separate class EMPLOYEE, containing employee information: employee ID, first name , last name and yearly salary. the class should have constructors properties and methods. all the employee information has to be stored in a array of type employee. after reading form GUI the information about particular employee , also create an object of class employee(element of the array) with the relevant constructor. the user would like to be able to find the employee with lowest yearly salary despite of having more than one employee with lowest yearly salary. and display information about them. user should be provided with appropriate GUI to display the required information.
i need to assure including in my program appropriate code for handling exceptions and also methods where appropriate.
here is the class employee:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Project_employee
{
class Employee
{
private int employeeID;
private string fullName;
private string lastName;
private double salary;
public Employee()
{
employeeID = 0;
fullName = "";
lastName = "";
salary = 0.0;
}
public Employee(int empIDValue, string fullNameVal, string lastNameVal)
{
employeeID = empIDValue;
fullName = fullNameVal;
lastName = lastNameVal;
salary = 0.0;
}
public Employee(int empIDValue, string fullNameVal, string lastNameVal, double salaryValue)
{
employeeID = empIDValue;
fullName = fullNameVal;
lastName = lastNameVal;
salary = salaryValue;
}
public int EmployeeIDNum
{
get
{
return employeeID;
}
set
{
employeeID = value;
}
}
public string FullName
{
get
{
return fullName;
}
set
{
fullName = value;
}
}
public int Getinfo
{
get
{
return employeeID;
}
set
{
employeeID = value;
}
}
public string employeeInformationToString()
{
// employeeID = Convert.ToInt32(this.textBox1.Text);
return (Convert.ToString(employeeID) + " " + fullName + " " + lastName + " " + Convert.ToString(salary));
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Project_employee
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
}
private void Searchbtn_Click(object sender, EventArgs e)
{
employee[0] = new Employee();
employee[1] = new Employee(17433, "Adrian", "Smith", 8000.00);
employee[2] = new Employee(17434, "Stephen", "Rad", 9000.00);
employee[3] = new Employee(17435, "Jesse", "Harris", 800.00);
employee[4] = new Employee(17436, "jonatan", "Morris", 9500.00);
employee[5] = new Employee(17437, "Morgen", "Freeman", 12000.00);
employee[6] = new Employee(17438, "Leory", "Gomez", 10200.00);
employee[7] = new Employee(17439, "Michael", "Brown", 9000.00);
employee[8] = new Employee(17440, "Andrew", "White", 3500.00);
employee[9] = new Employee(17441, "Maria", "Carson", 12000.00);
//employee[10] = new Employee(17442, "Mark", "Jonson", 17000.00);
for(int i = 0; i < 10; i++)
{
string employeeString = employee[i].employeeInformationToString() + "\r\n";
richTextBox1.AppendText(employeeString);
}
}
Employee[] employee = new Employee[10];
private void getinfibtn_Click(object sender, EventArgs e)
{
Find();
}
private void Find()
{
}
}
}
My question is:
How the user can find the employee with the lowest yearly salary. i have to make sure that there can be more than one employee with lowest yearly salary and display the information about them. providing the user with an appropriate GUI (e.g a message box) to display the required information with including appropriate code for handling exceptions and also use methods where appropriate?
You need to make your class Employee to implement the IComparable interface, then compare the objects against the salary and in the other class sort the array...
Example:
public class Employee :IComparable<Employee>
{
private int employeeID;
private string fullName;
private string lastName;
private double salary;
public int CompareTo(Employee other)
{
return salary.CompareTo(other.salary);
}
}
private void Find()
{
Array.Sort(employee); // after this Employee is sorted
employee[0];
or
employee[9];
}
this will give a list of lowest salary emplyees
employee.Add(new Employee(17434, "Stephen", "Rad", 9000.00));
employee.Add(new Employee(17435, "Jesse", "Harris", 800.00));
employee.Add(new Employee(17436, "jonatan", "Morris", 9500.00));
var c = employee.OrderBy(i => i.salary).ToList();
var e = employee.Where(i => Math.Abs(i.salary - c[0].salary) < 1).ToList();
Modified you code a little bit
class Employee
{
private int employeeID;
private string fullName;
private string lastName;
private double salary;
public double Salary
{
get
{
return salary;
}
set
{
salary = value;
}
}
//public Employee()
//{
// employeeID = 0;
// fullName = "";
// lastName = "";
// salary = 0.0;
//}
//public Employee(int empIDValue, string fullNameVal, string lastNameVal)
//{
// employeeID = empIDValue;
// fullName = fullNameVal;
// lastName = lastNameVal;
// salary = 0.0;
//}
public Employee(int empIDValue, string fullNameVal, string lastNameVal, double salaryValue)
{
employeeID = empIDValue;
fullName = fullNameVal;
lastName = lastNameVal;
salary = salaryValue;
}
public int EmployeeIDNum
{
get
{
return employeeID;
}
set
{
employeeID = value;
}
}
public string FullName
{
get
{
return fullName;
}
set
{
fullName = value;
}
}
public int Getinfo
{
get
{
return employeeID;
}
set
{
employeeID = value;
}
}
public string employeeInformationToString()
{
// employeeID = Convert.ToInt32(this.textBox1.Text);
return (Convert.ToString(employeeID) + " " + fullName + " " + lastName + " " + Convert.ToString(salary));
}
}
and to get min values in list
var minEmpSalarylist = employee.Where(x => x.Salary == employee.Min(y => y.Salary)).ToList();
If default constructor is present then all minEmpSalarylist become initialized with default constructor.
and
employee[0] = new Employee();
to change it to
employee[0] = new Employee(17433, "XXX", "YYY", 8000.00);
I am creating some forms and I need to create masks and validation for some fields.
Is it implemented in anyway in JavaFX?
My example of the mask.
Using:
<MaskField mask="+7(DDD)DDD-DDDD"/>
<MaskField mask="AA DDD AAA" placeholder="__ ### ___"/>
etc
Restricting input from Richard's fxexperience post:
TextField field = new TextField() {
#Override public void replaceText(int start, int end, String text) {
// If the replaced text would end up being invalid, then simply
// ignore this call!
if (!text.matches("[a-z]")) {
super.replaceText(start, end, text);
}
}
#Override public void replaceSelection(String text) {
if (!text.matches("[a-z]")) {
super.replaceSelection(text);
}
}
};
If you want to create your use a mask and create your own control, take a look at Richard's MoneyField, which also includes a sample project and source. Along the same lines there are controls to restict input to Integers, Doubles or formatted web colors (e.g. #rrggbb) in the fxexperience repository. All of these follow a common theme where they subclass Control, provide some properties to be get and set which define the public interface and then also define a private backing skin which handles rendering of the UI based on the values set through the public interface.
I had the same needs. I created this field, called it SpecialTextField, and pushed into GitHub. Example also there. Hope this help.
NOTE: this only works correctly with JRE 1.8.0_25 or lower. With JRE 1.8.0_48 or 0_51, the caret position is always set to 0 after each character input.
No, this is not implemented in standard JavaFX. You need to use some library or do it yourself.
This is my implementation of static mask for text fields. It works for date, phone and other types of static masks:
/**
* Adds a static mask to the specified text field.
* #param tf the text field.
* #param mask the mask to apply.
* Example of usage: addMask(txtDate, " / / ");
*/
public static void addMask(final TextField tf, final String mask) {
tf.setText(mask);
addTextLimiter(tf, mask.length());
tf.textProperty().addListener(new ChangeListener<String>() {
#Override
public void changed(final ObservableValue<? extends String> ov, final String oldValue, final String newValue) {
String value = stripMask(tf.getText(), mask);
tf.setText(merge(value, mask));
}
});
tf.setOnKeyPressed(new EventHandler<KeyEvent>() {
#Override
public void handle(final KeyEvent e) {
int caretPosition = tf.getCaretPosition();
if (caretPosition < mask.length()-1 && mask.charAt(caretPosition) != ' ' && e.getCode() != KeyCode.BACK_SPACE && e.getCode() != KeyCode.LEFT) {
tf.positionCaret(caretPosition + 1);
}
}
});
}
static String merge(final String value, final String mask) {
final StringBuilder sb = new StringBuilder(mask);
int k = 0;
for (int i = 0; i < mask.length(); i++) {
if (mask.charAt(i) == ' ' && k < value.length()) {
sb.setCharAt(i, value.charAt(k));
k++;
}
}
return sb.toString();
}
static String stripMask(String text, final String mask) {
final Set<String> maskChars = new HashSet<>();
for (int i = 0; i < mask.length(); i++) {
char c = mask.charAt(i);
if (c != ' ') {
maskChars.add(String.valueOf(c));
}
}
for (String c : maskChars) {
text = text.replace(c, "");
}
return text;
}
public static void addTextLimiter(final TextField tf, final int maxLength) {
tf.textProperty().addListener(new ChangeListener<String>() {
#Override
public void changed(final ObservableValue<? extends String> ov, final String oldValue, final String newValue) {
if (tf.getText().length() > maxLength) {
String s = tf.getText().substring(0, maxLength);
tf.setText(s);
}
}
});
}
See also:
JavaFX 2.2 TextField maxlength
Supported by current javafx-2 platform by default - No, but go through this link , it has many insights and sample code for Form validation in javaFX
public class NumberTextField extends TextField {
private int maxLenght;
public NumberTextField(int maxLenght) {
super();
this.maxLenght = maxLenght;
}
#Override
public void replaceText(int start, int end, String text) {
if (validate(text)) {
super.replaceText(start, end, text);
}
}
#Override
public void replaceSelection(String text) {
if (validate(text)) {
super.replaceSelection(text);
}
}
private boolean validate(String text) {
if (this.getText() != null) {
}
boolean status = ("".equals(text) || text.matches("[0-9]"));
if (this.getText() == null) {
return status;
} else {
return (status && this.getText().length() < maxLenght);
}
}
}
In some cases I would validate the text property:
myTextField
.textProperty()
.addListener(
(obs, oldVal, newVal) ->
{
if(!newVal.matches("\\d+"))
textField.setText(oldV);
});
Unlucky: textField.setText(oldV); will enter the same function again, testing unnecessarily if oldVal matches.
If the TextField becomes a value that doesn't matches before this listener is added to the TextField, enter a not matching new value will cause a loop!!!
To avoid this, it will be safer to write:
String acceptableValue = "0";
myTextField
.textProperty()
.addListener(
(obs, oldVal, newVal) ->
{
if(!newVal.matches("\\d+"))
textField.setText(oldVal.matches("\\d+") ? oldV : acceptableValue);
});
I wrote a class that extends the TextField and apply the mask.
package com.model;
import java.text.NumberFormat;
import java.util.Locale;
/**
* ATENTION
* DO NOT FORGUET TO IMPORT IN FXML
* <?import com.view.TextFieldMoney?>
*
* */
import javafx.scene.control.TextField;
public class TextFieldMoney extends TextField {
private int maxlength;
private String valor = "";
public TextFieldMoney() {
this.maxlength = 11;
}
public void setMaxlength(int maxlength) {
this.maxlength = maxlength;
}
#Override
public void replaceText(int start, int end, String text) {
// Delete or backspace user input.
if (getText() == null || getText().equalsIgnoreCase("")) {
valor = "";
}
if (text.equals("")) {
super.replaceText(start, end, text);
} else{
text = text.replaceAll("[^0-9]", "");
valor += text;
super.replaceText(start, end, text);
if (!valor.equalsIgnoreCase(""))
setText(formata(valor));
}
}
#Override
public void replaceSelection(String text) {
// Delete or backspace user input.
if (text.equals("")) {
super.replaceSelection(text);
} else if (getText().length() < maxlength) {
// Add characters, but don't exceed maxlength.
// text = MascaraFinanceira.show(text);
if (text.length() > maxlength - getText().length()) {
// text = MascaraFinanceira.show(text);
text = text.substring(0, maxlength - getText().length());
}
super.replaceSelection(text);
}
}
/*
*Return the number without money mask
**/
public String getCleanValue(){
String cleanString = getText().replaceAll("[^0-9]", "");
Double cleanNumber = new Double(cleanString);
return String.valueOf(cleanNumber/100);
}
private String formata(Double valor) {
Locale locale = new Locale("pt", "BR");
NumberFormat nf = NumberFormat.getInstance(locale);
nf.setMaximumFractionDigits(2);
nf.setMinimumFractionDigits(2);
return nf.format(valor);
}
public String formata(String valor) {
double v = new Double(valor);
return formata(v/100);
}
}
And in the FXML where is
<TextField fx:id="valorTextField" GridPane.columnIndex="2" GridPane.rowIndex="2" />
put
<TextFieldMoney fx:id="valorTextField" GridPane.columnIndex="2" GridPane.rowIndex="2" />
Please don't get mad, I am amiting this is help on my homework but I like to learn this and can't find it anywhere. I have looked for it and couldn't find anything like it, idk if I am looking in all the wrong places or for the wrong thing I have two other classes inside my code and having trouble creating another class with class objectives inside of it, I will show what I attempted and see if yall can please help me out. Also, I want to make sure I am using the keyword " this" right in my other two classes. She wanted us to use this in our program and the comments are what we are told to do:
public class Person
{
private String lastName;
private String firstName;
//default constructor
public Person()
{
lastName= null;
firstName = null;
}
//two-parameter constructor
public Person(String lastName, String firstName)
{
this.lastName=lastName;
this.firstName=firstName;
}
//copy constructor
public Person(Person object2)
{
this.lastName=object2.lastName;
this.firstName=object2.firstName;
}
// standard accessor method for each of the two fields
public String getLastName(String lastName)
{
lastName = this.lastName;
return lastName;
}
public String getFirstName(String firstName)
{
firstName = this.firstName;
return firstName;
}
public void setLastName(String lastName)
{
this.lastName=lastName;
}
public void setFirstName(String firstName)
{
this.firstName=firstName;
}
//mutator method for both fields—using standard mutator methods
public void setName(String lastName,String firstName)
{
this.lastName= lastName;
this.firstName = firstName;
}
//toString method
public String toString()
{
String str = “Last Name: “ + lastName + “\nFirst Name: “ + firstName;
return str;
}
//equals method
public boolean equals(Person name2)
{
boolean status;
if (this.lastName.equals(name2.lastName) && this.firstName.equals(name2.firstName))
status = true;
else
status = false;
return status;
}
//copy method
public Person copy()
{
Person copyObject = new Person(lastName, firstName);
return copyObject;
}
}
public class Date
{
private int month;
private int day;
private int year;
//default constructor
public Date()
{
this (0,0,0);
}
//three-parameter constructor
public Date(int month, int day, int year)
{
this.month = month;
this.day = day;
this.year = year;
}
//copy constructor
public Date(Date object2)
{
this (object2.month, object2.day, object2.year);
}
//standard accessor method for each field
public int getMonth(int month)
{
month = this.month;
return month;
}
public int getDay(int day)
{
day = this.day;
return day;
}
public int getYear(int year)
{
year = this.year;
return year;
}
//standard mutator method for each field
public void setMonth(int month)
{
this.month = month;
}
public void setDay(int day)
{
this.day = day;
}
public void setYear(int year)
{
this.year = year;
}
//mutator method for both fields—using standard mutator methods
public void setDate(int month, int day, int year)
{
this.month = month;
this.day = day;
this.year= year;
}
//toString method
public String toString()
{
String str = "Date:" + month+ " " + day + ", " + year;
return str;
}
//equals method
public boolean equals (Date object2)
{
boolean status;
if (this.month == object2.month && this.day == object2.day && this.year == object2.year)
status = true;
else
status = false;
return status;
}
//copy method
public Date copy()
{
Date copyObject = new Date(month, day, year);
return copyObject;
}
}
And this is what I have been trying for my other class and It shows an ERROR:
public class PersonalInfo
{
private Person name;
private Date birthday;
private int idNumber;
// the default constructor
public PersonalInfo()
{
Person name = new Person();
Date birthday = new Date();
this.idNumber = 0;
}
// A constructor that passes 6 parameters
public PersonalInfo(String lastName, String firstName, int month, int day, int year, int idNumber )
{
Person name = new Person(lastName, firstName);
Date birthday= new Date(month, day, year);
this.idNumber = idNumber;
}
}
Please help! And thank you for looking
Since you haven't specified the language or the error message, this is only a qualified guess. If this isn't the actual problem, provide more details.
public PersonalInfo()
{
Person name = new Person();
Date birthday = new Date();
this.idNumber = 0;
}
You are declaring new local variables name and birthday here, rather than using the class members. That means the class members never get initialized, and I suspect that's what the error is trying to tell you.
The right way to do this is to just refer directly to the variables:
this.name = new Person();
this.birthday = new Date();
or, since this is implied when there is no local variable or parameter with the same name:
name = new Person();
birthday = new Date();