import java.util.Scanner;
public class Prac3_Q2_JasmineLimSmith {
Scanner scan;
String set;
int setA = 0, setB = 0, setC = 0, setD = 0;
void createFile() throws Exception {
File file = new File("orders.txt");
scan = new Scanner(file);
}
void readData() {
setA = scan.nextInt();
setB = scan.nextInt();
setC = scan.nextInt();
setD = scan.nextInt();
if (scan.hasNextLine())
scan.nextLine();
}
void calcOrder() {
double order = ((setA * 9.90) + (setB * 10.90) + (setC * 11.90) + (setD * 12.90));
double totalOrder = (order);
System.out.println("Set A " + setA);
System.out.println("Set B " + setB);
System.out.println("Set C " + setC);
System.out.println("Set D " + setD);
System.out.printf("Total price: %.2f", order);
System.out.println();
}
public static void main(String args[]) throws Exception {
Prac3_Q2_JasmineLimSmith cc = new Prac3_Q2_JasmineLimSmith();
cc.createFile();
for (int cnt = 1; cnt <= 10; cnt++) {
cc.readData();
cc.calcOrder();
}
}
}
This is the sample output
Set A 1
Set B 4
Set C 3
Set D 2
Total price: 115.00
Sorry, Im new to java, This is my code so far.
In total there would be 10 outputs like that one.
how would i take all the total prices and calculate it into 1 grand total at the very end?
Any help would be appreciated, Thank you
Welcome to StackOverflow! Are you allowed to change the return types of any methods, or add new parameters/methods? Since this seems like homework, I'll give you a general idea of two possible similar approaches.
One way to do this would be to return the total price from calcOrder (by changing the void return type to double). You can then declare an double sumOfOrders = 0 variable outside of your loop where you call calcOrder and then keep adding the return value of calcOrder to it. At the end of the loop, you will have the sum of all orders which you can print out.
For example:
double calcOrder() { // note that the return type has been changed from 'void' to 'double'
double order = ((setA * 9.90) + (setB * 10.90) + (setC * 11.90) + (setD * 12.90));
// print statements
return order;
}
Then, in your main function, you can use the return value when calling calcOrder():
double sumOfOrders = 0;
for (int cnt = 1; cnt <= 10; cnt++) {
cc.readData();
// The following can alternatively be written as
// sumOfOrders += cc.calcOrder();
sumOfOrders = sumOfOrders + cc.calcOrder();
}
System.out.printf("Sum of all orders: %.2f", sumOfOrders);
If you are not allowed to change the return types of existing methods, you could:
Make order an instance variable (e.g. private double orderPrice;
Set order to the sum of all prices (e.g. this.orderPrice = ((setA * 9.90) + ...);)
Add a getter for the orderPrice variable (e.g. by adding a double getOrderPrice() { return this.orderPrice; } method in your Prac3_Q2_JasmineLimSmith class)
Sum the orders in the same way as above:
double sumOfOrders = 0;
for (int cnt = 1; cnt <= 10; cnt++) {
cc.readData();
cc.calcOrder();
sumOfOrders = sumOfOrders + cc.getOrderPrice();
}
System.out.printf("Sum of all orders: %.2f", sumOfOrders);
Related
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 1 year ago.
The output is taking count, name, income and then again income according to the number of counts and then shows outOfBound error for the count.
Here is the code -
public class Main { // Tax Calculator App
public static long calculateTax(long income1){
long tax = 0;
if (income1 >= 300000) {
tax = income1 * 20 / 100;
} else if (income1 >= 100000 && income1 < 300000) {
tax = income1 * 10 / 100;
} else if (income1 < 100000) {
tax = 0;
System.out.println("Tax Amount = 0 ");
}
return tax;
}
public static void main(String[] args) {
System.out.println("Tax Calculator App");
System.out.println("-----WELCOME-----");
Scanner sc = new Scanner(System.in);
System.out.println("Enter total person count: ");
int count = sc.nextInt();
sc.nextLine();
String[] pName = new String[count];
long[] pIncome = new long[count];
System.out.println("Enter the name: ");
for (int i = 0; i <= count; i++) {
pName[i] = sc.nextLine();
System.out.println("Enter the income: ");
}for (int i = 0; i <= count; i++) {
pIncome[i] = sc.nextLong();
sc.nextLine();
long tax = 0;
System.out.println("Name: " + pName + "Tax: " + tax);
}
}
}
You are using a <= (less than or equals) operator in your for loop. This mean it will reach the person count and attempt to index the pName array by the count.
For example, say the count is 1, the array will be initialized with a size of 1, and it'll access pName[0], then pName[1], which is out of bounds, as the size is one.
You're also referencing the entire array in the printed result, you should be indexing to get the person's name.
Revised code for you is here: https://replit.com/#viomckinney/SOHelp#Main.java (Note: Indentation is not perfect as I just did a quick copy)
As #Violet McKinney and #Henry Twist were saying, your array is out of bounds because of the =.
Also, after updating the loop I checked your output is missing the name. The outcome was a java object.
On your last part of the code:
for (int i = 0; i < count; i++) {
pIncome[i] = sc.nextLong();
sc.nextLine();
long tax = 0;
System.out.println("Name: " + pName[i] + "Tax: " + tax);
}
pName => pName[i]
I have the code below:
package Main; import java.util.*;
public class Generator {
List <List<String>>masterList = new ArrayList<List<String>>();
ArrayList memberList = new ArrayList<String>();
String leaderName, memberName;
int numLeaders, numMembers;
double x;
Scanner scanner = new Scanner(System.in);
// This program takes in total number of people first
// Then takes in number of leaders to assign peoples to
// Then takes in people to be assigned
// And then assigns people to given leaders randomly
public int getNumLeader() {
System.out.println("How many leaders are there??");
numLeaders = scanner.nextInt();
return numLeaders;
}
public void setNumLeader(int numLeaders) {
this.numLeaders = numLeaders;
}
public int getNumMembers() {
System.out.println("How many members are there?");
numMembers = scanner.nextInt();
return numMembers;
}
public void setNumMembers(int numMembers) {
this.numMembers = numMembers;
}
public void genLeaders() {
System.out.println("Please type the name of the leader on the following:");
for (int i = 1; i <= numLeaders; i++) {
if (i == numLeaders) {
System.out.println("What is the last leader's name?");
leaderName = scanner.next();
List <String> leaderList = new ArrayList<String>();
masterList.add(leaderList);
} else {
System.out.println("What is the leader" + i + "'s name?");
leaderName = scanner.next();
List <String> leaderList = new ArrayList<String>();
masterList.add(leaderList);
}
}
}
public void genMembers() {
System.out.println("Please enter the members on the following:");
for (int i = 1; i <= numMembers; i++) {
if (i == numMembers) {
System.out.println("What is the last member's name?");
memberName = scanner.next();
memberList.add(memberName);
} else {
System.out.println("What is the member" + i + "'s name?");
memberName = scanner.next();
memberList.add(memberName);
}
}
}
public void /*should return arraylist*/ brackets() {
double y = 1.0/numLeaders;
for (double j = 0.0; j <= 1.0; y++) {
//Generate Linked list with initial element of 0.0
//then 0.0 + y, then 0.0 + y + y ... till 1.0
}
}
public void assignMembers() {
System.out.println("Shuffling members..");
Collections.shuffle(memberList);
System.out.println("Assigning members to leaders now..");
int cellSize = memberList.size()/numLeaders;
for (int i = 0; i <= memberList.size(); i++) {
double x = Math.random();
double y = 1.0/numLeaders;
if (x <= y) {
masterList.get(0).add((String) memberList.get(i));
}
else if (y < x && x <= y + y) {
masterList.get(1).add((String) memberList.get(i));
}
else if (y < x && y + y < x && x <= y + y + y) {
masterList.get(2).add((String) memberList.get(i));
}
// assign given element's name from the big linkedList to the first leader's
// arrayList
}
}
public static void main(String[] args) {
Generator x = new Generator();
x.getNumLeader();
x.getNumMembers();
x.genLeaders();
x.genMembers();
System.out.println(x.memberList);
System.out.println(x.masterList);
System.out.println(x.masterList.get(0));
System.out.println(x.masterList.get(1));
System.out.println(x.masterList.get(2));
}
}
And I made lists within an arraylist, called masterList. I try to assign people in a list within that arraylist, in this manner: masterList.get(0).add((String) memberList.get(i)); Nothing's being added to the list within the arrayList.. what would be the 'correct' way to do this, and is there a way to pinpoint the list within the arraylist, other than 'masterList.get(0)'? Thanks in advance.
You are calling 4 methods, 2 to get numbers of leader and member, and another 2 to generate them. In your generateLeader method, you read name from console but never used it within this method. You are just adding emptylist to master list in this method. The other method generateMembers looks fine as you are adding this in the expected list. I dont see anywhere else that main method calls to populate the emptylist inside the masterlist you added in generateLeaders method.
Also, use nextln to read input, there are scenarios where the linebreak character will still be in buffer when you use just "next" and that linebreak will be read read as next input.
EDIT: HERE IS A SCREENSHOT OF THE OUTPUT
https://www.dropbox.com/s/93d09a627se3b1u/Screenshot%202015-09-16%2019.08.19.png?dl=0]
I was recently asked to make a program that can calculate and display...
1 / (1!) + 1 / (2!) + . . . 1 / (n!)
using the Scanner utility. I seem to be having a lot of trouble with this. the program itself works, but it somehow gives the same answer no matter what number I input. Here's what I have so far (And yes, it is purposely incomplete, I'm stumped).
import java.util.Scanner;
class Power2
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("I will calculate 1/(1!) + 1/(2!) . . . +
1/(n!)\nWhat is the value of n?");
Double n = input.nextDouble();
Math(n);
System.out.println("e = " + Math.E);
}
public static void Math(Double E)
{
Double product = 1.0;
int x = 0;
while (E > 0)
{
product = product * E;
E--;
}
Can anyone give me a way to finish/solve this problem? Thanks a ton.
~Andrew
EDIT: This code works fine for just finding the extreme. I will work on a way to add the preceding components of the equation to this, but It's a bit tricky for me.
import java.util.Scanner;
class Power2
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("I will calculate 1/(1!) + 1/(2!) . . . +
1/(n!)\nWhat is the value of n?");
Double n = input.nextDouble();
Math(n);
System.out.println("e = " + Math(n));
}
public static Double Math(Double E)
{
Double product = 1.0;
while (E > 0)
{
product *= E;
E--;
}
return product;
}
}
You are confused with too much Math.
You've got your method Math with a parameter E and the Java Math class with a constant E. You're mixing them up.
Try
public static double factorial(double v)
{
double product = 1.0;
while (v > 0)
{
product *= v;
v--;
}
return product;
}
Your code:
System.out.println("e = " + Math.E);
Math.E is a constant - it will always print the euler number hence your output.
To call the the method correctly it should be
System.out.println("e = " + math(e)"
Input 1 - Output 1
Input 2 - Output 1.5
Input 3 - Output 1.66666667
import java.util.Scanner;
class MyClass
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("I will calculate 1/(1!) + 1/(2!) . . . + 1/(n!)\nWhat is the value of n?");
double n = input.nextDouble();
double solution = doMath(n);
System.out.println("e = " + solution);
}
public static double doMath(double n) {
double ret = 0;
// the number of terms we add
for (int i = 1; i <= n; i++) {
ret += calcFaculty(i);
}
return ret;
}
// calculate every single term
public static double calcFaculty(double d){
double calc = 1;
for (int i = 1; i <= d ; i++) {
calc = calc* 1/i;
}
return calc;
}
}
Hi Andrew the program always return the same number
e = 2.718281828459045
Because the line System.out.println("e = " + Math.E); is not calling the method Math but calling to the class java.lang.Math. I dont know if is this what you find dubious.
So, I'm trying to create a driver for my method. I apologize in advance, I know very little about what I'm talking about. What the program does, is it calculates sine, cosine, and the exponential function by means of taylor series for a number that the user inputs. The use of Math.pow and Math.fact were not allowed. My compiler isn't giving me any errors, and I'm all out of ideas at this point. In addition, the scanner doesn't seem to stop accepting input after I press enter. It continues to take numbers, but doesn't do anything else. It gives an exception when I type a letter. High possibility of ID10T error. I know that the output isn't well formatted yet, but that's because I haven't had a chance to see it yet. If someone could help me figure this out, I would be very greatful. Thanks in advance!
-An aspiring code monkey
Driver (Lab4.java)
/*
This program is being created to solve Lab 4.
*/
import java.util.*;
public class Lab4
{
public static void main(String[] args)
{
String again, more = "y";
while (more.toUpperCase().charAt(0) == 'Y')
{
Scanner keyboard = new Scanner (System.in);
System.out.println("Input X: ");
Function number = new Function();
double x = number.x();
System.out.println("x = " + x);
Function sine = new Function();
double mySin = sine.funcSine();
Function cosine = new Function();
double myCos = cosine.funcCos();
Function expo = new Function();
double myExp = expo.funcExp();
System.out.println("\t\t\t\tLibraryResult My Result");
System.out.println("\n\t\tsin(" + Function.x() + ")" + " = " + "\t\t\t" + Math.sin(Function.x()) + "\t" + mySin);
System.out.println("\n\t\tcos(" + Function.x() + ")" + " = " + "\t\t\t" + Math.cos(Function.x()) + "\t" + myCos);
System.out.println("\n\t\texp(" + Function.x() + ")" + " = " + "\t\t\t" + Math.exp(Function.x()) + "\t" + myExp);
System.out.println("\n\t\t\tDo more (Y/N) ? ");
more = keyboard.next();
String junk = keyboard.nextLine();
}
}
}
Method (Function.java)
/*
This class provides the information for the parent to use in order to solve Lab 4.
*/
import java.util.*;
public class Function
{
Scanner keyboard = new Scanner(System.in);
public static int number;
private double temp = 1;
private double last = 1;
public static double x()
{
Scanner keyboard = new Scanner(System.in);
double x = keyboard.nextDouble();
return x;
}
public static double pow(double value, double power)
{
if(power == 0)
{
return 1;
}
double result = value;
for(int i = 0; i < power -1; i++)
{
result = result * value;
}
return result;
}
public static double getFact()
{
while (number < 0)
{
number =(number * -1);
}
double factorial = 1;
if (0 == (number % 1))
{
do
{
factorial = factorial * number;
--number;
} while (number >= 1);
}
else //Stirling's Approximation
{
double e = 2.718281828459;
double part1 = Math.sqrt(2 * 3.141592653589 * number);
double part2a = (number / e);
double part2b = (pow(part2a,number));
factorial = (part1 * part2b);
}
return factorial;
}
public static double funcSine()
{
int place = 0;
double next = x()*1;
for(number = 3; number <= 30; number = number + 2)
{
next = next + ((pow((-1),place))*((pow(x(),number))/(getFact())));
place = place + 1;
}
double mySin = next * 1;
return mySin;
}
public static double funcCos()
{
int place = 0;
double next = 1;
for(number = 2; number <= 30; number = number + 2)
{
next = next + ((pow(-1,place))*((pow(x(),number))/(getFact())));
place = place + 1;
}
double myCos = next * 1;
return myCos;
}
public static double funcExp()
{
int place = 0;
double next = 1 + x();
for(number = 1; number <= 30; number++)
{
next = next + ((pow(-1,place))*((pow(x(),number))/(getFact())));
place = place + 1;
}
double myExp = next * 1;
return myExp;
}
}
Check the syntax of your while loop:
while (more.toUpperCase().charAt(0) == 'Y')
Think about when the program will ever not satisfy this expression.
Also you have multiple Scanners all over your code. ITs not clear why you need to keep reading inout over and over again.
Before this the user inputs an int for numOfTimes. Say it's 5. This will ask the question 5 times. But each time through it will erase the previous value in hrs1. It needs to be a separate variable. So if numOfTimes=5 Then I should get 5 different doubles for "Hour " and 5 different doubles for "Minute ". (assuming the user inputs different times) but they all need to be stored in different variables. How should I do this?
Thank you my question has been answered!
use an array ..
int a[] = new int[5];
for(int i =0;i<5;i++){
a[i] = //your value
}
You just need to put your "calculate average" code outside the for loop. I am not sure exactly how you want to calculate the average. But here are two simple ways.
Method one - keep track of the totals and calculate the basic average.
public class AvgTime {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("How many times? ");
int numOfTimes = in.nextInt();
System.out.println("\n");
double hrTotal = 0;
double minTotal = 0;
for (int i = 1; i <= numOfTimes; i++){
System.out.println("What Time (military time): ");
System.out.print("Hour ");
double hrs1 = in.nextDouble();
System.out.print("Minute ");
double min1 = in.nextDouble();
hrTotal += hrs1;
minTotal += min1;
}
//calculate average
double avdHr1 = hrTotal/numOfTimes;
double timeMin1 = minTotal/numOfTimes;
System.out.println(avgHr1+":"+timeMin1 + " P.M");
}
}
Method 2 - Use lists and iterate twice
public class AvgTime {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("How many times? ");
int numOfTimes = in.nextInt();
System.out.println("\n");
ArrayList<Double> hours = new ArrayList<>();
ArrayList<Double> minutes = new ArrayList<>();
double minTotal = 0;
for (int i = 1; i <= numOfTimes; i++){
System.out.println("What Time (military time): ");
System.out.print("Hour ");
double hrs1 = in.nextDouble();
System.out.print("Minute ");
double min1 = in.nextDouble();
hours.add(hrs1);
minutes.add(min1);
}
//calculate average
double avgHr1 = 0;
double timeMin1 = 0:
for (int i = 0; i < hours.size(); i++) {
double hour = hours.get(i);
double minute = minutes.get(i);
//ToDo: calculate average so far
}
System.out.println(avgHr1+":"+timeMin1 + " P.M");
}
You can use arrays to store the information the user has input. Before the loop, make an array using the new keyword, e.g. double[] hrs=new double[numOfTimes]. In the loop, write to different locations in the array for each input, hrs[i]=in.nextDouble(). You can later read from a position on the array using the syntax 'name[index]', such as 'hrs[2]'. Note that for java and many other languages, arrays start at 0. This means for an array [1,2,3] named arr, arr[1] equals 2 instead of 1. This means it would be best if your for loop was changed from for(int i=1;i<=numofTimes;i++) to 'for(int i=0;i
<SOAPBOX,RANT,HIGHHORSE>
This is more of a code review than a straight answer, but something has been bugging me about newbie questions that I've observed on stackoverrflow.
When developing, I avoid keyboard input like the plague. It is such drudgery, especially with a loop such as in this program. So many newbie questions have user-keyboard input. Why?! It makes development so much more difficult!
I've rewritten your program to add the ability for testing data, completely avoiding the need for user-input during development. When testing is over, just switch the test/live comments around.
I'm sure there's a more elegant way, but this style has worked well for me, and I recommend it.
</SOAPBOX,RANT,HIGHHORSE>
import java.util.*;
import static java.lang.Math.abs;
public class AverageTimeWTestingData {
public static void main(String[] args) {
HourMin24[] ahm = null;
//EXACTLY ONE of the following lines must be commented out
//Test only:
ahm = getTestData();
//Live only:
// ahm = getDataFromUserInput();
double dTotalHours = 0.0;
for (HourMin24 hm : ahm){
System.out.println("Time: " + hm.iHour + ":" + hm.iMin);
dTotalHours += hm.iHour + (hm.iMin / 60);
}
System.out.println("Average time (" + ahm.length + "): " + (dTotalHours / ahm.length));
}
private static final HourMin24[] getDataFromUserInput() {
Scanner in = new Scanner(System.in);
System.out.print("How many times? ");
int numOfTimes = in.nextInt();
ArrayList<HourMin24> al24 = new ArrayList<HourMin24>(numOfTimes);
while(numOfTimes < 0) {
System.out.println("What Time (military time): ");
System.out.print("Hour ");
int iHour = in.nextInt();
System.out.print("Minute ");
int iMin = in.nextInt();
al24.add(new HourMin24(iHour, iMin));
numOfTimes--;
}
return al24.toArray(new HourMin24[al24.size()]);
}
private static final HourMin24[] getTestData() {
System.out.println("TEST MODE ON");
return new HourMin24[] {
new HourMin24(13, 1),
new HourMin24(23, 19),
new HourMin24(0, 59),
new HourMin24(16, 16),
};
}
}
class HourMin24 {
public int iHour;
public int iMin;
public HourMin24(int i_hour, int i_min) {
iHour = i_hour;
iMin = i_min;
}
}
Output:
[C:\java_code\]java AverageTimeWTestingData
TEST MODE ON
Time: 13:1
Time: 23:19
Time: 0:59
Time: 16:16
Average time (4): 13.0