Capitalize Name in output of ArrayLists in Java - java

I am relatively fresh (couple weeks) into Java and I am messing around with an Employee input system with ArrayLists. Anyway I want to ensure no matter the user input that that name in the output is the same format.
Example:
Input --> Enter Employee Name: SAMANTHA
Output --> Employee Name: Samantha
Here is the code I am running, I am just not sure where within this I could set that formatting.
import java.util.ArrayList;
import java.util.Scanner;
public class EmployeeTester_v5
{
public static void main (String[] args)
{
//ASSIGN VARIABLES
String c = "";
String newEmployee = "";
double yearToDate = 0.0;
double increase = 0.025;
double newSalary = 0.0;
//ARRAY LISTS
ArrayList<String>first = new ArrayList<String>();
ArrayList<String>last = new ArrayList<String>();
ArrayList<Double>salary = new ArrayList<Double>();
ArrayList<Integer>months = new ArrayList<Integer>();
//SCANNER INPUT
//create a new scanner
Scanner input = new Scanner(System.in);
//WHILE LOOP - to keep asking for user input until "No" is entered
do{
//USER INPUT
System.out.println ("Enter employee first name: ");
first.add(input.next());
System.out.println ("Enter employee last name: ");
last.add(input.next());
System.out.println ("Enter employee salary: ");
salary.add(input.nextDouble());
System.out.println ("Number of months worked this year: ");
months.add(input.nextInt());
System.out.println("Enter another employee in the system?");
c = input.next();
}while(c.equalsIgnoreCase("Yes"));
System.out.println();
//ARRAY OUTPUT
for(int i=0; i < first.size(); i++)
{
yearToDate = months.get(i) * salary.get(i)/12;
newSalary = (increase * salary.get(i)) + salary.get(i);
System.out.print("Employee Name: " + first.get(i) + " ");
System.out.print(last.get(i)+"\n");
System.out.printf("Current Salary: $%.2f\n", salary.get(i));
System.out.printf("Year to Date: $%.2f\n", yearToDate);
System.out.printf("New Salary: $%.2f\n", newSalary);
System.out.println("----------------------");
}
}
}

First thing you should do is to check out String API https://docs.oracle.com/javase/8/docs/api/java/lang/String.html
It's a must-know when it comes to Java, you'll need it in possibly every project you'll work on :)
There are plenty of ways to achieve your goal here.
What you could do for example is to capitalize the first letter and then append the rest of the String that you'll force to lowercase - check out the snippet below.
String inputString = input.next();
String resultString = inputString.substring(0, 1).toUpperCase() + inputString.substring(1).toLowerCase();

Try like this :
System.out.print("Employee Name: " + first.get(i).substring(0,1).toUpperCase()+first.get(i).substring(1).toLowerCase() + " ");
this one first.get(i).substring(0,1).toUpperCase() gest your first letter in string upper, and first.get(i).substring(1).toLowerCase() gets letters from index 1 - so from the 2nd letter of the string to lower.

Maybe what the OP is not understanding, is that this can be wrapped in a private method, like this:
private String fixCapitalisation(String input) {
return input.substring(0, 1).toUpperCase() + input.substring(1).toLowerCase();
}
Then your line uses this by adjusting the line that prints the name:
System.out.print("Employee Name: " + fixCapitalisation(first.get(i)) + " ");
You can then reuse this function on the last name too...
Here is the entire class with this change:
package Dunno;
import java.util.ArrayList;
import java.util.Scanner;
public class EmployeeTester_v5
{
public static void main (String[] args)
{
//ASSIGN VARIABLES
String c = "";
String newEmployee = "";
double yearToDate = 0.0;
double increase = 0.025;
double newSalary = 0.0;
//ARRAY LISTS
ArrayList<String>first = new ArrayList<String>();
ArrayList<String>last = new ArrayList<String>();
ArrayList<Double>salary = new ArrayList<Double>();
ArrayList<Integer>months = new ArrayList<Integer>();
//SCANNER INPUT
//create a new scanner
Scanner input = new Scanner(System.in);
//WHILE LOOP - to keep asking for user input until "No" is entered
do{
//USER INPUT
System.out.println ("Enter employee first name: ");
first.add(input.next());
System.out.println ("Enter employee last name: ");
last.add(input.next());
System.out.println ("Enter employee salary: ");
salary.add(input.nextDouble());
System.out.println ("Number of months worked this year: ");
months.add(input.nextInt());
System.out.println("Enter another employee in the system?");
c = input.next();
}while(c.equalsIgnoreCase("Yes"));
System.out.println();
//ARRAY OUTPUT
for(int i=0; i < first.size(); i++)
{
yearToDate = months.get(i) * salary.get(i)/12;
newSalary = (increase * salary.get(i)) + salary.get(i);
System.out.print("Employee Name: " + fixCapitalisation(first.get(i)) + " ");
System.out.print(last.get(i)+"\n");
System.out.printf("Current Salary: $%.2f\n", salary.get(i));
System.out.printf("Year to Date: $%.2f\n", yearToDate);
System.out.printf("New Salary: $%.2f\n", newSalary);
System.out.println("----------------------");
}
}
//New Method to fix capitalisation
private static String fixCapitalisation(String input) {
return input.substring(0, 1).toUpperCase() + input.substring(1).toLowerCase();
}
I hope my answer might help you to understand the answers already given better, and how the duplicate answer i provided is relevant - the use of an ArrayList here makes no difference to the String manipulation.
You should consider defining your own class of "Employee", that can persist the name, salary etc. then you only need one ArrayList, you currently have lists with values that are Logically linked by their position in the Array, but there is no technical dependency on that.

Related

How to calculate sum from user input inside while loop

I got two classes, this one and other called DailyExpenses that's full of getters and setters + constructors etc..
My problem is that I want to get the sum value of all daily expenses user inputs inside the while loop and print the sum after the program is closed, and I don't know how to do it.
Here is my code:
import java.util.Scanner;
import java.util.ArrayList;
public class DailyExpensesMain {
public static void main(String[] args) {
ArrayList<DailyExpenses> expenses = new ArrayList<DailyExpenses>();
Scanner sc = new Scanner(System.in);
boolean isRunning = true;
System.out.println("Enter the date for which you want to record the expenses : ");
String date = sc.nextLine();
while(isRunning) {
System.out.println("Enter category: (quit to exit)");
String category = sc.nextLine();
if(category.equalsIgnoreCase("quit")) {
break;
}
System.out.println("Enter price: ");
double price = sc.nextDouble();
sc.nextLine();
System.out.println("Enter details: ");
String detail = sc.nextLine();
DailyExpenses newExpense = new DailyExpenses(date, category, price, detail);
expenses.add(newExpense);
}
sc.close();
for(DailyExpenses u: newExpense) {
System.out.println("Date: " + u.getDate() + " Category: " + u.getExpenseCategory() + " Price: " + u.getExpensePrice() +
" Detail: " + u.getExpenseDetail());
}
}
}
I still clueless on the situation

Java grades exercise

I'm Adrian and i'm kinda new to programming, would like to learn more and improve. I was asked to do a grade average exercise and i did this , but i'm stuck at making the code so if you type a number instead of a name the code will return from the last mistake the writer did , like it asks for a name and you put "5". In my code gives an error and have to re-run it. Any tips?
import java.util.*;
import java.math.*;
import java.io.*;
class Grades {
public static void main(String[] args) {
int j = 1;
double sum = 0;
double average;
Scanner keyboard = new Scanner(System.in);
System.out.println("Insert Student's Name");
String name = keyboard.next();
System.out.println("Insert Student's Surname");
String surname = keyboard.next();
System.out.println("Student's name: " + name + " " + surname);
System.out.println("How many Grades?");
int nVotes = keyboard.nextInt();
int[] arrayVotes = new int[nVotes];
System.out.println("Now insert all the grades");
for (int i=0; i<arrayVotes.length; i++) {
System.out.println("Insert the grade " + j);
arrayVotes[i] = keyboard.nextInt();
j++;
}
for (int i=0; i<arrayVotes.length; i++) {
sum += arrayVotes[i];
}
average = sum / arrayVotes.length;
System.out.println("Student's grade average is: " + average);
System.out.println("Does he have a good behaviour? Answer with true or false");
boolean behaviourStudent = keyboard.nextBoolean();
average = !behaviourStudent ? Math.floor(average) : Math.ceil(average);
System.out.println("The grade now is: " + average);
keyboard.close();
}
}
At the heart of any solution for this, it requires a loop, and a condition for resetting.
String result = null;
while (result == null) {
//OUT: Prompt for input
String input = keyboard.next();
if (/* input is valid */) {
result = input; //the loop can now end
} else {
//OUT: state the input was invalid somehow
}
//Since this is a loop, it repeats back at the start of the while
}
//When we reach here, result will be a non-null, valid value
I've left determining whether a given input is valid up to your discretions. That said, you may consider learning about methods next, as you can abstract this prompting/verification into a much simpler line of code in doing so (see: the DRY principle)
There are several ways to do it.
But the best way is to use regex to validate the user input.
Have a look at the below code, you can add other validations as well using regex.
import java.util.Scanner;
class Grades {
public static boolean isAlphabetOnly(String str)
{
return (str.matches("^[a-zA-Z]*$"));
}
public static void main(String[] args) {
int j = 1;
double sum = 0;
double average;
Scanner keyboard = new Scanner(System.in);
System.out.println("Insert Student's Name");
String name = keyboard.next();
if(!isAlphabetOnly(name)){
System.out.println("Please enter alfabets only");
return;
}
System.out.println("Insert Student's Surname");
String surname = keyboard.next();
System.out.println("Student's name: " + name + " " + surname);
System.out.println("How many Grades?");
int nVotes = keyboard.nextInt();
int[] arrayVotes = new int[nVotes];
System.out.println("Now insert all the grades");
for (int i=0; i<arrayVotes.length; i++) {
System.out.println("Insert the grade " + j);
arrayVotes[i] = keyboard.nextInt();
j++;
}
for (int i=0; i<arrayVotes.length; i++) {
sum += arrayVotes[i];
}
average = sum / arrayVotes.length;
System.out.println("Student's grade average is: " + average);
System.out.println("Does he have a good behaviour? Answer with true or false");
boolean behaviourStudent = keyboard.nextBoolean();
average = !behaviourStudent ? Math.floor(average) : Math.ceil(average);
System.out.println("The grade now is: " + average);
keyboard.close();
}
}

Skips over system out, scan nextLine, and if loops

New here (and to Java!). I've searched around the site for an answer to my problem but came up naught. This program executes up to the scan.nextDouble statement.
If I enter a salary value such as "8," I get:
/////OUTPUT/////
Enter the performance rating (Excellent, Good, or Poor):
Current Salary: $8.00
Amount of your raise: $0.00
Your new salary: $8.00
/////END OF OUTPUT/////
So obviously, my following scan.nextLine and all the if-else statements are bypassed. What am I missing?
import java.util.Scanner;
import java.text.NumberFormat;
public class Salary
{
public static void main(String[] args)
{
double currentSalary; // employee's current salary
double raise = 0; // amount of the raise
double newSalary = 0; // new salary for the employee
String rating; // performance rating
String rating1 = new String("Excellent");
String rating2 = new String("Good");
String rating3 = new String("Poor");
Scanner scan = new Scanner(System.in);
System.out.print ("Enter the current salary: ");
currentSalary = scan.nextDouble();
System.out.print ("Enter the performance rating (Excellent, Good, or Poor): ");
rating = scan.nextLine();
// Compute the raise using if ...
if (rating.equals(rating1))
raise = .06;
else
if (rating.equals(rating2))
raise = .04;
else
if (rating.equals(rating3))
raise = .015;
else
newSalary = currentSalary + currentSalary * raise;
// Print the results
{
NumberFormat money = NumberFormat.getCurrencyInstance();
System.out.println();
System.out.println("Current Salary: " + money.format(currentSalary));
System.out.println("Amount of your raise: " + money.format(raise));
System.out.println("Your new salary: " + money.format(newSalary));
System.out.println();
}
}
}
When you scan input using scanner.nextDouble() it takes only the float value and leaves the new line character in the buffer so after that when you do scanner.nextLine(() it takes the new line character and returns empty string.Put another scanner.nextLine() before scanning the next line to eat up the new line character
currentSalary = scan.nextDouble();
System.out.print ("Enter the performance rating (Excellent, Good, or Poor): ");
scan.nextLine();
rating = scan.nextLine();
Scanner.nextDouble() just reads the next available double value and does not by itself point to next line.
use a dummy scanner.nextLine() before your actual one. that lets your cursor point to next line from which your scanner.nextline() takes the input.
-cheers :)

Create multiple students and check if any are repeated java

In my code I am to input multiple students and have a method check to see if any of the students are repeated (by checking ID number) but I cant seem to be able to set multiple students with my current code and save them. From my current code is there any way to be able to set multiple students or will I have to change my code completely
import java.util.Scanner;
public class Registrar
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String string1 = " ";
while(string1 != "1")
{
System.out.println("Please input full name name of student: ");
string1 = input.next(); // user input of name
if (string1 != "0"){
break;
}
System.out.println("Please input Student ID (if done enter 0): ");
String string2 = input.next(); // user input of ID
System.out.println("Please input Students Credits: ");
int inputCredits = input.nextInt(); // User input of Credits
System.out.println("Please input Student's Total Grade Points Earned: ");
double getPoints = input.nextDouble();
double GPA = getPoints/inputCredits; //User input of Grade Points Earned and Divide by Credits to get GPA
Student first = new Student(string1, string2, inputCredits, GPA);
System.out.println( "Name: " + first.getName() + "\nUser ID: " + first.getId() + "\nCredits: " + first.getCredits() + "\nGrade Point Average: " + first.getGradePoints() );
}
}
}
This is my Student Class
public class Student {
private String name;
private String idnum;
private int credits;
private double gradePoints;
public Student(String n, String id, int c, double gp){
name = n;
idnum = id;
credits = c;
gradePoints = gp;
}
public String getName(){
return name;
}
public String getId(){
return idnum;
}
public int getCredits(){
return credits;
}
public double getGradePoints(){
return gradePoints;
}
}
Try this code. better implementation with collection.
Scanner input = new Scanner(System.in);
String string1 = " ";
System.out.println("Number of students to be entered");
int s = input.nextInt();
List<Student> studentList = new ArrayList<Student>();
for(int i = 0; i<s; i++) {
System.out.println("Please input full name of student: ");
string1 = input.next(); // user input of name
System.out.println("Please input Student ID (if done enter 0): ");
String string2 = input.next(); // user input of ID
System.out.println("Please input Students Credits: ");
int inputCredits = input.nextInt(); // User input of Credits
System.out.println("Please input Student's Total Grade Points Earned: ");
double getPoints = input.nextDouble();
double GPA = getPoints/inputCredits; //User input of Grade Points Earned and Divide by Credits to get GPA
Student student = new Student(string1, string2, inputCredits, GPA);
System.out.println( "Name: " + first.getName() + "\nUser ID: " + first.getId() + "\nCredits: " + first.getCredits() + "\nGrade Point Average: " + first.getGradePoints() );
studentList.add(student);
}
You can take a user input(How many student you want to save and run a loope to take details of input. The rough code will be like this:
System.out.println("Enter how many student you want to enter");
int s = input.nextInt();
for(int i = 0; i<s; i++) {
//Code for take details of user
}
//Then you can print the details of student in similar way.

how to check the int range in java and limit it only 5digits

Please help with my assignment. Here is the question:
Create a separate test driver class
called TestEmployeePayroll that will
test the EmployeePayroll class by
performing the following:
Prompt the user to enter the
employees’ ID number, First name, Last
name, Pay Category and Hours worked
(one at a time).
The user entry for employees ID
number must be exactly 5 digits long.
The user entry for Category must only
be accepted if it is in the range 1
to 4.
The user entry for Hours worked
must only be accepted if it is the
range 1 to 80.
This is what I did till now:
import java.util.Scanner;
public class TestEmployeePayRoll {
public static void main(String[] args){
EmployeePayRoll obj1 = new EmployeePayRoll();
Scanner input = new Scanner(System.in);
System.out.println("Enter the Employee ID number: "+ " ");
String EmployeeID = input.nextLine();
//How to check the range here if int is 5 digits long or not ?
System.out.println("Enter the first Name: "+ " ");
String FirstName = input.nextLine();
System.out.println("Enter Last Name: "+ " ");
String LastName = input.nextLine();
System.out.println("Enter the Pay Category: "+ " ");
double PayCategory = input.nextDouble();
System.out.println("Enter the number of hours worked: "+ " ");
double HoursWorked = input.nextDouble();
}
}
You will probably want to use Integer.parseInt().
You can count the length of a String and then convert it to number, Oli Charlesworth told you how to convert it, or you can measure the number. It depends on what you want. Is 012345 a valid ID? It's a 6 char String but it is less than the biggest 5 digits number.
I think you almost got it...
import java.util.Scanner;
public class TestEmployeePayRoll {
public static void main(String[] args){
// ... get the values, as you are doing already
// validate input
int employeeIdAsInteger = validateAndConvertEmployeeId(EmployeeId);
int payCategoryAsInteger = validateAndConvertPayCategory(PayCategory);
// ... and so on
}
private int validateAndConvertEmployeeId(String employeeId) {
// The user entry for employees ID number must be exactly 5 digits long.
if (employeeId == null || employeeId.trim().length() != 5) {
throw new IllegalArgumentException("employee id must be exactly 5 digits long");
}
// will throw an exception if not a number...
return Integer.parseInt(employeeId);
}
// ...
}
Depending on your objectives & constraints, you could look into the Pattern class and use a regular expression.
You can check for conditions like this.
import java.util.Scanner;
public class TestEmployeePayRoll {
public static void main(String[] args) {
TestEmployeePayRoll obj1 = new TestEmployeePayRoll();
Scanner input = new Scanner(System.in);
System.out.println("Enter the Employee ID number: " + " ");
String EmployeeID = input.nextLine();
if (EmployeeID.trim().length() != 5) {
System.out.println("--- Enter valid Employee ID number ---");
}
System.out.println("Enter the first Name: " + " ");
String FirstName = input.nextLine();
System.out.println("Enter Last Name: " + " ");
String LastName = input.nextLine();
System.out.println("Enter the Pay Category: " + " ");
double PayCategory = input.nextDouble();
Double pay = new Double(PayCategory);
if (pay.isNaN()) {
System.out.println("***** Enter a valid Pay Category *****");
}
if (!(PayCategory >= 0 && PayCategory <= 5)) {
System.out.println(" --- PayCategory must be between 0 and 5");
}
System.out.println("Enter the number of hours worked: " + " ");
double HoursWorked = input.nextDouble();
Double hours = new Double(HoursWorked);
if (hours.isNaN()) {
System.out.println("--- Enter a valid hours value ----");
} else {
if (!(HoursWorked >= 1 && HoursWorked <= 80)) {
System.out.println("--- Enter value between 1 and 80 ---");
}
}
}
}

Categories

Resources