JAVA using assigned values from an array in a calculation - java

This is a very basic question but I have just started out with JAVA and have hit a bit of a bump with regards to arrays.
What I am trying to do is populate an array with 6 pieces of information from the user:
Number of employees to be input,
An alphanumeric employee number,
A first name,
A last Name,
the number of hours they have worked,
a number input corresponding to Pay Scale.
So far I have gotten these inputs into an array in JAVA however what I wanted to do was use corresponding number input to select a constant within the Pay Scale array and then use that constant to calculate the wages of each employee.
for instance employee 1 worked 10 hours at scale 0 so that would be 10*4.50
and employee worked 10 hours at scale 1 which would be 10*4.62
import java.util.Arrays; //imports Array utility
import java.util.Scanner; //imports Scanner utility
public class test1 {
static Scanner keyb = new Scanner(System.in); //Adds a keyboard input
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number of Employees: ");
int employees = scanner.nextInt();
String[] Employee = new String[employees];
String[] FirstName = new String[employees];
String[] LastName = new String[employees];
double[] HoursWorked = new double[employees];
double[] PayScale = {4.50,4.62,4.90,5.45,6.20};
for (int i = 0; i < Employee.length; i++) {
System.out.print("Enter Employee Number: ");
Employee[i] = scanner.next();
System.out.print("Enter Employee's First name: ");
FirstName[i] = scanner.next();
System.out.print("Enter Employee's Last name: ");
LastName[i] = scanner.next();
System.out.print("Enter Employee's Hours worked: ");
HoursWorked[i] = scanner.nextDouble();
System.out.print("Enter Employee's Payscale (Number 0 to 4): ");
PayScale[i] = scanner.nextDouble();
}
for (int i = 0; i < HoursWorked.length; i++) {
System.out.println("Employee " + Employee[i] + " " + FirstName[i] + " " + LastName[i] + " has "
+ HoursWorked[i] * PayScale[0]);
}
}
}
}
Am I even close to a solution on this?
Is what I'm asking possible in JAVA?
Maybe I'm just looking at this the wrong way, but any help regarding this would be greatly appreciated.
edit
OK I added the extras array into the code
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number of Employees: ");
int employees = scanner.nextInt();
String[] Employee = new String[employees];
String[] FirstName = new String[employees];
String[] LastName = new String[employees];
double[] HoursWorked = new double[employees];
int[]PayScale2 = {0,1,2,3,4};
double[] PayScale = {4.50,4.62,4.90,5.45,6.20};
I'm just unsure as to where I'd index the original PayScale array with the
PayScale[PayScale2[i]]
would it go into the for statement codeblock? (I have tried putting it in there however I get an error that it's not a statement :/

change
+ HoursWorked[i] * PayScale[0]);
to
+ HoursWorked[i] * PayScale[i]);
apart from that seems to me like you're doing what you're saying you should be doing..
you already have the payscales from here: double[] PayScale = {4.50,4.62,4.90,5.45,6.20}; so the following doesn't make a lot of sense:
System.out.print("Enter Employee's Payscale (Number 0 to 4): ");
PayScale[i] = scanner.nextDouble();
First of all, if you want to keep this number (Number 0 to 4) separately, you should use another Array, not the one where you keep the Payscales, then you could index to the first array which keeps the different rates.. or else you could directly use the first array if you know the pay scale for every employee.. in the end it has to do with what you want to do and how you want to do it, but the logic and the tools are there. If you call the 2nd array PayScale2 for example:
System.out.print("Enter Employee's Payscale (Number 0 to 4): ");
PayScale2[i] = scanner.nextDouble();
then you can index to the first array for example:
PayScale[PayScale2[i]]
in which case if the user inputs 0 then PayScale2[i] would be 0 then PayScale[PayScale2[i]] would be PayScale[0] or 4.5 or whatever you set the value equal to at the first array

Related

Arrays With Multiple Information Per Box

So I have this practice question where I should create an array with the employee's information and pass it on to the class; there is a problem with my code which I cant seem to figure out.
What the code is meant to do is:
Have the information as seen in the code put into an array, then passed to the methods in the class and then printed out to the user. (The code in the class is perfectly fine, hence why it's not included here).
If anyone could help, that'd be awesome.
Thank you.
// Code.
// The Scanners.
Scanner input = new Scanner(System.in);
Scanner scan = new Scanner(System.in);
// Taking Number Of Employees From The User.
System.out.println("How many employees are there: ");
int numberOfEmployees = input.nextInt();
//Creating An Array With The Size Of Employees Entered By The User.
Employee[] E = new Employee[numberOfEmployees];
// Filling Out Information About Employees In Array.
for(int i = 0; i <= E.length-1; i++){
System.out.println("Enter employee " + i + "'s name: ");
String name = scan.nextLine();
System.out.println("Enter employee " + i + "'s birth date: ");
String bday = scan.nextLine();
System.out.println("Enter employee " + i + "'s salary: ");
double salary = input.nextDouble();
System.out.println("Enter employee " + i + "'s overtime: ");
int overtime = input.nextInt();
E[i] = (name, bday, salary, overtime);
}
System.out.println("Employee's Information"
+ "\n----------------------"
+ "\n----------------------");
for(int i = 0; i <= E.length-1; i++){
E[i].print();
}
}
There are two issues here that need to be addressed.
First, don't create more than one Scanner object, reading from System.in. I know you did this, because of this issue (check it out): Scanner is skipping nextLine() after using next() or nextFoo()? - But there is another solution than creating another Scanner.
The second issue is here:
E[i] = (name, bday, salary, overtime);
You have a Employee[] which you are trying to fill. But you got the syntax wrong. You actually want to create a new Employee(...) to fill your array with.
So this line should correctly be (provided that Employee has a constructor with the given types):
E[i] = new Employee(name, bday, salary, overtime);
When considering this in your code snippet:
Scanner scan = new Scanner(System.in);
// Taking Number Of Employees From The User.
System.out.println("How many employees are there: ");
int numberOfEmployees = scan.nextInt();
scan.nextLine(); // <- reads the newline from the console
//Creating An Array With The Size Of Employees Entered By The User.
Employee[] E = new Employee[numberOfEmployees];
// Filling Out Information About Employees In Array.
for(int i = 0; i <= E.length-1; i++){
System.out.println("Enter employee " + i + "'s name: ");
String name = scan.nextLine();
System.out.println("Enter employee " + i + "'s birth date: ");
String bday = scan.nextLine();
System.out.println("Enter employee " + i + "'s salary: ");
double salary = scan.nextDouble();
System.out.println("Enter employee " + i + "'s overtime: ");
int overtime = scan.nextInt();
// create a new employee with the entered information and save in the array
E[i] = new Employee(name, bday, salary, overtime);
}
I am not sure with the Double scanner.
The obvious one is since you defined an empty array of Employee object type, the array can only be fit by Employee objects.
Employee[] E = new Employee[numberOfEmployees]
to define one object, you need to allocate a memory onto it, like:
new Employee(name, bday, salary, overtime);
then assign it into the array E
E[i] = new Employee(name, bday, salary, overtime);
i hope that clear things up.

Adding the code for ascending order of user input

import java.util.Scanner;
import java.util.Arrays;
public class searchSorting
{
public static void main (String[]args)
{
String line;
Scanner in = new Scanner(System.in);
System.out.print("How many numbers you want to input?: ");
line = in.nextLine();
System.out.print("Input Number 1: " );
line = in.nextLine();
System.out.print("Input Number 2: ");
line = in.nextLine();
System.out.print("Input Number 3: " );
line = in.nextLine();
System.out.print("Input Number 4: ");
line = in.nextLine();
System.out.print("Input Number 5: " );
line = in.nextLine();
}
public static void sortAscending (double[]arr)
{
Arrays.sort(arr);
System.out.printf("Sorted arr[] = %s",
Arrays.toString(arr));
}}
I am stuck on what the code is for putting the what the user inputs in ascending order. I have looked up and tried multiple resources on ascending order but nothing seems to work. I tried:
System.out.print("Input number 1: "+(i+1+":");
to try and add the inputs instead of writing all of them out but i was an unknown variable.
You should use an array to store input and a loop to read input.
System.out.print("How many numbers you want to input?: ");
int num = in.nextInt();
double[] arr = new double[num];
for(int i = 0; i < num; i++){
arr[i] = in.nextDouble();
}
sortAscending(arr);
You have to create an array. Then put the stuff you are reading into the array and after that call your method.
System.out.print("How many numbers you want to input?: ");
int amount = Integer.parseInt(in.nextLine());
double[] values = new double[amount];
for (int i = 0; i < values.length; i++) {
System.out.print("Input Number " + i + ": ");
values[i] = Double.parseDouble(in.nextLine());
}
sortAscending(values);
Note that the name sortAscending is not accurate, it is not just sorting (and then returning the result or in-place), but also printing. So maybe you should rename it to sortAndPrintAscending. Or just sort it and let your main method to the printing.
Or drop it completely, the method does not really serve any purpose as it is just calling Arrays.sort, might as well do that in main:
System.out.print("How many numbers you want to input?: ");
int amount = Integer.parseInt(in.nextLine());
double[] values = new double[amount];
for (int i = 0; i < values.length; i++) {
System.out.print("Input Number " + i + ": ");
values[i] = Double.parseDouble(in.nextLine());
}
Arrays.sort(values);
System.out.println("Sorted: " + Arrays.toString(values));

Having weird issue with array [duplicate]

This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 7 years ago.
Im currently in the process of creating a program and stores data and I'm running into an issue where its printing out a statement twice and counting it as two in an array(its hard to explain so ill show it)
So this is the code
public static void GetData()
{
Scanner input = new Scanner(System.in);
System.out.println("How many names do you want to enter?");
int num = input.nextInt();
int array[] = new int[num];
for (int i = 0 ; i < array.length ; i++ )
{
String[] names = new String[num];
System.out.println("enter employee's name: ");
names[i] = input.nextLine();
}
for(int j = 0; j < array.length;j++)
{
double[] payrate = new double[num];
System.out.println("enter employee's payrate: ");
payrate[j] = input.nextDouble();
}
}
}
the problems is its printing out :
How many names do you want to enter?
4
enter employee's name:
enter employee's name:
harry
enter employee's name:
larry
enter employee's name:
mary
enter employee's payrate:
twice right away so when the user declares let says the array size of 4 it'll print that twice and it'll count that as two spots already so now it only counts 3 of the data and switches to the next array, I'm honestly not sure whats causing this, I tried to debug it but it tells me nothing, any help would be loved!
The first names[i] = input.nextLine(); will read the \n from the line containing the number which you read with input.nextInt(), so you'll get an empty name there.
You could read the num as follows:
String strNum = input.nextLine();
int num = Integer.parseInt(strNum);

Lost first element in array? [duplicate]

This question already exists:
Scanner issue when using nextLine after nextXXX [duplicate]
Closed 8 years ago.
Yes this is an assignment...
I've got 2 arrays; one for student names and one for their scores. I've asked the user to input the number of students to initialize the sizes of both, and then loop through the input process to fill the elements.
But the weirdest thing happens that hasn't happened before. It seems that the student array is cut short by one element when the code is run (after 4 entries the program jumps to the next input loop), but even weirder is that the truncation seems to be at the front of the array, because the scores loop starts with a blank where a name should be but allows for 5 inputs.
import java.util.Scanner;
public class Ex6_17SortStudents {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int numOfStu;
String[] students;
double[] scores;
System.out.println("Enter the number of students being recorded: ");
numOfStu = input.nextInt();
students = new String[numOfStu];
System.out.println("Enter students' names: ");
for (int i = 0; i < students.length; i++)
students[i] = input.nextLine();
scores = new double[numOfStu];
for (int i = 0; i < students.length; i++) {
System.out.print("Enter score for " + students[i] + ": ");
scores[i] = input.nextDouble();
}
}
}
Any ideas why this happens?
There's eventually a sort but that's a mess i think i have a handle on.
Sorry if the format for the post is wrong -- first time posting; trying my best.
thanks
This debugging output should give you a clue to your problem:
System.out.println("Enter students' names: ");
for (int i = 0; i < students.length; i++) {
System.out.print("Name index " + i + ": ");
students[i] = input.nextLine();
}
And this answer to this question is exactly the answer you need.
Use students[i] = input.next();
Just checked it, and it works now.
nextLine() advances your scanner past the current line and returns the input that was skipped -- so you were pretty much skipping a line. The first time it enters the loop, you lose an i value, that is i is now 1, yet your scanner does not record user input. The second time around, when i is 1, it takes input, and so forth.
New code:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int numOfStu;
String[] students;
double[] scores;
System.out.println("Enter the number of students being recorded: ");
numOfStu = input.nextInt();
students = new String[numOfStu];
scores = new double[numOfStu];
System.out.println("Enter students' names: ");
for (int i = 0; i < students.length; i++) {
students[i] = input.next();
}
for (int i = 0; i < students.length; i++) {
System.out.print("Enter score for " + students[i] + ": ");
scores[i] = input.nextDouble();
}
}

JAVA beginner help needed string input in a loop

im a beginner in Java, and i have a problem to do:
the problem prompts the user 5 times to enter, the Name of a stock then the Share Price then the number of shares owned and we should calculate the sum of all the stock values, i wrote it using only two prompts using a loop, but my issue is that, in the second prompt time the loop Skips the String input for the second Name of stock instead of promting...bellow is the code:
import java.util.Scanner;
public class test1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double sharePrice =0,stockPrice = 0, temp = 0 ;
int i = 0;
double sum=0;
String name;
while (i < 2) {
System.out.println("Enter the Name of the Stock ");
name = input.nextLine();
System.out.println("Enter the Share price ");
sharePrice = input.nextDouble();
System.out.println("Enter the number of owned shares");
int numberOfshares = input.nextInt();
stockPrice = sharePrice * (double)(numberOfshares);
sum += stockPrice;
i++;
}
System.out.println("the total stockprice owned is: " + sum );
}
}
And this is the output i get:
Enter the Name of the Stock
nestle
Enter the Share price
2
Enter the number of owned shares
4
Enter the Name of the Stock
Enter the Share price
What makes the input skip during the second loop?
Again as per my comment the problem is that your code doesn't handle the End Of Line (EOL) token when calling nextInt() or nextDouble().
The solution is to use input.nextLine() after getting your int and double in order to swallow the EOL token:
sharePrice = input.nextDouble();
input.nextLine(); // add this
System.out.println("Enter the number of owned shares");
int numberOfshares = input.nextInt();
input.nextLine(); // add this
stockPrice = sharePrice * (double)(numberOfshares);
The problem is that the last time you call
int numberOfshares = input.nextInt();
in the first iteration of the loop your first passes a carriage return as the next stock name. You could instead use:
double sharePrice = Double.parseDouble(input.nextLine());
and
int numberOfshares = Integer.parseInt(input.nextLine());
You should readout the newline characters after reading the share price and number of shares:
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
double sharePrice = 0, stockPrice = 0;
int i = 0;
double sum = 0;
String name;
while (i < 2)
{
System.out.println("Enter the Name of the Stock ");
name = input.nextLine();
System.out.println("Enter the Share price ");
sharePrice = input.nextDouble();
// Read out the newline character after the share price.
input.nextLine();
System.out.println("Enter the number of owned shares");
int numberOfshares = input.nextInt();
// Read out the newline character after the number of shares.
input.nextLine();
stockPrice = sharePrice * (double) (numberOfshares);
sum += stockPrice;
System.out.println(String.format("Name: %s, Price: %f, Shares: %d, Total: %f",
name,
sharePrice,
numberOfshares,
stockPrice));
i++;
}
System.out.println("the total stockprice owned is: " + sum);
}
See the lines with comments above:

Categories

Resources