Write a java program to accept an unlimited # of double type (variable) expense records with description.
Mean time list in console O/P of the same, and accumulate the total # of entries.
heres my code I have so far
public class Quizz {
public double expense;
public double totalExpenses;
public static void main(String[] args) {
Quizz expenses = new Quizz();
Scanner intScan = new Scanner(System.in);
do
{
System.out.println("Enter an expense");
expenses.expense = intScan.nextInt();
}
while (proceed);
System.out.println("done counting");
}
}
The class definition here is rather weird. You don't really need a class, just a main method to do what you want:
Scanner doubleScan = new Scanner(System.in);
double runningTotal = 0;
do {
System.out.print("Enter an amount (-1 to exit): ");
double expense = doubleScan.nextDouble();
if (expense != -1) runningTotal += expense;
} while (expense != -1);
System.out.println("Total: " + runningTotal);
Related
I am new to JAVA and am writing a program that passes a variable between two separate classes. I cannot seem to figure out how to send the data of a variable from one class to the other and then back? Is such a thing possible?
for example:
Public Class A {
Scanner input = new Scanner(System.in);
System.out.println("Please input the weight:");
bagWeight=input.nextDouble();
System.out.println("The total weight is: "+total);
}
Public Class B {
double number = 3;
public method(double number, double bagWeight)
{
total = bagWeight*number;
return total;
}
}
Sure this is possible :D There are many ways to do so.
For example you can easily do this:
//Obviously pseudo Code...u need a constructor..or method
Public Class A{
Scanner input = new Scanner(System.in);
System.out.println("Please input the weight:");
bagWeight=input.nextDouble();
B b = new B();
double total = b.method(1337, bagWheight);
System.out.println("The total weight is: "+total);
}
I did this once before on a different project, but I have no idea how to do it on this project. I just need to do the calculations for my output in a separate method and then have them print to the console from the main method. I know that this is probably really easy for most of you but I just started coding yesterday, so I have never learned this.
My code:
import java.util.Scanner; // This allows for the use of the scanner in the class
public class SavingsAccount // Start of class
{
public static void main(String[]args) // Start of main
{
double P; // These store the amounts that will be used in the accruing interest formula
double i;
double n;
double S = 0;
int timesLooped = 0;
Scanner readConsole = new Scanner(System.in); // This is the scanner
System.out.println("I am a savings account interest calculator."); // Prompts the user for input
System.out.println("How much money have you deposited?");
P = readConsole.nextDouble();
S = P;
System.out.println("Now, what is the annual interest rate? (i.e. .05)");
i = readConsole.nextDouble();
System.out.println("Finally, how long do you plan on having the money in the account?");
n = readConsole.nextDouble();
while (timesLooped <= n)
{
S = S + (P * i);
timesLooped += 1;
}
System.out.println("Your balance in that time span is " + S + "."); // Tells you your ending balance
}
}
private static double doyourstuff(double d1,double d2,double d3)
{
write your entire logic here as above written in main method.
return calculated_balance;
}
public static void main(String[]args)
{
--read values via scanner as you read above.
double S= doyourstuff(d1,d2,d3);
System.out.println("Your balance in that time span is " + S + ".");-- your final call
}
I have made it a little further. It turns out I can use loops but not arrays in my assignment. So here's the current version (keep in mind no final calculations or anything yet.) So if you look at the homework method, you can see I am asking for the "number of assignments." Now, for each assignment, I need to ask for and sum both the Earned Score and the Maximum Possible Score. So for instance, if there were 3 assignments, they might have earned scores of 18, 22, and 29, and maximum possible scores of 20, 25, and 30 respectively. I need to grab both using the console, but I don't know how to get two variables using the same loop (or in the same method).
Thanks in advance for your help!
import java.util.*;
public class Grades {
public static void main(String[] args) {
welcomeScreen();
weightCalculator();
homework();
}
public static void welcomeScreen() {
System.out.println("This program accepts your homework scores and");
System.out.println("scores from two exams as input and computes");
System.out.println("your grade in the course.");
System.out.println();
}
public static void weightCalculator() {
System.out.println("Homework and Exam 1 weights? ");
Scanner console = new Scanner(System.in);
int a = console.nextInt();
int b = console.nextInt();
int c = 100 - a - b;
System.out.println();
System.out.println("Using weights of " + a + " " + b + " " + c);
}
public static void homework() {
Scanner console = new Scanner(System.in);
System.out.print("Number of assignments? ");
int totalAssignments = console.nextInt();
int sum = 0;
for (int i = 1; i <= totalAssignments; i++) {
System.out.print(" #" + i + "? ");
int next = console.nextInt();
sum += next;
}
System.out.println();
System.out.println("sum = " + sum);
}
}
I don't know where exactly your problem is, so I will try to give you some remarks. This is how I would start (of course there are other ways to implement this):
First of all - create Assignment class to hold all informations in nice, wrapped form:
public class Assignment {
private int pointsEarned;
private int pointsTotal;
public Assignment(int pointsEarned, int pointsTotal) {
this.pointsEarned = pointsEarned;
this.pointsTotal = pointsTotal;
}
...getters, setters...
}
To request number of assignments you can use simply nextInt() method and assign it to some variable:
Scanner sc = new Scanner(System.in);
int numberOfAssignments = sc.nextInt();
Then, use this variable to create some collection of assignments (for example using simple array):
Assignment[] assignments = new Assignment[numberOfAssignments];
Next, you can fill this collection using scanner again:
for(int i = 0; i < numberOfAssignments; i++) {
int pointsEarned = sc.nextInt();
int pointsTotal = sc.nextInt();
assignments[i] = new Assignment(pointsEarned, pointsTotal)
}
So here, you have filled collection of assignments. You can now print it, calculate average etc.
I hope above code gives you some remarks how to implement this.
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
This is very basic java that i'm struggling with n00b style. it just prints out this
Please enter '.' when you want to calculate
1 2 3
.
Numbers are 1 2 3
The Sum is0The Product is1
when it is supposed to calculate the sum and product of those consecutive numbers. something is wrong id appreciate any help!
main method
import java.util.*;
public class NumberScanned {
public static void main(String[] args) {
System.out.println("Please enter '.' when you want to calculate");
Scanner keyboard = new Scanner(System.in);
String scannedString = keyboard.nextLine();
Scanning scanz= new Scanning(scannedString);
while(!keyboard.nextLine().equals("."))
{
scanz.set(scannedString);
}
keyboard.close();
System.out.println("Numbers are"+scannedString);
scanz.printState();
}
}
Class Scanning
public class Scanning {
int num;
int sum;
int product;
String userInput;
public Scanning(String userInput)
{
num=0;
sum=0;
product=1;
this.userInput=userInput;
}
public void set(String userInput)
{
for(int index=0; index<userInput.length(); index++)
{
if(Character.isDigit(userInput.charAt(index))==true)
{
num=userInput.charAt(index);
sum+=num;
product*=num;
}
else
{
index++;
}
}
}
public void printState()
{
System.out.println("The Sum is"+sum+"The Product is"+product);
}
}
A few things to look at:
We know keyboard.nextLine() gets the input from the console, but where are you checking it's validity (more importantly, when do you check it?). Are you looking at all input or just the last line?
isDigit will return true if the passed in character is a number. Do you want to operate on numbers or characters in your for loop?
(a side note, What happens if I enter "1 10" in the console?)
A for loop will automatically increment its index at the end of a loop, so an additional ++ is unnecessary
You might find this helful in case you just need the sum and product values of a user entered
values.
public class ProductSumCalculator{
private static List<Integer> numbers = new ArrayList<Integer>();
public static void main(String[] args){
getInputs();
calculateSumAndProduct();
}
private static void getInputs() {
Scanner scanner = new Scanner(System.in);
System.out.println("Please Enter numbers or ctrl+z to end inputs");
while(scanner.hasNext()){
numbers.add(scanner.nextInt());
}
}
private static void calculateSumAndProduct() {
Iterator<Integer> iterator = numbers.iterator();
int sum=0;
int product=1;
int nextVal;
while(iterator.hasNext()){
nextVal = iterator.next();
sum+=nextVal;
product*=nextVal;
}
System.out.println("Value entered are: "+numbers+".\nThe sum is "+
sum+".The product is "+product);
}
}
You can also try this. You can calculate the sum and product of all the int from your string line input like this:
import java.util.Scanner;
public class Scanning {
/*
* This method returns the integer. If while
* conversion an Exception is thrown it returns
* null. Otherwise the integer.
*/
public static Integer tryParse(String text) {
try {
return Integer.parseInt(text);
} catch (NumberFormatException e) {
return null;
}
}
/*
* Next String line is scanned. It is split by space.
* Stores String tokens in an String array from one String variable.
* Then passed to tryParse() class method. null or auto Boxed Integer
* is returned accordingly. It is auto unboxed from Integer
* object to int variable. Then sum and product is calculated and
* the final result is printed on the console Or Integrated
* Development Environment.
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner keyboard = new Scanner(System.in);
String strInts = keyboard.nextLine();
String[] splits = strInts.split("\\s+");
int i = 0;
Integer anInteger = null;
int total = 0;
int product = 1;
while((i < splits.length)) {
anInteger = tryParse(splits[i]);
if(anInteger != null) {
total = total + anInteger;
product = product * anInteger;
}
++i;
}
System.out.println("The sum is: " + total);
System.out.println("The product is: " + product);
}
}