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.
Related
Here is my updated code. Again, the instructions are as follows: "Enter a first name, last name, student id, and avg, then have those 4 things displayed in a new csv file, with each of the 4 inputs separated by a comma in each record." This code works well, is there anything I can do better? Also, is "in.close()" necessary in this case since I am not reading a file, but rather user input?
public class Homework07 {
public static void main(String[] args) throws FileNotFoundException {
System.out.println("Welcome! This program will store student records that you enter.");
System.out.println("When you are done entering student records, simply type in 'Done' .");
Scanner in = new Scanner(System.in);
PrintWriter outFile = new PrintWriter("students.csv");
while (true) {
System.out.print("Please enter the first name: ");
String firstName = in.nextLine();
if (firstName.equals("Done")) {
break;
}
System.out.print("Please enter the last name: ");
String lastName = in.nextLine();
System.out.print("Please enter the student ID: ");
int studentId = in.nextInt();
System.out.print("Please enter the current average: ");
double currentAvg = in.nextDouble();
in.nextLine();
String newRecord = (firstName + ", " + lastName + ", " + studentId + ", " + currentAvg);
outFile.println(newRecord);
}
in.close();
outFile.close();
}
}
your code capture the enter key entered by user to I added an empty in.nextLine(); to escape it, and secondly I added outFile.flush(); to flush the stream to the file.
System.out.println("Welcome! This program will store student records that you enter.");
System.out.println("When you are done entering student records, simply type in 'Done' .");
Scanner in = new Scanner(System.in);
PrintWriter outFile = new PrintWriter("students.csv");
while (true) {
System.out.print("Please enter the first name: ");
String firstName = in.nextLine();
if (firstName.equals("Done")) {
break;
}
System.out.print("Please enter the last name: ");
String lastName = in.nextLine();
System.out.print("Please enter the student ID: ");
int studentId = in.nextInt();
System.out.print("Please enter the current average: ");
double currentAvg = in.nextDouble();
in.nextLine();
outFile.write(firstName + "," + lastName + "," + studentId + "," + currentAvg);
outFile.flush();
}
in.close();
outFile.close();
Your call to the Scanner#nextDouble() method does not consume the ENTER key hit (the newline character) therefore you need to do it yourself by placing this line: in.nextLine(); directly under this line:
double currentAvg = in.nextDouble();
Ironically, you need to apply a newline character when you write to your file for every record you want to save, like this:
String record = new StringBuilder(firstName).append(", ").append(lastName)
.append(", ").append(studentId).append(", ")
.append(currentAvg).append(System.lineSeparator())
.toString();
outFile.write(record);
public class FinalMarkCalculator
{
/**
* This method is used to caculate the students mark
*/
public static void main(String[] args)
{
//Assigning the string a variable that holds the students name
String studentName;
//Initalizing a keyboard scanner
Scanner keyboardStudentName = new Scanner(System.in);
//System printing out the question
System.out.print("Enter the students name: ");
//Assigns the string studentName to the users input
studentName = keyboardStudentName.nextLine();
//Assigning the double a variable that hold the students assignment marks as a integer
double assignmentMarks;
//Assigning the string a variable that hold the students assignment marks
String assignmentMarksInput;
//Initalizing a keyboard scanner with the variable
Scanner keyboardAssignmentMarks = new Scanner(System.in);
//Asking the user for assingment marks while printing students name
System.out.printf("Enter %s's mark for Assignments (Max. 140): ", studentName);
//Taking the user input and assigning it to our string assignmentMarksInput
assignmentMarksInput = keyboardAssignmentMarks.nextLine();
//Converting the user input from a string to a double
assignmentMarks = Double.parseDouble(assignmentMarksInput);
//Assigning the double a variable that hold the students Mid-Term exam marks as a integer
double midTermExamMark;
//Assigning the string a variable that hold the students assignment marks from user input
String midTermExamMarkInput;
//Initalizing a keyboard scanner with the variable
Scanner keyboardExamMidTermMark = new Scanner(System.in);
//Asking the user for the Mid-Term Exam mark while printing students name
System.out.printf("Enter %s's mark for Mid-Term Exam (Max. 60): ", studentName);
//Taking the user input and assigning it to our midTermExamMarkInput
midTermExamMarkInput = keyboardExamMidTermMark.nextLine();
//Converting the user input from a string to a double
midTermExamMark = Double.parseDouble(midTermExamMarkInput);
//Assigning the double a variable that hold the students Mid-Term exam marks as a integer
double finalExamMark;
//Assigning the string a variable that hold the students assignment marks from user input
String finalExamMarkInput;
//Initalizing a keyboard scanner with the variable
Scanner keyboardFinalExamMark = new Scanner(System.in);
//Asking the user for the Mid-Term Exam mark while printing students name
System.out.printf("Enter %s's mark for Final Exam (Max. 85): ", studentName);
//Taking the user input and assigning it to our midTermExamMarkInput
finalExamMarkInput = keyboardFinalExamMark.nextLine();
//Converting the user input from a string to a double
finalExamMark = Double.parseDouble(finalExamMarkInput);
//Printing grade report title
System.out.println("Grade report" + "\n------------");
//Printing the students name
System.out.println(studentName + "\n");
//Printing the assignments mark
System.out.printf("%.2f/140 worth 15%%\n", assignmentMarks);
//Printing the Mid-Term exam mark
System.out.printf("%.2f/60 worth 40%%\n", midTermExamMark);
//Printing the Final exam mark
System.out.printf("%.2f/85 worth 45%%\n", finalExamMark);
double finalMark = (assignmentMarks*.15)+(midTermExamMark*.40)+(finalExamMark*.45);
//Printing the total calculated final mark
System.out.printf("\n\nFinal Mark: " + finalMark);
}
}
My code runs fine but it does not do the math correctly and I can't seem to figure out why even if I put everything perfect it still doesn't equal 100%.
This is the equation I'm using and I think this is how it should be done:
(assignmentMarks*.15)+(midTermExamMark*.40)+(finalExamMark*.45)
The maths should be
double finalMark = (assignmentMarks/140*15)+(midTermExamMark/60*40)+(finalExamMark/85*45);
Also I think it is better to not declare (and then later) initialize your variables - do in one step
double assignmentMarks = Double.parseDouble(assignmentMarksInput);
Also just use one Scanner
Scanner scanner = new Scanner(System.in);
and use it for all input
String studentName = scanner.nextLine();
....
String assignmentMarksInput = scanner.nextLine();
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
Scanner scanner = new Scanner(System.in);
int weight;
int age;
//arrays
List<String> last = new ArrayList<String>();
List<Integer> zage = new ArrayList<Integer>();
List<Integer> zweight = new ArrayList<Integer>();
int i = 0;
int userInput = 0;
//menu options
while(userInput != 2) {
userInput = scanner.nextInt(); // collects the user inputs
//several switch statements to answer each menu options
switch(userInput) {
case 1:
it saves and stores all the user inputs.
System.out.println("Enter a last name, age, weight"); //stores all the user information
String lastName = scanner.next();
last.add(lastName);
age = scanner.nextInt();
zage.add(age);
weight = scanner.nextInt();
zweight.add(weight);
break;
Need to add a search code where it will retrieve the user inputs and display it, but i'm not sure on how to do it.
case 5:
System.out.println("Enter the name; Enter DONE to exit");
System.out.println("FOUND!!! Last Name: " +last+ " Age: " +zage+ " Weight: " +zweight);
Your names are stored in a list so you can try this:
if (last.contains(searchName)) {
String foundName = last.get(last.indexOf(searchName));
System.out.println("FOUND!!! Last Name: " +foundName);
} else{
System.out.println("Last Name: " +searchName+ " NOT FOUND!!! ");
}
Note that duplicate names may be in the list so you may want to loop over the indexes.
you can do this:
String enteredLastName = scanner.next();
for (String name : last){
if (name.equals(enteredLastName ){
//do something
}
}
I need to create an array that prompts a professor to input how many students are in their class. Then prompts them to input their names until the number of students is met. What I have is clearly wrong but I was hoping for some insight.
System.out.println("Please enter the number of students in the class: ");
int numberOfStudents = console.nextInt();
String [] studentName = new String [numberOfStudents];
for (int i=0; i<studentName.length; i++)
{
System.out.println("Enter the name of student " + (i+1) + " in your class. ");
studentName[i] = console.nextLine();
System.out.println("Student name entered: " + studentName[i]);
}
EDIT: I changed the code a bit, mainly the array. With the for loop I am intending to simply have it go through each number and assign a student name to it. But with the last line of code it gives me an error saying its a confusing indentation.
EDIT 2: After proofreading my question and the code myself I've noticed very basic mistakes and have dealt with them, but one last question. Right now while the code works, when it asks for me to input the name, it skips student 1, leaves it blank then moves onto student 2. As shown in this screenshot http://puu.sh/8fl8e.png
you weren't far...
Scanner console = new Scanner (System.in);
System.out.println("Please enter the number of students in the class: ");
int numberOfStudents = console.nextInt();
String [] studentName = new String [numberOfStudents];
for (int i=0; i<studentName.length; i++){
System.out.println("Enter the name of student" + (i+1) + "in your class. ");
studentName[i] = console.next();
}
to test the code:
for (int i=0; i<studentName.length; i++){
System.out.println(studentName[i]);
}
EDIT: an answer for your second edit:
use
console.next();
instead of
console.nextLine();
I guess that studentName should be String, not double. And maybe you should consider taking advantage of fact that Java is OO? :)
since you are taking names as input which is string type but you are using double(not possible to store string) and you also missed bracket after for loop.
change
double [] studentName = new double [numberOfStudents];
to
String [] studentName = new String [numberOfStudents];
final correct code:
System.out.println("Please enter the number of students in the class: ");
int numberOfStudents = console.nextInt();
String [] studentName = new String[numberOfStudents];
for (int i=0; i< numberOfStudents; i++){
System.out.println("Enter the name of student" + (i+1) + "in your class. ");
studentName[i] = console.nextLine();
}
System.out.println("Please enter the number of students in the class: ");
int numberOfStudents = console.nextInt();
String [] studentName = new String [numberOfStudents];
for (int i=0; i<studentName.length; i++)
{
System.out.println("Enter the name of student " + (i+1) + " in your class. ");
studentName[i] = console.nextLine();
System.out.println("Student name entered: " + studentName[i]);
}