I am a JAVA beginner, and I've done some research. It turned out there is no such a way to deal with this problem. I'm assigned to design a prompt command with multiple data inputs, with only one scanner object.
Now, I've already achieved the following:
Set an array for saving the NimPlayer object.
Set the NimPlayer class for creating a unique NimPlayer object.
Set the counter, used as an index.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print('$');
String input = in.next();
// initialize an array
NimPlayer [] playerList = new NimPlayer[10];
// create a position in the array
int addUserCount = 0;
if (input.equals("addplayer")) {
String userName = in.next();
String familyName = in.next();
String givenName = in.next();
addUserCount +=1;
playerList[addUserCount] = new NimPlayer(userName, familyName, givenName);
}
public class NimPlayer {
String userName;
String familyName;
String givenName;
public NimPlayer(String userName,String surName, String givenName) {
this.userName = userName;
this.familyName = surName;
this.givenName = givenName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public void setFamilyName(String familyName) {
this.familyName = familyName;
}
public void setGivenName(String givenName) {
this.givenName = givenName;
}
public String getUserName() {
return userName;
}
public String getfamilyName() {
return familyName;
}
public String getGivenName() {
return givenName;
}
}
the goal is to design like this:
addplayer userName,familyName,givenName
So, that's why I use next() to identify the first word, and space is the default delimiter.
I am not sure how to do next. What should I do to add a feature that separates the inputs using ",".
Any help is appreciated.
You can read lines with Scanner.nextLine(). Here is an example how you can type "username, surname, givenname" in one line and get splitted by String.split(",").
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String line = s.nextLine();
String[] splittedLine = line.split(",");
for(int i = 0; i < splittedLine.length; i++) {
System.out.printf("splitted line: %d. %s \n", i, splittedLine[i].trim());
}
}
Input:
name, surename, username
Output:
splitted line: 1. name
splitted line: 2. surename
splitted line: 3. username
Related
I'm trying to create this payroll system which has a login class and a salary-calculator class. I'm trying to use the username string entered by the user in the login class in the salary calculator class to determine the basic salary, but the username string is treated as null in the salary-calculator class hence I'm getting a lot of errors. I'm quite new to java programming so I would highly appreciate your help. Here is my code.
public class loginpage {
Scanner x; // declares scanner
static String name;
static String username;
public void username(){
String filepath = "/home/ogweno/NetBeansProjects/Payroll System/src/payroll/system/employees.txt"; // Declaring the filepath
// Declaring a string for the username
String password; // Declaring a string for the password
String username;
username = JOptionPane.showInputDialog("Please enter your username: ", "username");
password=JOptionPane.showInputDialog("Please enter your Password: ");
VerifyLoginA(username, password, filepath);
}
public void VerifyLoginA(String username, String password, String filepath) {
boolean flag = false; // boolean variable set to false for later use
String tempUsername = ""; // variable used for extracting the username from txt file and storing in this
String tempPassword = ""; // variable used for extracting the password from txt file and storing in this
try {
x = new Scanner(new File(filepath)); //opens the file "/home/ogweno/Students.txt"
x.useDelimiter("[,\n]"); // use of delimiter to specify the seperation of username & password by ","
boolean passed = false; // boolean variable set to false and later use
while (x.hasNext()&& !flag){ // use of while to check if the file has any contents
tempUsername = x.next(); // extracts the username and stores it
tempPassword = x.next();// extracts the password and stores it
if (tempUsername.trim().equals(username.trim()) && tempPassword.trim().equals(password.trim())) {
passed = true; // use of trim to remove any unwanted space in user input or in txt file
break; // boolean passedA becomes true if the username and passwords entered by user match the ones in file
}
}
if(passed) { // if passedA is true then prints Welcome + the username
// System.out.println("Welcome " + username);
//System.out.println(""); // space
JOptionPane.showMessageDialog(null,"Welcome " + username);
boolean check = true;
setName(username);
}
else { // if passedA is false then prints a error message
// System.out.println("********WARNING**Incorrect Username or Password*********");
JOptionPane.showMessageDialog(null,"********WARNING**Incorrect Username or Password*********");
boolean check = false;
System.exit(0); // Terminates program if username and/or password is incorrect
}
}
catch (FileNotFoundException e){ // prints error if there is an error in opening the file
System.out.println("Error");
}
}
public static void setName(String usernamename) {
name=username;
//To change body of generated methods, choose Tools | Templates.
}
public static String getName(){
return name;
}
}
Here's the salary-calculator class
public class Salary_calculator extends loginpage {
public void calculator(){
int HS=10000;
int TV=5000;
int NSSF=2000;
int NHIF=500;
loginpage login=new loginpage();
int grossPay=0;
String post="";
float netSalary;
if (name=="Jane"){
grossPay=20000;
post="Finance Officer";
}
else if (name=="Michael"){
grossPay=30000;
post="IT technician";
}
else if (name=="Josphine"){
grossPay=40000;
post="Marketing Officer";
}
else if (name=="Darshan"){
grossPay=50000;
post="Public Relations Officer";
}
else if (name=="Ketan"){
grossPay=60000;
post="Operations Manager";
}
int salary=grossPay + HS + TV -(NSSF+NHIF);
netSalary=(float) (0.7*salary);
JOptionPane.showMessageDialog(null, name + ": " + post + "\n" + "Your net salary is: " + netSalary + "\n");
}
}
An example of accessing data in another class.
A minimal example class with one static and one non-static variable.
public class Payroll{
public static String name1 = "static name1, same for all instances!";
public String name2 = "name2, each instance has its own!";
}
Access the static name1 in Payroll from other classes:
String name = Payroll.name1;
Access the non-static name2 in Payroll from other classes:
Payroll payroll = new Payroll();
// Later, after the new instance has its data
String name = payroll.name2;
Remember, access to non-static variables requires that you have access to the instance. Every time you create a new instance with new it initially has no data or only standard data for you!
Edit: An example to demonstrate the interaction of two classes:
import java.util.*;
import javax.swing.*;
public class Payroll {
static final List<Employee> employees = new ArrayList<>();
public static void main(String[] args) {
var payroll = new Payroll();
var employee = payroll.login();
JOptionPane.showMessageDialog(null, employee == null ? "Invalid Login!" : employee.getSalaryMessage());
}
public Payroll(){
loadEmployees();
}
public Employee login(){
String username = JOptionPane.showInputDialog("Please enter your Username:");
String password = JOptionPane.showInputDialog("Please enter your Password:");
for(var employee : employees) if(employee.isEmployee(username, password)) return employee;
return null;
}
private void loadEmployees(){
employees.add(new Employee("Jane", "jan", "xxx", 20000, "Finance Officer"));
employees.add(new Employee("Michael", "mic", "yyy", 30000, "IT technician"));
employees.add(new Employee("Josphine", "jos", "zzz", 40000, "Marketing Officer"));
employees.add(new Employee("Darshan", "dar", "qqq", 50000, "Public Relations Officer"));
employees.add(new Employee("Ketan", "ket", "ppp", 60000, "Operations Manager"));
}
}
For completeness, the Employee class:
public class Employee {
private String name;
private String username;
private String password;
private double grossPay;
private String post;
public Employee(String name, String username, String password, double grossPay, String post){
this.name = name;
setUsername(username);
setPassword(password);
setGrossPay(grossPay);
setPost(post);
}
public String getSalaryMessage(){
return name + " (" + post + ") earns " + grossPay;
}
public boolean isEmployee(String username, String password){
return this.username.equals(username) && this.password.equals(password);
}
public String getName(){ return name; }
public void setName(String name){ this.name = name; }
public String getUsername(){ return username; }
public void setUsername(String username){ this.username = username; }
public String getPassword(){ return password; }
public void setPassword(String password){ this.password = password; }
public double getGrossPay(){ return grossPay; }
public void setGrossPay(double salary){ this.grossPay = salary; }
public String getPost(){ return post; }
public void setPost(String post){ this.post = post; }
}
I am a java beginner and I've tried to add the player in an array. I thought I successfully dealt with the problem, but it's not. I've done the following:
I have a split text send to create a player.
I have made a constructor in NimPlayer.
I set the array in Nimsys to save created player data.
And I have two questions:
It is for sure that the array will be all null at first. If I use the only array here, is that possible to add the player here?
I have set the counter for recording a created player, but I cannot do it in the else statement.
Here is my code:
int static counter;
public static String[] splitName(String inName) {
String[] splittedLine = inName.split(",");
String[] name = null;
if (splittedLine.length==3) {
String userName = splittedLine[0].trim();
String familyName = splittedLine[1].trim();
String givenName = splittedLine[2].trim();
name = new String[3];
name[0] = userName;
name[1] = familyName;
name[2] = givenName;
}
return name; }
public static void main(String[] args) {
NimPlayer[] playerList = new NimPlayer[10]; // set an array here
Scanner in = new Scanner(System.in);
while (true) {
System.out.print('$');
String commandin = in.next();
if (commandin.equals("addplayer")) {
String inName = in.nextLine();
String[] name = splitName(inName);
//Make sure the vadality of in name
//Can use playerCheck to simplify the code
if (name != null && name.length==3 && counter < 10) {
if (playerList != null) {
for (int i = 0; i < playerList.length; i++) {
String userCheck = playerList[i].getUserName();
if (userCheck.contains(name[0])) {
System.out.println("The player already exist.");
} else {
System.out.println("The player has been created.");
playerList[counter++] = new NimPlayer(name[0],name[1],name[2], 0, 0);
}
}
} else {
// I have to add the player here
}
} else {
System.out.println("Invalid input! e.g. addplayer george,Washington,George");
}
}
And my NimPlayer is:
public class NimPlayer {
private String userName;
private String familyName;
private String givenName;
private int score;
private int gamePlayed;
public NimPlayer(String userName, String familyName, String givenName, int gamePlayed, int score) {
this.userName = userName;
this.familyName = familyName;
this.givenName = givenName;
this.gamePlayed = gamePlayed;
this.score = score;
}
public void setUserName(String userName) {
this.userName = userName;
}
public void setFamilyName(String familyName) {
this.familyName = familyName;
}
public void setGivenName(String givenName) {
this.givenName = givenName;
}
public String getUserName() {
return userName;
}
public String getfamilyName() {
return familyName;
}
public String getGivenName() {
return givenName;
}
public int setScore(int score) {
return score;
}
public int getScore() {
return score;
}
public int setGamePlayed (int gamePlayed) {
return gamePlayed;
}
public int getGamePlayed() {
return gamePlayed;
}
}
Yes, you may alter the array elements as you wish. So "adding" players (setting the value of an array element within array bounds) is OK.
The else ("// I have to add the player here") will never be reached, since playerList is never null.
Since all elements in playerList is initialized to null, you should check if playerList[i] is null before calling
getUserName() (to avoid NullpointerException).
The exercise is to have a class named Tenant that will be used to store values of tenants for an apartment. In the main class Prog2 I am trying to create an ArrayList that can hold 4 different values, all regarding the tenant class, which are - the tenant's name, apartment number, initial first payment, and monthly payment. I want to be able to print these values out in separate lines that will provide all 4 pieces of information per tenant - followed by a blank line, and then the same 4 pieces of information for another tenant if there is another one. I can get the program to prompt the questions correctly, but then all I get are nulls and 0's printed out (see below at comment). I appreciate all the help - I'm not the best at this.
// this class is the tenant class that passes all the tenant's
information
public class Tenant {
private String firstName;
private String lastName;
private String aptNumber;
private double yearlyRent;
private String fullName;
private double firstPayment;
private double monthlyPayment;
public Tenant(String name, String aptNum, double fPayment, double
mPayment){
name = fullName;
aptNum = aptNumber;
fPayment = firstPayment;
mPayment= monthlyPayment;
}
public Tenant() {
}
public void setFirstName(String name) {
firstName = name;
}
public void setLastName(String lName) {
lastName= lName;
}
public void setAptNumber(String apt) {
aptNumber = apt;
}
public void setRent(double rent) {
yearlyRent = rent;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getAptNumber() {
return aptNumber;
}
public double getRent() {
return yearlyRent;
}
public double getFirstPayment() {
double monthlyRent = yearlyRent/12;
firstPayment = monthlyRent * 3;
return firstPayment;
}
public double getmonthlyPayment() {
double firstAndLast = yearlyRent/12;
monthlyPayment = (yearlyRent - firstAndLast)/11;
return monthlyPayment;
}
public String getFullName(){
fullName = firstName + " " + lastName;
return fullName;
}
}
// The below class contains the main method
public class Prog2 {
public static double getDouble(Scanner scan) {
System.out.println("Enter yearly rent:");
while (!scan.hasNextDouble()) {
scan.next();
System.out.println("Error: please enter a numeric
value");
}
return scan.nextDouble();
}
public static void main(String[] args) {
Tenant tnt = new Tenant();
Scanner scan = new Scanner(System.in);
System.out.println("Enter number of tenenats:");
int numTenants = scan.nextInt();
ArrayList<Tenant> list = new ArrayList<Tenant>();
for (int i = 0; i<numTenants; i++) {
System.out.println("Enter first name:");
tnt.setFirstName(scan.next());
System.out.println("Enter last name:");
tnt.setLastName(scan.next());
System.out.println("Enter apt number:");
tnt.setAptNumber(scan.next());
tnt.setRent(getDouble(scan));
list.add(new Tenant(tnt.getFullName(), tnt.getAptNumber(),
tnt.getFirstPayment(), tnt.getmonthlyPayment()));
}
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i).getFullName());
System.out.println(list.get(i).getAptNumber());
System.out.println(list.get(i).getFirstPayment());
System.out.println(list.get(i).getmonthlyPayment());
System.out.println();
}
}
}
// this prints out:
null null
null
0.0
0.0
null null
null
0.0
0.0
The issue is with the first constructor in the Tenant class. Remember that the = operator assigns the value of the right operand to the variable in the left operand. In your case the code should look like this:
public Tenant(
String name,
String aptNum,
double fPayment,
double mPayment)
{
fullName = name;
aptNumber = aptNum;
firstPayment = fPayment;
monthlyPayment = mPayment;
}
What I typically do with constructors is name the parameters after the field, then on the left side of the field assignments use this to refer to the field as opposed to the parameter. This ends up looking much clearer:
public Tenant(
String fullName,
String aptNumber,
double firstPayment,
double monthlyPayment)
{
this.fullName = fullname;
this.aptNumber = aptNumber;
this.firstPayment = firstPayment;
this.monthlyPayment = monthlyPayment;
}
this can be tricky to use but this is an example where it can clear things up.
Many things are wrong with your code .
Constructor of
public Tenant(String name, String aptNum, double fPayment, double
mPayment){
name = fullName;
aptNum = aptNumber;
fPayment = firstPayment;
mPayment= monthlyPayment;
}
here your not just assigning null values to your function parameeters, instead of assigning values to your class fields from function parameters.
Also, when you are calling function getFullName() , it will return null as firstName and lastName fields are not initialized.
So, you need to modify your constructor to -
public Tenant(String firstNamename, String lastName, String aptNum, double fPayment, double
mPayment){
this.firstName = firstNamename;
this.lastName = lastName;
this.aptNumber = aptNum;
this.firstPayment = fPayment;
this.monthlyPayment = mPayment;
this.fullName = getFullName();
}
also in for loop , you need to change
list.add(new Tenant(tnt.getFullName(), tnt.getAptNumber(),
tnt.getFirstPayment(), tnt.getmonthlyPayment()));
to -
list.add(new Tenant(tnt.getFirstName(),tnt.getLastName(), tnt.getAptNumber(),
tnt.getFirstPayment(), tnt.getmonthlyPayment()));
Ive been trying to use a for loop to add instances of a driver to a driver array. Each driver has 3 basic variables that are gathered through the for loop. When the loop runs though, the details of the last driver are stored in all of the indexes of the array! I want to get it so that i can add each individual driver to the array.
public static void addDriver(Driver[] d) { //method using for loop to add drivers
for(int i = 0; i < d.length; i++ ) {
String name, DOB, occupation;
System.out.println("Please Enter Driver Name");
name = kb.nextLine();
System.out.println("Please Select Driver Occupation");
System.out.println("1: Chauffeur" + "\n2: Accountant");
int choice = kb.nextInt();
kb.nextLine();
if (choice == 1) {
occupation = "Chauffeur";
} else {
occupation = "Accountant";
}
System.out.println("Please Enter Driver D.O.B");
DOB = kb.nextLine();
d[i] = new Driver(name, occupation, DOB);
}
}
any and all help greatly appreciated!
edit...
here is the code from the main method, i get the size of the array from a separate method called driverNum.
public static void main(String[] args) {
int drivers = driverNum(); //Setting size of the array
Driver[] d = new Driver[drivers]; //creating new array using number of drivers to be insured
addDriver(d); //calling method to add drivers to array
for(int x = 0; x < d.length; x++)
{
System.out.println(d[x].toString());
}
}
here is the Driver class that i have been using...
public class Driver {
static String name, occupation, DOB;
public Driver()
{
name = "";
occupation = "";
DOB = "";
}
public Driver(String name, String occupation, String DOB)
{
this.name = name;
this.occupation = occupation;
this.DOB = DOB;
}
public void setName(String name)
{
this.name = name;
}
public String getName(Driver d)
{
return name;
}
public void setOccupation(String occupation)
{
this.occupation = occupation;
}
public String getOccupation()
{
return occupation;
}
public void setDOB(String DOB)
{
this.DOB = DOB;
}
public String getDOB()
{
return DOB;
}
public String toString()
{
String s;
s = "Name: " + name;
s = s + "\nOccupation: " + occupation;
s = s + "\nDOB: " + DOB;
return s;
}
}
Ive been scratching my head over this for a while now, because i thought it was correct. Thanks for the help so far!
In your Driver class, you defined your three global variables, name, occupation, and D.O.B as static. This means that whenever you change the value of that variable, it will change everywhere in the program, even if you create multiple instances of that class. Just take out the static declaration and that should solve your problem.
first of all sorry for my english it is not perfect.
I got a little problem (for me a huge problem) in java.
package test;
import java.util.Scanner;
public class adress {
String adress;
String city;
int postcode;
String ergebnis;
public void setadress(String adress)
{
this.adress = adress;
}
public String getadress()
{
return adress;
}
public void setcity(String city)
{
this.city = city;
}
public String getcity()
{
return city;
}
public void setpostcode(int postcode)
{
this.postcode = postcode;
}
public int getpostcode()
{
return postcode;
}
public void output (String adress, String city, int postcode) {
Scanner a = new Scanner (System.in);
System.out.println("How much values?");
int b = a.nextInt();
int [] c = new int [b];
for (int i=0; i<c.length; i++) {
Scanner input = new Scanner (System.in);
System.out.println("Adress?");
String temp = input.nextLine();
setadresse(temp);
Scanner input3 = new Scanner (System.in);
System.out.println("City?");
String temp2 = input3.nextLine();
setcity(temp2);
Scanner input4 = new Scanner (System.in);
System.out.println("Postcode?");
int temp3 = input4.nextInt();
setpostcode(temp3);
this.adress = adress;
this.city = city;
this.postcode = postcode;
System.out.println("Adress: "+adress+"City"+city+"postcode"+postcode);
}
}
}
Now, i want to save the values in a new class in a array
package test;
public class save {
adress [] saver = new adress[10];
public adressenpool (String adress, String city, int postcode){
for(int i =0; i<10;i++)
saver[i] = ????? ; //i have tried several things here, but it will not work. i know it is just a little problem but i can't get it the mistake
}
}
}
How can i get the values from address class an copy it as an array in the saver class?
It looks like you are attempting to put 10 objects of class address in an object of class save, as opposed to just the information within address. This is generally a good idea so I encourage you to continue.
In order to create the address within method adressenpool you need to use its constructor. At present class address only had a default constructor, which creates an effectively empty address. I would add a new constructor that fully creates the object
public class adress {
String adress;
String city;
int postcode;
String ergebnis;
public adress(String adress, String city, int postcode, String ergebnis){
this.adress=address;
this.city=city;
this.postcode=postcode;
this.ergebnis=ergebnis;
}
//you can have several constructors so you can keep the empty constructor if you want to set the elements piece by piece
public adress(){
}
......
other methods as before
}
Having added the constructor you can now make addresses easily
public adressenpool (String adress, String city, int postcode,String ergebnis){
saver[0] = new adress(adress, city, postcode,ergebnis);
}
However, your method adressenpool only contains enough information to create 1 adress. You may wish to set which index to save it at. Or you may want to change from an array to an arraylist so you can just add new adress as you go.
public adressenpool (String adress, String city, int postcode,String ergebnis, int index){
saver[index] = new adress(adress, city, postcode,ergebnis);
}
Notes
Classes always start with an uppercase letter. Objects with
lowercase. So it should be class Save and class Address
For loops (and if statements) without braces are considered a dangerous thing to do. Always include {} with your loops even if it contains a single statement. So
for(int i =0; i<10;i++){
saver[i] new Adress(adress, city, postcode,ergebnis);
}
I think you should be more specific of what you want to do exactly.
Your first class has 4 members (3 String and 1 int) and you want to save the values from address class as an array in the saver class? What do you mean by the last one?
I am guessing you need to fill each address instance in the array you define (saver) by calling the appropriate setters. (You haven't defined setadresse() by the way). This can be done in a loop for example.
Also this is not very straight forward: //i have tried several things here, but it will not work. What have you tried and did not work?
Of course you need a main() function also to run your program.
I hope that helped a bit...
This will solve the issue
package temp;
import java.util.Scanner;
public class adress {
String adress;
String city;
int postcode;
String ergebnis;
public void setadress(String adress)
{
this.adress = adress;
}
public String getadress()
{
return adress;
}
public void setcity(String city)
{
this.city = city;
}
public String getcity()
{
return city;
}
public void setpostcode(int postcode)
{
this.postcode = postcode;
}
public int getpostcode()
{
return postcode;
}
public void setAddress () {
Scanner input = new Scanner (System.in);
System.out.println("Adress?");
String temp = input.nextLine();
setadress(temp);
Scanner input3 = new Scanner (System.in);
System.out.println("City?");
String temp2 = input3.nextLine();
setcity(temp2);
Scanner input4 = new Scanner (System.in);
System.out.println("Postcode?");
int temp3 = input4.nextInt();
setpostcode(temp3);
}
#Override
public String toString() {
// TODO Auto-generated method stub
return "Adress: "+adress+"City"+city+"postcode"+postcode;
}
}
And the second class
package temp;
import java.util.Scanner;
public class save {
adress [] saver;
public save(){
saver = new adress[10];
}
public void adressenpool(){
Scanner a = new Scanner (System.in);
System.out.println("How much values?");
int b = a.nextInt();
adress address1 = null;
for (int i=0; i<b; i++) {
address1 = new adress();
address1.setAddress();
this.saver[i] = address1;
}
}
public static void main(String[] args) {
save saveTemp = new save();
saveTemp.adressenpool();
for(int i=0; i<2; i++){
System.out.println(saveTemp.saver[i].toString());
}
}
}