I am a fairly new programmer in Java and am currently learning about how to incorporate multiple methods in one code. The goal of this practice activity is to use several different methods to:
-Create two arrays (one for employee names and another for how much that employee sold)
-Find the average of total sales
-Find the highest sale number
-Find the name of the Employee(s) with the highest sale count (and print "hooray" for every employee that had the highest sale count)
import java.util.*;
public class MethodActivity{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String[] names={"Employee A", "Employee B", "Employee C", "Employee D", "Employee E", "Employee F", "Employee G", "Employee H", "Employee I", "Employee J"};
System.out.print("Enter the sales numbers, in dollars, for each employee: ");
int num1 = sc.nextInt();
int num2 = sc.nextInt();
int num3 = sc.nextInt();
int num4 = sc.nextInt();
int num5 = sc.nextInt();
int num6 = sc.nextInt();
int num7 = sc.nextInt();
int num8 = sc.nextInt();
int num9 = sc.nextInt();
int num10 = sc.nextInt();
double[] sales={num1, num2, num3, num4, num5, num6, num7, num8, num9, num10};
return double[] sales;
return String[] names;
}
public static double getAverage(double[] sales){
double average=(num1+num2+num3+num4+num5+num6+num7+num8+num9+num10)/10;
return average;
}
public static int getHighestSale(double[] sales){
double highest = sales[0];
int locationOfHighest=0;
if(sales[1]>highest){
highest=sales[1];
locationOfHighest=1;
}else if(sales[2]>highest){
highest=sales[2];
locationOfHighest=2;
}else if(sales[3]>highest){
highest=sales[3];
locationOfHighest=3;
}else if(sales[4]>highest){
highest=sales[4];
locationOfHighest=4;
}else if(sales[5]>highest){
highest=sales[5];
locationOfHighest=5;
}else if(sales[6]>highest){
highest=sales[6];
locationOfHighest=6;
}else if(sales[7]>highest){
highest=sales[7];
locationOfHighest=7;
}else if(sales[8]>highest){
highest=sales[8];
locationOfHighest=8;
}else{
highest=sales[9];
locationOfHighest=9;
}
return highest;
}
public static String showName(String[] names){
String nameOfHighest = "";
String hooray = "";
for (int i = 0; i<names.length; i++){
if (i=locationOfHighest){
nameOfHighest=nameOfHighest+names[i]+", ";
hooray = ""+"hooray ";
}else{
nameOfHighest=nameOfHighest;
}
}
return nameOfHighest;
}
public static void (String[] args){
System.out.println("The average sales for today was: "+average);
System.out.println(nameOfHighest+" made the highest sales of "+highest);
System.out.println(hooray);
}
}
However, when I run the program, I got these errors. The thing is, I don't really understand what they mean:
MethodActivity.java:20: error: '.class' expected
return double[] sales;
^
MethodActivity.java:21: error: '.class' expected
return String[] names;
^
MethodActivity.java:75: error: <identifier> expected
public static void (String[] args){
I would really appreciate if someone could clarify what these mean, since I'm still quite confused by the concept of a multi method code. And, if you could, maybe point out any other issues or fixable elements in my code (since I know my code might look pretty sloppy to someone with programming experience and I could really use some pointers). Thank you for your time.
You need to remove this both returns.
There are two problem in your code:
1) java method can have only one return statement.
2) it is main method and because of it returns void type. void means no return type.
Rather using separate method for printing "public static void (String[] args), print those in main method itself.
Also refer answer by iMBMT.
import java.util.Scanner;
public class MethodActivity {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter Number of employees : ");
int totalEmployeeCount = sc.nextInt();
System.out.println("## totalEmployeeCount : " + totalEmployeeCount);
String[] employeeNames = new String[totalEmployeeCount];
int[] employeeSoldCount = new int[totalEmployeeCount];
String name;
int count;
for (int index = 0; index < totalEmployeeCount; index++) {
System.out.print("Enter employee name : ");
name = sc.next();
System.out.print("Enter employee sale count : ");
count = sc.nextInt();
employeeNames[index] = name;
employeeSoldCount[index] = count;
}
System.out.println("---------------- Pringting all info ----------------");
for (int i = 0; i < employeeNames.length; i++) {
System.out.println("name : " + employeeNames[i] + " & sale count : " + employeeSoldCount[i]);
}
findTheAverageOfTotalSales(employeeSoldCount);
findTheHighestSaleNumber(employeeSoldCount);
}
private static void findTheAverageOfTotalSales(int[] employeeSoldCount) {
for (int saleCount : employeeSoldCount) {
System.out.println("Write your own code ...");
}
}
private static void findTheHighestSaleNumber(int[] employeeSoldCount) {
for (int saleCount : employeeSoldCount) {
System.out.println("Write your own code ...");
}
}
}
Related
I wanted to write a program that records bar inventory as I'm a bartender. I can't figure out how to pass the liquorCost and liquorCount data to the GetCostTotal() method below the main() method. I'm absolutely sure it's something fairly straightforward that I'm doing incorrectly but I just can't figure it out. Any help is appreciated.
My Liquor class is separate and I can post that if necessary but I don't think it's the class that's giving me the problem, it's retrieving the data input from the array to the separate method.
package inventory;
import java.util.Scanner;
public class Inventory {
public static void main(String[] args) {
System.out.println("How many bottles are you taking inventory of?: ");
Scanner keyboard = new Scanner(System.in);
int size = keyboard.nextInt();
Liquor[] inv = new Liquor[size];
for (int i = 0; i < inv.length; i++) {
inv[i] = new Liquor();
System.out.println("Enter product name: ");
inv[i].setLiquorName(keyboard.next());
System.out.println("Enter the count for the product: ");
inv[i].setLiquorCount(keyboard.nextDouble());
System.out.println("Enter the cost for the product: ");
inv[i].setLiquorCost(keyboard.nextDouble());
}
System.out.println("The sitting inventory cost of these products is: ");
//double totalCost = 0
for (Liquor inv1 : inv) {
System.out.println(inv1.getLiquorName() + ": $" + inv1.getLiquorCost() * inv1.getLiquorCount());
}
double costTotal = GetCostTotal(Liquor[] inv, double liquorCost, double liquorCount);
System.out.println("The total cost of the inventory is: "
+ costTotal);
System.exit(0);
}
public static double GetCostTotal(Liquor[] inv, double liquorCost, double liquorCount) {
double costTotal = 0;
for ( int i = 0; i < inv.length; i++) {
costTotal += (liquorCost * liquorCount);
}
return costTotal;
}
}
try this
public static void main(String[] args) {
System.out.println("How many bottles are you taking inventory of?: ");
Scanner keyboard = new Scanner(System.in);
int size = keyboard.nextInt();
Liquor[] inv = new Liquor[size];
for (int i = 0; i < inv.length; i++) {
inv[i] = new Liquor();
System.out.println("Enter product name: ");
inv[i].setLiquorName(keyboard.next());
System.out.println("Enter the count for the product: ");
inv[i].setLiquorCount(keyboard.nextDouble());
System.out.println("Enter the cost for the product: ");
inv[i].setLiquorCost(keyboard.nextDouble());
}
System.out.println("The sitting inventory cost of these products is: ");
//double totalCost = 0
for (Liquor inv1 : inv) {
System.out.println(inv1.getLiquorName() + ": $" + inv1.getLiquorCost() * inv1.getLiquorCount());
}
double costTotal = GetCostTotal(inv);
System.out.println("The total cost of the inventory is: "
+ costTotal);
System.exit(0);
}
public static double GetCostTotal(Liquor[] inv) {
double costTotal = 0;
for ( int i = 0; i < inv.length; i++) {
costTotal += (inv[i].getLiquorCost() * inv[i].getLiquorCount());
}
return costTotal;
}
Lets understand what went wrong here.Take a look at how you are trying to call the GetCostTotal() method.
double costTotal = GetCostTotal(Liquor[] inv, double liquorCost, double liquorCount);
This is incorrect. The syntax/way you are calling the method is actually used when we what to define a method. Like you did:
public static double GetCostTotal(Liquor[] inv, double liquorCost, double liquorCount) {}
Your call should be like:
double costTotal = GetCostTotal(inv);
Here, we are passing only inv because the data for liquorCost and liquorCount is available inside "each" element of array inv.
Now you can accept this argument in GetCostTotal method. Here as you are iterating using a for loop, you can read the data you needed as inv[i].getLiquorCost() and inv[i].getLiquorCount().
I suggest you can read more on defining a method and calling a method in java.
I'm quite new to Java and I've been asked to create a program in which the user is able to input two values and store them in separate arrays. The two values I'm asking the user are name and cell number, then I must allow the user to search by typing either a name or a cell number and return the corresponding name or cell number. I made it possible to input the values and search within them by number but when I try searching by name I get this error :
Exception in thread "main" java.lang.NumberFormatException: For input string: "B"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.base/java.lang.Integer.parseInt(Integer.java:652)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
This is my code:
import java.util.Scanner;
public class HW {
static Scanner sc = new Scanner(System.in);
private static int i, x = 2;
static String names[] = new String[x];
static int numbers[] = new int[x];
public static void main(String[] args) {
Input();
Compare();
}
public static void Input() {
System.out.println("Enter a name followed by the persons number");
while (i < x) {
System.out.println("NAME: ");
names[i] = sc.next();
System.out.println("NUMBER: ");
numbers[i] = sc.nextInt();
i++;
}
}
public static void Compare() {
System.out.println("=======SEARCH=======\nSEARCH CRITERIA: ");
var temp = sc.next();
System.out.println("NAME\tNUMBER");
for (i = 0; i < numbers.length; i++)
if ((names[i].equals(temp)) || (numbers[i] == Integer.parseInt(temp.trim()))) {
System.out.println(names[i] + "\t" + numbers[i]);
}
}
}
Thanks! :)
Looking at your problem statement it doesn't seem like you need to do any additional processing on numbers. Hence, even if you store the number as a string it should be fine in this case.
Hence after getting a user search criteria, you could do a simple string search within both arrays.
Hope this helps :)
First of all, the highest number that can be represented as an int in Java is 2147483647 (214-748-3647). This clearly will not be able to hold a high enough number to accommodate any phone number. To address this issue and also fix your main error, I would suggest storing the numbers as a string instead. Here's my solution:
import java.util.Scanner;
public class HW {
static Scanner sc = new Scanner(System.in);
private static int x = 2;
static String names[] = new String[x];
static String numbers[] = new String[x];
public static void main(String[] args) {
input();
compare();
}
public static void input() {
System.out.println("Enter a name followed by the persons number");
for (int i = 0; i < x; i++) {
System.out.println("NAME: ");
names[i] = sc.next();
System.out.println("NUMBER: ");
numbers[i] = sc.next();
i++;
}
}
public static void compare() {
System.out.println("=======SEARCH=======\nSEARCH CRITERIA: ");
String temp = sc.next();
System.out.println("NAME\tNUMBER");
for (int i = 0; i < numbers.length; i++) {
if ((names[i].equals(temp)) || numbers[i].equals(temp)) {
System.out.println(names[i] + "\t" + numbers[i]);
}
}
System.out.println("===END OF SEARCH====")
}
}
Please also note that I un-defined your variable i. As far as I can see there's no reason for you to be defining it. Hope this helps, good luck!
I'm trying to print the average marks of each subject.
When I try to do that i'm unable to get the output in decimal value.
It is rounding to nearest value.
package cube;
import java.io.*;
import java.util.Scanner;
import java.util.Scanner;
public class ReportCard
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
double DB[][],nos=0;
String S="";
double total1=0, total2=0, total3=0, total4=0, total5=0;
Scanner s = new Scanner(System.in);
void Input()throws Exception
{
System.out.print("Enter The Number Of Students : ");
nos=Integer.parseInt(br.readLine());
DB=new double[(int) (nos+1)][20];
String arrayOfNames[] = new String[(int) nos];
for (int i = 0; i < arrayOfNames.length; i++) {
System.out.print("Enter the name of student:");
arrayOfNames[i] = s.nextLine();
System.out.print("\nEnter "+arrayOfNames[i]+"'s English Score : ");
DB[i][0]=Integer.parseInt(br.readLine());
total1=total1+DB[i][0];
System.out.print("Enter "+arrayOfNames[i]+"'s Science Score : ");
DB[i][1]=Integer.parseInt(br.readLine());
total2=total2+DB[i][1];
System.out.print("Enter "+arrayOfNames[i]+"'s Maths Score : ");
DB[i][2]=Integer.parseInt(br.readLine());
total3=total3+DB[i][2];
DB[i][3]=(int)(DB[i][0]+DB[i][1]+DB[i][2]);
total4=total4+DB[i][3];
DB[i][4]=((int)((DB[i][3])*100)/300);
total5=total5+DB[i][4];
}
System.out.println("\n\n\nStudent Name. English Science \t Maths Total Percentage Pass or Fail \n");
for(int i=0;i<nos;i++)
{
System.out.print(""+arrayOfNames[i]+"\t\t");Padd("English \t ",DB[i][0]);Padd("Science \t ",DB[i][1]);
Padd("Maths \t\t ",DB[i][2]);Padd("Total \t",DB[i][3]);Padd("Percentage\t",DB[i][4]);
if ((DB[i][0])< 50 | (DB[i][1])< 50 | (DB[i][2]) < 50) {
System.out.print("\t\tFail");
}
else {
System.out.print("\t\tPass");
}
System.out.println(S);
S="";
}
//System.out.println(total);
int j=0;
DB[j][0]=(int) (total1/nos);
DB[j][1]=(int) (total2/nos);
DB[j][2]=(int) (total3/nos);
DB[j][3]=(int) (total4/nos);
DB[j][4]=(int) (total5/nos);
System.out.println(DB[j][0]);
System.out.println(DB[j][1]);
System.out.println(DB[j][2]);
System.out.println(DB[j][3]);
System.out.println(DB[j][4]);
System.out.print("\nAverage ");
Padd("English ",DB[j][0]);Padd("Science ",DB[j][1]);Padd("Maths ",DB[j][2]);Padd("Total ",DB[j][3]);Padd("Percentage ",DB[j][4]);
}
void Padd(String S,double dB2)
{
double N=dB2;
int Pad=0,size=S.length();
while(dB2!=0)
{
dB2/=10;
Pad++;
}
System.out.print(" "+N);
for(int i=0;i<size-Pad-4;i++)
System.out.print(" ");
}
public static void main(String args[])throws Exception
{
ReportCard obj=new ReportCard();
obj.Input();
}
}
When I try to change the data type of the j to double it gives me the error "Type mismatch: cannot convert from double to int"
2 quick fixes available
1) Add cast to int
2) Change j to int
could anyone help me fix this please.
Thank you.
Using integer calculations, or casting to an integer, will result in an integer output.
So DB[j][0]=(int) (total1/nos); is going to be an integer value.
DB[j][0] = (total1 / nos); should result in the expected value.
The issue is not with the j variable (which is an index into an array), but the calculation.
However, you'd make your code more readable by defining some constants to use:
private static final int ENG = 0;
private static final int SCI = 1;
private static final int MAT = 2;
private static final int AVG = 3;
DB[i][ENG] = Integer.parseInt(br.readLine());
...
Or better yet make a class for a Student. For example:
class Student
{
final String name;
int englishScore = 0;
int scienceScore = 0;
int mathScore = 0;
public int getEnglishScore()
{
return englishScore;
}
public Student setEnglishScore(int englishScore)
{
this.englishScore = englishScore;
return this;
}
public int getScienceScore()
{
return scienceScore;
}
public Student setScienceScore(int scienceScore)
{
this.scienceScore = scienceScore;
return this;
}
public int getMathScore()
{
return mathScore;
}
public Student setMathScore(int mathScore)
{
this.mathScore = mathScore;
return this;
}
public String getName()
{
return name;
}
Student(String name)
{
this.name = name;
}
}
Also, for testing, always separate input (which could change -- perhaps you'd like to read from a file?), the data handling, and the data output.
I'm working on CS homework and have run into a problem. The end of the homework asks about using a copy constructor. The goal is to "make one Payroll object, instantiate it, make a second one, then print them both. Then, change values in the second Payroll object, and show that the changed values only appear in one and not both (that is, print out the original and the copy with slightly changed values)." I tried changing the values in the second Payroll object, but it also changes it in the first. I've listed my code below:
import java.util.Random;
public class Payroll {
private int[] employeeId;
private int[] hours;
private double[] payRate;
public Payroll(){
this.employeeId = new int[0];
this.hours = new int[0];
this.payRate = new double[0];
}
public Payroll(Payroll obj){
this.employeeId = obj.employeeId;
this.hours = obj.hours;
this.payRate = obj.payRate;
}
public Payroll(int i){
this.employeeId = new int[i];
this.hours = new int[i];
this.payRate = new double[i];
}
public int getEmployeeIdAt(int index){
return employeeId[index];
}
public int getHoursAt(int index){
return hours[index];
}
public double getPayRateAt(int index){
return payRate[index];
}
public double getGrossPay(int index){
double grossPay = hours[index] * payRate[index];
grossPay = Math.round(grossPay * 100);
return grossPay/100;
}
public void setEmployeeIdAt(int index, int id){
this.employeeId[index] = id;
}
public void setHoursAt(int index, int hrs){
this.hours[index] = hrs;
}
public void setPayRateAt(int index, double pr){
this.payRate[index] = pr;
}
public void setHoursAt(int i){
Random rand = new Random();
int randHours = rand.nextInt((50 - 15) + 1) + 15;
this.hours[i] = randHours;
}
}
import java.util.Scanner;
public class PayrollDriver {
public static void main(String[] args) {
Payroll pr = new Payroll(5);
Scanner scan = new Scanner(System.in);
int empID = 1001;
for(int i = 0; i < 5; i++){
pr.setEmployeeIdAt(i, empID);
empID++;
}
for(int i = 0; i < 5; i++){
System.out.println("Enter the hourly pay rate for employee number " + pr.getEmployeeIdAt(i) + ": ");
double payRate = scan.nextDouble();
if(payRate < 7.50){
do{
System.out.println("ERROR: Enter 7.50 or greater for pay rate: ");
payRate = scan.nextDouble();
} while(payRate < 7.50);
}
pr.setPayRateAt(i, payRate);
pr.setHoursAt(i);
}
System.out.println("PAYROLL DATA");
System.out.println("======================");
for(int i = 0; i < 5; i++){
System.out.println("Employee ID: " + pr.getEmployeeIdAt(i) + " Hours: " + pr.getHoursAt(i) + " Rate: " + pr.getPayRateAt(i) +
" Gross Pay: $" + pr.getGrossPay(i));
}
System.out.println("Would you like to run the Copy Constructor Test? Enter 'y' (lowercase) if yes, enter any other letter if no: ");
char copyTestVerify = scan.next().charAt(0);
if(copyTestVerify == 'y'){
CopyConstructorTest ct = new CopyConstructorTest();
ct.CopyTest();
}
scan.close();
}
}
The following is my CopyConstructorTest class, the one that tests whether or not the copy constructor will change the original object's values:
public class CopyConstructorTest {
public void CopyTest(){
Payroll pay = new Payroll(5);
pay.setEmployeeIdAt(0, 1001);
Payroll payCopy = new Payroll(pay);
System.out.println("Original: " + pay.getEmployeeIdAt(0));
System.out.println("Copy: " + payCopy.getEmployeeIdAt(0));
payCopy.setEmployeeIdAt(0, 5000);
System.out.println("Original after changes: " + pay.getEmployeeIdAt(0));
System.out.println("Copy after changes: " + payCopy.getEmployeeIdAt(0));
}
}
I'm not positive on what I'm doing wrong. Any help or guidance is much appreciated.
You are just copying the references to the arrays, not the actual data. Therefore whenever you change the data in one of your objects, the changes are seen in both, since they point to the same array.
The easiest way to copy the data is probably using System.arraycopy():
public Payroll(Payroll obj) {
this.employeeId = new int[obj.employeeId.length];
System.arraycopy(obj.employeeId, 0, this.employeeId, 0, obj.employeeId.length);
...
Im' trying to get user input if he presses "a", he can do the average, calls in average method if he types in "s", he uses the sum method.
Im new to enums so im experimenting. I made an enum that stores a,b and am trying to compare it's values to user input using scanner.
I could be using if statements and forget the whole enum thing but i want to know how it works.
thanks.
public enum RecursionEnum {
s, a
}
main class:
import java.util.*;
public class Recursion {
static RecursionEnum enumtest;
public static void yn() {
Scanner boges = new Scanner(System.in);
System.out.println("Enter a for average or s for sum");
String answer = boges.nextLine();
switch (enumtest) {
case a:
average();
case s:
sums();
}
}
public static void main(String[] args) {
yn();
}
public static int sums() {
int i = 0;
int j = 0;
int sum = i + j;
return sum;
}
public static double average() {
Scanner avgs = new Scanner(System.in);
System.out.println("Enter total number of numbers; ");
double tnum = avgs.nextDouble();
double[] nums = new double[(int) tnum];
double sum = 0;
for (int i = 0; i < tnum; i++) {
System.out.println("Enter number " + (i + 1) + " : ");
nums[i] = avgs.nextDouble();
sum += nums[i];
}
System.out.println(" ");
double avg = sum / tnum;
return avg;
}
}
This is the output:
Enter a for average or s for sum
a
Exception in thread "main" java.lang.NullPointerException
at com.towerdef.shit.Recursion.yn(Recursion.java:14)
at com.towerdef.shit.Recursion.main(Recursion.java:26)
Enumerable types have a synthetic static method, namely valueOf(String), which will return an enum instance matching the input, if it exists. Note that the input is case-sensitive in this case. Trim is used to deal with potential extraneous whitespace.
You can switch on that:
public static void yn() {
Scanner boges = new Scanner(System.in);
System.out.println("Enter a for average or s for sum");
String answer = boges.nextLine();
switch (RecursionEnum.valueOf(answer.trim())) {
case a:
average();
case s:
sums();
}
}
Of course, on Java 7 and higher, you can switching on strings. You may thus use:
public static void yn() {
Scanner boges = new Scanner(System.in);
System.out.println("Enter a for average or s for sum");
String answer = boges.nextLine();
switch (answer.trim()) {
case "a":
average();
break;
case "s":
sums();
break;
}
}