Help with calculating fractions in a program...
I'm supposed to declare to fractions and then add, subtract, mulitply, and divide them.
(3, 4)
(2, 3)
The outcome is supposed to look like this...
Number 1 is 3/4
Number 2 is 2/3
Reciprocal of 3/4 is 4/3
Reciprocal of 2/3 is 3/2
3/4 + 2/3 is 17/12
3/4 - 2/3 is 1/12
3/4 * 2/3 is 6/12
3/4 divided by 2/3 is 9/8
And I have my Fraction class all figured out, but I'm not sure how to display the calculations in the main part of my program.
Here is my fraction class
public class Fraction {
private int numerator;
private int denominator;
//Constructor method
public Fraction(int n, int d) {
numerator = n;
denominator = d;
//Returns the fractions numerator
public int getNumerator() {
return numerator;
//Returns the fractions denominator
public int getDenominator() {
return denominator;
//Returns the fractions reciprocal
public Fraction reciprocal() {
//Declare the local variables
int newNumerator;
int newDenominator;
int tempNumerator;
int tempDenominator;
//Swap the two values
newNumerator = denominator
newDenominator = numerator;
//Return a new Fraction as the reciprocal
return new Fraction(newNumerator, newDenominator);
//Returns a string representing numerator/denominator
public String toString() {
return (numerator + "/" + denominator);
public Fraction add(Fraction f2) {
tempNumerator = (numerator * number2.getDenominator()) + (denominator * number2.getNumerator());
tempDenominator = (denominator * number2.getNumerator());
return new Fraction (tempNumerator, tempDenominator);
public Fraction subtract(Fraction f2) {
tempNumerator = (numerator * number2.getDenominator()) - (denominator * number2.getNumerator());
tempDenominator = (denominator * number2.getDenominator());
return new Fraction (tempNumerator, tempDenominator);
public Fraction multiply(Fraction f2) {
tempNumerator = (numerator * number2.getNumerator());
tempDenominator = (denominator * number2.getDenominator());
return new Fraction (tempNumerator, tempDenominator);
public Fraction divide(Fraction f2) {
tempNumerator = (numerator * number2.getDenominator());
tempDenominator = (denominator * number2.getNumerator());
return new Fraction (tempNumerator, tempDenominator);
}
You've got the Fraction class already written and it looks not too bad. Probably there's some bugs, and it won't compile, but that's not your question. Are you saying you have written a Java class, but you don't know how to write a main program to use that class?
Okay, let's suppose you want to get the following output:
Number 1 is 3/4
Reciprocal of 3/4 is 4/3
Then your program would look something like this:public class FractionTest {
public static void main(String[] args) {
Fraction f1 = new Fraction(3, 4);
System.out.println("Number 1 is " + f1);
System.out.println("Reciprocal of " + f1 + " is " + f1.reciprocal());
}
Similar Messages
-
Need help with calculator project for an assignment...
Hi all, I please need help with my calculator project that I have to do for an assignment.
Here is the project's specifications that I need to do"
"""Create a console calculator applicaion that:
* Takes one command line argument: your name and surname. When the
program starts, display the date and time with a welcome message for the
user.
* Display all the available options to the user. Your calculator must include
the arithmetic operations as well as at least five scientific operations of the
Math class.
-Your program must also have the ability to round a number and
truncate it.
-When you multiply by 2, you should not use the '*' operator to perform the
operation.
-Your program must also be able to reverse the sign of a number.
* Include sufficient error checking in your program to ensure that the user
only enters valid input. Make use of the String; Character, and other
wrapper classes to help you.
* Your program must be able to do conversions between decimal, octal and
hex numbers.
* Make use of a menu. You should give the user the option to end the
program when entering a certain option.
* When the program exits, display a message for the user, stating the
current time, and calculate and display how long the user used your
program.
* Make use of helper classes where possible.
* Use the SDK to run your program."""
When the program starts, it asks the user for his/her name and surname. I got the program to ask the user again and again for his/her name and surname
when he/she doesn't insert anything or just press 'enter', but if the user enters a number for the name and surname part, the program continues.
Now my question is this: How can I restrict the user to only enter 'letters' (and spaces of course) but allow NO numbers for his/her surname??
Here is the programs code that I've written so far:
{code}
import java.io.*;
import java.util.*;
import java.text.*;
public class Project {
private static String nameSurname = "";
private static String num1 = null;
private static String num2 = null;
private static String choice1 = null;
private static double answer = 0;
private static String more;
public double Add() {
answer = (Double.parseDouble(num1) + Double.parseDouble(num2));
return answer;
public double Subtract() {
answer = (Double.parseDouble(num1) - Double.parseDouble(num2));
return answer;
public double Multiply() {
answer = (Double.parseDouble(num1) * Double.parseDouble(num2));
return answer;
public double Divide() {
answer = (Double.parseDouble(num1) / Double.parseDouble(num2));
return answer;
public double Modulus() {
answer = (Double.parseDouble(num1) % Double.parseDouble(num2));
return answer;
public double maximumValue() {
answer = (Math.max(Double.parseDouble(num1), Double.parseDouble(num2)));
return answer;
public double minimumValue() {
answer = (Math.min(Double.parseDouble(num1), Double.parseDouble(num2)));
return answer;
public double absoluteNumber1() {
answer = (Math.abs(Double.parseDouble(num1)));
return answer;
public double absoluteNumber2() {
answer = (Math.abs(Double.parseDouble(num2)));
return answer;
public double Squareroot1() {
answer = (Math.sqrt(Double.parseDouble(num1)));
return answer;
public double Squareroot2() {
answer = (Math.sqrt(Double.parseDouble(num2)));
return answer;
public static String octalEquivalent1() {
int iNum1 = Integer.parseInt(num1);
String octal1 = Integer.toOctalString(iNum1);
return octal1;
public static String octalEquivalent2() {
int iNum2 = Integer.parseInt(num2);
String octal2 = Integer.toOctalString(iNum2);
return octal2;
public static String hexadecimalEquivalent1() {
int iNum1 = Integer.parseInt(num1);
String hex1 = Integer.toHexString(iNum1);
return hex1;
public static String hexadecimalEquivalent2() {
int iNum2 = Integer.parseInt(num2);
String hex2 = Integer.toHexString(iNum2);
return hex2;
public double Round1() {
answer = Math.round(Double.parseDouble(num1));
return answer;
public double Round2() {
answer = Math.round(Double.parseDouble(num2));
return answer;
SimpleDateFormat format1 = new SimpleDateFormat("EEEE, dd MMMM yyyy");
Date now = new Date();
SimpleDateFormat format2 = new SimpleDateFormat("hh:mm a");
static Date timeIn = new Date();
public static long programRuntime() {
Date timeInD = timeIn;
long timeOutD = System.currentTimeMillis();
long msec = timeOutD - timeInD.getTime();
float timeHours = msec / 1000;
return (long) timeHours;
DecimalFormat decimals = new DecimalFormat("#0.00");
public String insertNameAndSurname() throws IOException{
boolean inputCorrect = false;
while (inputCorrect == false) {
while (nameSurname == null || nameSurname.length() == 0) {
for (int i = 0; i < nameSurname.length(); i++) {
if ((nameSurname.charAt(i) > 'a') && (nameSurname.charAt(i) < 'Z')){
inputCorrect = true;
else{
inputCorrect = false;
break;
try {
BufferedReader inStream = new BufferedReader (new InputStreamReader(System.in));
System.out.print("Please enter your name and surname: ");
nameSurname = inStream.readLine();
inputCorrect = true;
}catch (IOException ex) {
System.out.println("You did not enter your name and surname, " + nameSurname + " is not a name, please enter your name and surname :");
inputCorrect = false;
System.out.println("\nA warm welcome " + nameSurname + " ,todays date is: " + format1.format(now));
System.out.println("and the time is now exactly " + format2.format(timeIn) + ".");
return nameSurname;
public String inputNumber1() throws IOException {
boolean inputCorrect = false;
while (inputCorrect == false) {
try {
BufferedReader br = new BufferedReader (new InputStreamReader(System.in));
System.out.print("\nPlease enter a number you want to do a calculation with and hit <ENTER>: ");
num1 = br.readLine();
double number1 = Double.parseDouble(num1);
System.out.println("\nThe number you have entered is: " + number1);
inputCorrect = true;
} catch (NumberFormatException nfe) {
System.out.println("\nYou did not enter a valid number: " + "\""+ num1 + "\" is not a number!!");
inputCorrect = false;
return num1;
public String calculatorChoice() throws IOException {
System.out.println("Please select an option of what you would like to do with this number from the menu below and hit <ENTER>: ");
System.out.println("\n*********************************************");
System.out.println("---------------------------------------------");
System.out.println("Please select an option from the list below: ");
System.out.println("---------------------------------------------");
System.out.println("1 - Add");
System.out.println("2 - Subtract");
System.out.println("3 - Multiply");
System.out.println("4 - Divide (remainder included)");
System.out.println("5 - Maximum and minimum value of two numbers");
System.out.println("6 - Squareroot");
System.out.println("7 - Absolute value of numbers");
System.out.println("8 - Octal and Hexadecimal equivalent of numbers");
System.out.println("9 - Round numbers");
System.out.println("0 - Exit program");
System.out.println("**********************************************");
boolean inputCorrect = false;
while (inputCorrect == false) {
try {
BufferedReader inStream = new BufferedReader (new InputStreamReader(System.in));
System.out.print("Please enter your option and hit <ENTER>: ");
choice1 = inStream.readLine();
int c1 = Integer.parseInt(choice1);
System.out.println("\nYou have entered choice number: " + c1);
inputCorrect = true;
} catch (NumberFormatException nfe) {
System.out.println("You did not enter a valid choice number: " + "\""+ choice1 + "\" is not in the list!!");
inputCorrect = false;
return choice1;
public String inputNumber2() throws IOException {
boolean inputCorrect = false;
while (inputCorrect == false) {
try {
BufferedReader br2 = new BufferedReader (new InputStreamReader(System.in));
System.out.print("\nPlease enter another number you want to do the calculation with and hit <ENTER>: ");
num2 = br2.readLine();
double n2 = Double.parseDouble(num2);
System.out.println("\nThe second number you have entered is: " + n2);
System.out.println("\nYour numbers are: " + num1 + " and " + num2);
inputCorrect = true;
} catch (NumberFormatException nfe) {
System.out.println("You did not enter a valid number: " + "\""+ num2 + "\" is not a number!!");
inputCorrect = false;
return num2;
public int Calculator() {
int choice2 = (int) Double.parseDouble(choice1);
switch (choice2) {
case 1 :
Add();
System.out.print("The answer of " + num1 + " + " + num2 + " is: " + decimals.format(answer));
break;
case 2 :
Subtract();
System.out.print("The answer of " + num1 + " - " + num2 + " is: " + decimals.format(answer));
break;
case 3 :
Multiply();
System.out.print("The answer of " + num1 + " * " + num2 + " is: " + decimals.format(answer));
break;
case 4 :
Divide();
System.out.print("The answer of " + num1 + " / " + num2 + " is: " + decimals.format(answer));
Modulus();
System.out.print(" and the remainder is " + decimals.format(answer));
break;
case 5 :
maximumValue();
System.out.println("The maximum number between the numbers " + num1 + " and " + num2 + " is: " + decimals.format(answer));
minimumValue();
System.out.println("The minimum number between the numbers " + num1 + " and " + num2 + " is: " + decimals.format(answer));
break;
case 6 :
Squareroot1();
System.out.println("The squareroot of value " + num1 + " is: " + decimals.format(answer));
Squareroot2();
System.out.println("The squareroot of value " + num2 + " is: " + decimals.format(answer));
break;
case 7 :
absoluteNumber1();
System.out.println("The absolute number of " + num1 + " is: " + decimals.format(answer));
absoluteNumber2();
System.out.println("The absolute number of " + num2 + " is: " + decimals.format(answer));
break;
case 8 :
octalEquivalent1();
System.out.println("The octal equivalent of " + num1 + " is: " + octalEquivalent1());
octalEquivalent2();
System.out.println("The octal equivalent of " + num2 + " is: " + octalEquivalent2());
hexadecimalEquivalent1();
System.out.println("\nThe hexadecimal equivalent of " + num1 + " is: " + hexadecimalEquivalent1());
hexadecimalEquivalent2();
System.out.println("The hexadecimal equivalent of " + num2 + " is: " + hexadecimalEquivalent2());
break;
case 9 :
Round1();
System.out.println("The rounded number of " + num1 + " is: " + decimals.format(answer));
Round2();
System.out.println("The rounded number of " + num2 + " is: " + decimals.format(answer));
break;
case 0 :
if (choice2 == 0) {
System.exit(1);
break;
return choice2;
public String anotherCalculation() throws IOException {
boolean inputCorrect = false;
while (inputCorrect == false) {
try {
BufferedReader br3 = new BufferedReader (new InputStreamReader(System.in));
System.out.print("\nWould you like to do another calculation? Y/N ");
more = br3.readLine();
String s1 = "y";
String s2 = "Y";
if (more.equals(s1) || more.equals(s2)) {
inputCorrect = true;
while (inputCorrect = true){
inputNumber1();
System.out.println("");
calculatorChoice();
System.out.println("");
inputNumber2();
System.out.println("");
Calculator();
System.out.println("");
anotherCalculation();
System.out.println("");
inputCorrect = true;
} else {
System.out.println("\n" + nameSurname + " thank you for using this program, you have used this program for: " + decimals.format(programRuntime()) + " seconds");
System.out.println("the program will now exit, Goodbye.");
System.exit(0);
} catch (IOException ex){
System.out.println("You did not enter a valid answer: " + "\""+ more + "\" is not in the list!!");
inputCorrect = false;
return more;
public static void main(String[] args) throws IOException {
Project p1 = new Project();
p1.insertNameAndSurname();
System.out.println("");
p1.inputNumber1();
System.out.println("");
p1.calculatorChoice();
System.out.println("");
p1.inputNumber2();
System.out.println("");
p1.Calculator();
System.out.println("");
p1.anotherCalculation();
System.out.println("");
{code}
*Can you please run my code for yourself and have a look at how this program is constructed*
*and give me ANY feedback on how I can better this code(program) or if I've done anything wrong from your point of view.*
Your help will be much appreciated.
Thanks in advanceSmirre wrote:
Now my question is this: How can I restrict the user to only enter 'letters' (and spaces of course) but allow NO numbers for his/her surname??You cannot restrict the user. It is a sad fact in programming that the worst bug always sits in front of the Computer.
What you could do is checking the input string for numbers. If it contains numbers, just reprompt for the Name.
AND you might want to ask yourself why the heck a calculator needs to know the users Name. -
Help with calculated column formula- combine strings and convert to date
In my list (SharePoint Server 2013) I have:
'Invoiced Month' column, type of choice (strings with names of months- January, February, March..., December)
'Year' column, single line of text (e.g. 2012, 2013, 2014)
1. I need to create a calculated column which will return combined value of the columns above, but in DATE format e.g. 'Sep-2013' or '01-Sep-2013'.
I then use that newly created calculated column to do this: http://iwillsharemypoint.blogspot.in/2012/03/sharepoint-list-view-of-current-month.html
I am rubbish with formulas, can I have some help with my problem please?Hi,
Use the formula, I have tested by creating Months column with choice, Year column as numeric and Calculated column as DateTime returned.
=DATE(Year,IF([Months]="January", 1,IF([Months]="February",2,IF([Months]="March",3,IF([Months]="April",4,IF([Months]="May",5,IF([Months]="June",6,IF([Months]="July",7,IF([Months]="August",8,IF([Months]="September",9,IF([Months]="October",10,IF([Months]="November",11,12))))))))))),1)
Before applying the formula few things need to be noted.
DATE(YEAR, MONTH,DAY) will accepts three parameters all should be type numeric(integer).
Create the Year column of type numeric
Create the calculated column of type "DateTime" to return as date
Please mark it answered, if your problem resolved or helpful. -
Help with calculation code!! for Times tables program
I am creating a times tables program that lets the user select the Times tables, number of lines required and the type of table (multipy, addition etc).
So if user selects 12 times tables and 4 lines it should look like this on the screen:
12 x 1 = 12
12 x 2 = 24
12 x 3 = 36
12 x 4 = 48
and so on...
Problem is that when I pass the info to the procedure in the below code I am not sure what I need to do to replicate the above.
Appreciate some ideas! Here is code so far:
class assign2{ // Begin Class
public static void main(String[]args){ // Begin Main
int table; // Declare a variable
int lines; // Declare a variable
char type; // Declare a variable
do // Begin do - while loop
System.out.println("Please enter the times tables required (1 - 12)");
Keyboard.skipLine();
table = Keyboard.readInt();
if (table < 1 || table > 12)
System.out.print("INVALID ENTRY - Please try again and enter between 1 and 12"); // Error msg if invalid
System.out.println();
}while (table < 1 || table > 12); // End do - while loop
do // Begin do - while loop
System.out.println("Please enter the number of lines required (1 - 12)");
Keyboard.skipLine();
lines = Keyboard.readInt();
if (lines < 1 || lines > 12)
System.out.print("INVALID ENTRY - Please try again and enter between 1 and 12"); // Error msg if invalid
System.out.println();
}while (lines < 1 || lines > 12); // End do - while loop
do // Begin do - while loop
System.out.println("Please select the table type from one of the following (A - D): ");
System.out.println();
System.out.println("A: Multiplication Tables");
System.out.println("B: Division Tables");
System.out.println("C: Addition Tables");
System.out.println("D: Subtraction Tables");
Keyboard.skipLine();
type = Keyboard.readChar();
if (type != 'a' && type != 'b' && type != 'c' && type != 'd')
System.out.print("INVALID ENTRY - Please try again and enter either A - B - C - D"); // Error msg if invalid
System.out.println();
}while (type != 'a' && type != 'b' && type != 'c' && type != 'd'); // End do - while loop
switch(type){ // Begin Switch
case 'a': getMultiply(table, lines); break;
case 'b': getDivide(); break;
case 'c': getAdd(); break;
case 'd': getSubtract(); break;
} // End Switch
//Procedure to calculate the Multiplication Times Tables//
static void getMultiply(int table, int lines){
//Procedure to calculate the Division Times Tables//
static void getDivide(){
System.out.println("This is divide!!!");
//Procedure to calculate the Addition Times Tables//
static void getAdd(){
System.out.println("This is Add!!!");
//Procedure to calculate the Subtraction Times Tables//
static void getSubtract(){
System.out.println("This is Subtract!!!");
} // Ends Main
} // Ends ClassI wasn't being rudeYes, you were.
or expecting an immediate
responseYour posts suggested otherwise.
I was simply expressing how I was stuck with
the problem.That's not relevant to anybody here. What is relevant is your specific question, which I don't see in your initial post. Just "how do I do this?"
You know what, I am a beginner to this programming
and it's people like you with your smug attitute and
'KNOW IT ALL' behaviour that puts people like me off
even looking to go down this road as a career.Given your attitude so far, I doubt you'll be missed.
So, why don't you stop acting like a spoilt little
child and stop pretending like you own this forum.Flounder was right: Nobody here likes that demanding, "Help me now!" attitude. Coupled with the fact that your question is very vague and the tone of your subsequent posts, you're not doing much to encourage anyone to volunteer their time to help you.
Not to mention that posting the same question multiple times is rude and annoying. It's very irritating to spend time answering a question, only to find out somebody else has already answered it. -
Need help with calculating interest
Hey im trying to find out where my calculations are screwing up on the interest is coming up wrong but i am unable to find out where. After every month its suppose to be deposit - withdrawl * monthly interest rate and then add that total to the new month etc... any help will be appreciated. Heres my class and test
public class SavingsAccount
private double bal;
private double intRate;
The constructor initializes an object with a
balance and an annual interest rate.
@param bal The account balance.
@param intRate The annual interest rate.
public SavingsAccount(double bal, double intRate)
bal= 0.0;
intRate = 0.0;
The withdraw method withdraws an amount from
the account.
@param amount The amount to withdraw.
public void withdraw(double amount)
bal -= amount;
The deposit method deposits an amount into
the account.
@param amount The amount to deposit.
public void deposit(double amount)
bal += amount;
The addInterest method calculates the monthly
interest and adds it to the account balance.
public void addInterest()
// Get the monthly interest rate.
// Calculate the last amount of interest earned.
// Add the interest to the balance.
intRate = bal * (intRate/12);
bal += intRate;
The getBalance method returns the account balance.
@return The account balance.
public double getBalance()
return bal;
The getInterestRate method returns the annual
interest rate.
@return The annual interest rate.
public double getInterestRate()
return intRate;
The getLastInterest method returns the last amount
of interest earned.
@return The last amount of interest earned.
public double getLastInterest()
return bal;
import java.util.Scanner;
import java.text.DecimalFormat;
public class SavingsAccountTest
public static void main(String args[])
// Annual interest rate
double intRate;
// Starting balance
double startBal;
// Amount of deposits for a month
double deposit;
double totalDeposit;
// Amount withdrawn in a month
double withdrawn;
double totalWithdrawn;
// Interest earned
double intEarned = 0;
// Deposit accumulator
deposit = 0.0;
totalDeposit = 0.0;
// Withdrawal accumulator
withdrawn =0.0;
totalWithdrawn = 0.0;
// Months that have passed
double months;
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
// Get the starting balance.
System.out.println("What is your account's starting balance");
startBal = keyboard.nextDouble();
while (startBal < 0)
startBal=0;
// Get the annual interest rate.
System.out.println("What is the annual interest rate?");
intRate = keyboard.nextDouble();
while (intRate <= 0 )
intRate = 0;
// Create a SavingsAccount object.
SavingsAccount account = new SavingsAccount(0.0, 0.0);
// Get the number of months that have passed.
System.out.println("How many months have passed since the " +
"account has opened? ");
months = keyboard.nextDouble();
while (months <= 0)
months = 1;
// Get the deposits and withdrawals for each month.
for (int i = 1; i <= months; i++)
// Get the deposits.
System.out.println("Enter the amount deposited during month " + i);
deposit= keyboard.nextDouble();
totalDeposit += deposit;
while (deposit <=0)
deposit = 0;
// Get the withdrawals.
System.out.println("Enter the amount withdrawn during month " + i);
withdrawn = keyboard.nextDouble();
totalWithdrawn += withdrawn;
while (withdrawn <= 0)
withdrawn = 0;
// Add the deposits to the account.
startBal += deposit;
// Subtract the withdrawals.
startBal -= withdrawn;
// Add the monthly interest.
intRate = startBal * intRate/12;
startBal += intRate;
// Accumulate the amount of interest earned.
intRate += intEarned;
// Create a DecimalFormat object for formatting output.
DecimalFormat dollar = new DecimalFormat("#,##0.00");
// Display the totals and the balance.
System.out.println("Total deposited: " + dollar.format(totalDeposit));
System.out.println("Total withdrawn: " + dollar.format(totalWithdrawn));
System.out.println("Total interest earned: " + dollar.format(intEarned));
System.out.println("Account balance: " + dollar.format(startBal));
}Ok this is what i have fixed up so far but im still having trouble calculating the interest. Problem1) We were given the skeleton to the class and demo. I cannot figure out what to enter in getLastInterest.(completely lost all i need is hint) 2)When i try to get the Total money deposited and i call the account.deposit(balance) it keeps on giving an error void not allowed. Any help is appreciated
public class SavingsAccount
private double balance;
private double interest;
private double intEarned;
The constructor initializes an object with a
balance and an annual interest rate.
@param bal The account balance.
@param intRate The annual interest rate.
public SavingsAccount(double bal, double intRate)
balance = bal;
interest = intRate;
The withdraw method withdraws an amount from
the account.
@param amount The amount to withdraw.
public void withdraw(double amount)
balance -= amount;
The deposit method deposits an amount into
the account.
@param amount The amount to deposit.
public void deposit(double amount)
balance += amount;
The addInterest method calculates the monthly
interest and adds it to the account balance.
public void addInterest()
// Get the monthly interest rate.
// Calculate the last amount of interest earned.
// Add the interest to the balance.
interest = balance * (interest/12);
interest = intEarned;
balance += interest;
The getBalance method returns the account balance.
@return The account balance.
public double getBalance()
return balance;
The getInterestRate method returns the annual
interest rate.
@return The annual interest rate.
public double getInterestRate()
return interest;
The getLastInterest method returns the last amount
of interest earned.
@return The last amount of interest earned.
public double getLastInterest()
return intEarned;
import java.util.Scanner;
import java.text.DecimalFormat;
public class SavingsAccountTest
public static void main(String args[])
// Annual interest rate
double intRate;
// Starting balance
double balance;
// Amount of deposits for a month
double deposit;
// Amount withdrawn in a month
double withdraw;
// Interest earned
double intEarned = 0;
// Deposit accumulator
deposit = 0.0;
// Withdrawal accumulator
withdraw =0.0;
// Months that have passed
double months;
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
// Get the starting balance.
System.out.println("What is your account's starting balance");
balance = keyboard.nextDouble();
if (balance < 0)
balance=0;
// Get the annual interest rate.
System.out.println("What is the annual interest rate?");
intRate = keyboard.nextDouble();
if (intRate <= 0 )
intRate = 0;
// Create a SavingsAccount object. Cannot find Symbol!!
SavingsAccount account = new SavingsAccount(balance,intRate);
// Get the number of months that have passed.
System.out.println("How many months have passed since the " +
"account has opened? ");
months = keyboard.nextDouble();
if (months <= 0)
months = 1;
// Get the deposits and withdrawals for each month.
for (int i = 1; i <= months; i++)
// Get the deposits.
System.out.println("Enter the amount deposited during month " + i);
deposit= keyboard.nextDouble();
account.deposit(deposit);
if (deposit <=0)
deposit = 0;
// Get the withdrawals.
System.out.println("Enter the amount withdrawn during month " + i);
withdraw = keyboard.nextDouble();
account.withdraw(withdraw);
if (withdraw <= 0 || withdraw >= balance)
withdraw = 0;
// Add the deposits to the account.
account.deposit(balance);
// Subtract the withdrawals.
account.withdraw(balance);
// Add the monthly interest.
account.addInterest();
// Accumulate the amount of interest earned. ????? Wrong
intRate += intEarned;
// Create a DecimalFormat object for formatting output.
DecimalFormat dollar = new DecimalFormat("#,##0.00");
// Display the totals and the balance.
System.out.println("Total deposited: " + dollar.format(account.deposit(balance)));
System.out.println("Total withdrawn: " + dollar.format(account.withdraw(balance)));
System.out.println("Total interest earned: " + dollar.format(account.addInterest()));
System.out.println("Account balance: " + dollar.format(account.getBalance()));
} -
Need help with calculated fields in Adobe Interactive Forms
Hi Gurus,
I have an Adobe Interactive form in which i have radio buttons. Upon selecting any of the radio buttons, value in text box should be changed( Calculqated filedS). How i can achieve this?
Regards,
Srini
Moderator message: wrong forum, please post again in Adobe Interactive Forms, but always try yourself before asking.
Edited by: Thomas Zloch on Jul 13, 2010 11:58 AMHi Tapan
No, it's working ,with one remark.
I've done a mistake, in the final formula. The logic remain the same! ;)
The calculation values for second column ( COL2 ) are 1,2,3 and not 0,1,2 as I wrote before and as for COL1 are so the formula is
=3*if(COL1="ABC",0,IF(COL1="DEF",1,2)+if(COL2="RST",1,IF(COL2="YYZ",2,3)
and not
=3*if(COL1="ABC",0,IF(COL1="DEF",1,2)+if(COL2="RST",0,IF(COL2="YYZ",1,2)
I created also a real example for you, with 2 dif calculation ways . First I created 2 calc_columns for COL1 and COL2 ( CALC_COL1+CALC_COL and after I added both these 2 column , and second way is to calculate directly) .
Check this image
Romeo Donca, Orange Romania (MCSE, MCITP, CCNA) Please Mark As Answer if my post solves your problem or Vote As Helpful if the post has been helpful for you. -
Need HELP with objects and classes problem (program compiles)
Alright guys, it is a homework problem but I have definitely put in the work. I believe I have everything right except for the toString method in my Line class. The program compiles and runs but I am not getting the right outcome and I am missing parts. I will post my problems after the code. I will post the assignment (sorry, its long) also. If anyone could help I would appreciate it. It is due on Monday so I am strapped for time.
Assignment:
-There are two ways to uniquely determine a line represented by the equation y=ax+b, where a is the slope and b is the yIntercept.
a)two diffrent points
b)a point and a slope
!!!write a program that consists of three classes:
1)Point class: all data MUST be private
a)MUST contain the following methods:
a1)public Point(double x, double y)
a2)public double x ()
a3public double y ()
a4)public String toString () : that returns the point in the format "(x,y)"
2)Line class: all data MUST be private
b)MUST contain the following methods:
b1)public Line (Point point1, Point point2)
b2)public Line (Point point1, double slope)
b3)public String toString() : that returns the a text description for the line is y=ax+b format
3)Point2Line class
c1)reads the coordinates of a point and a slope and displays the line equation
c2)reads the coordinates of another point (if the same points, prompt the user to change points) and displays the line equation
***I will worry about the user input later, right now I am using set coordinates
What is expected when the program is ran: example
please input x coordinate of the 1st point: 5
please input y coordinate of the 1st point: -4
please input slope: -2
the equation of the 1st line is: y = -2.0x+6.0
please input x coordinate of the 2nd point: 5
please input y coordinate of the 2nd point: -4
it needs to be a diffrent point from (5.0,-4.0)
please input x coordinate of the 2nd point: -1
please input y coordinate of the 2nd point: 2
the equation of the 2nd line is: y = -1.0x +1.0
CODE::
public class Point{
private double x = 0;
private double y = 0;
public Point(){
public Point(double x, double y){
this.x = x;
this.y = y;
public double getX(){
return x;
public double setX(){
return this.x;
public double getY(){
return y;
public double setY(){
return this.y;
public String toString(){
return "The point is " + this.x + ", " + this.y;
public class Line
private double x = 0;
private double y = 0;
private double m = 0;
private double x2 = 0;
private double y2 = 0;
public Line()
public Line (Point point1, Point point2)
this.x = point1.getX();
this.y = point1.getY();
this.x2 = point2.getX();
this.y2 = point2.getY();
this.m = slope(point1, point2);
public Line (Point point1, double slope)
this.x = point1.getX();
this.y = point1.getY();
public double slope(Point point1, Point point2)//finds slope
double m1 = (point1.getY() - point2.getY())/(point1.getX() - point2.getX());
return m1;
public String toString()
double temp = this.x- this.x2;
return this.y + " = " +temp + "" + "(" + this.m + ")" + " " + "+ " + this.y2;
//y-y1=m(x-x1)
public class Point2Line
public static void main(String[]args)
Point p = new Point(3, -3);
Point x = new Point(10, 7);
Line l = new Line(p, x);
System.out.println(l.toString());
}My problems:
I dont have the right outcome due to I don't know how to set up the toString in the Line class.
I don't know where to put if statements for if the points are the same and you need to prompt the user to put in a different 2nd point
I don't know where to put in if statements for the special cases such as if the line the user puts in is a horizontal or vertical line (such as x=4.7 or y=3.4)
Edited by: ta.barber on Apr 20, 2008 9:44 AM
Edited by: ta.barber on Apr 20, 2008 9:46 AM
Edited by: ta.barber on Apr 20, 2008 10:04 AMSorry guys, I was just trying to be thorough with the assignment. Its not that if the number is valid, its that you cannot put in the same coordinated twice.
public class Line
private double x = 0;
private double y = 0;
private double m = 0;
private double x2 = 0;
private double y2 = 0;
public Line()
public Line (Point point1, Point point2)
this.x = point1.getX();
this.y = point1.getY();
this.x2 = point2.getX();
this.y2 = point2.getY();
this.m = slope(point1, point2);
public Line (Point point1, double slope)
this.x = point1.getX();
this.y = point1.getY();
public double slope(Point point1, Point point2)//finds slope
double m1 = (point1.getY() - point2.getY())/(point1.getX() - point2.getX());
return m1;
public String toString()
double temp = this.x- this.x2;
return this.y + " = " +temp + "" + "(" + this.m + ")" + " " + "+ " + this.y2;
//y-y1=m(x-x1)
public class Point2Line
public static void main(String[]args)
Point p = new Point(3, -3);
Point x = new Point(10, 7);
Line l = new Line(p, x);
System.out.println(l.toString());
}The problem is in these lines of code.
public double slope(Point point1, Point point2) //if this method finds the slope than how would i use the the two coordinates plus "m1" to
double m1 = (point1.getY() - point2.getY())/(point1.getX() - point2.getX());
return m1;
public String toString()
double temp = this.x- this.x2;
return this.y + " = " +temp + "" + "(" + this.m + ")" + " " + "+ " + this.y2;
//y-y1=m(x-x1)
}if slope method finds the slope than how would i use the the two coordinates + "m1" to create a the line in toString? -
[New] Help with a VERY simple asterisk program.
Alright...I feel like a complete idiot asking this question..but I'm having such trouble writing this program. The program description is here:
Write a Java application using two for loops to produce the following pattern of asterisks.
I guess I'm really bad at algorithms yeah? Haha...well, any help would be very much appreciated.Hi,
I don't think you don't need to look through any C programming books.
When you have a problem like this, do some thinking about what methods you need to use and what the general structure of the program will be.
You need to print asterisks out to the screen... so you'll need:
System.out.println
System.out.printAnd you already know that you need two loops.
Now you can ask yourself how you might use the print statements with two loops in order to design a basic structure for the program.
You have 8 lines, so you might want a loop that runs through 8 times, one of the lines printed each time.
Within this loop, you need another loop that prints out *'s. This loop could run once for each asterisk, but because there is a different number of asterisks on each line, the number of times this loop runs would be variable.
So a basic structure:
//loop1 that runs 8 times
//loop2 that runs once for each *
print one star
//end loop2
//end loop1The key now is to recognise the difference between print and println. I don't know if you alread know, but System.out.print will print a string without creating a new line at the end, and println will create a new line at the end of the printed string.
Hope that helps. If you have any other problems, post specific questions along with the code you've written and are having trouble with. -
Help with constuctor, need to rewrite program with this constructor
i need to use this constructor for my Scholar class:
public Scholar(String fullName, double gradePointAverage, int essayScore, boolean scienceMajor){here is the project that i'm doing:
http://www.cs.utsa.edu/~javalab/cs17.../project1.html
here's my code for the Scholar class:package project1;
import java.util.*;
public class Scholar implements Comparable {
private static Random rand;
private String fullName;
private double gradePointAverage;
private int essayScore;
private int creditHours;
private boolean scienceMajor;
private String lastName;
private String firstName;
private double totalScore;
/** Creates a new instance of Scholar */
public Scholar(String lastName, String firstName){
this.fullName = lastName + ", " + firstName;
this.gradePointAverage = gradePointAverage;
this.essayScore = essayScore;
this.creditHours = creditHours;
this.scienceMajor = scienceMajor;
this.rand = new Random();
public String getFullName(){
return fullName;
public double getGradePointAverage(){
return gradePointAverage;
public int getEssayScore(){
return essayScore;
public int getCreditHours(){
return creditHours;
public boolean getScienceMajor(){
return scienceMajor;
public String setFullName(String lastName, String firstName){
fullName = lastName + ", " + firstName;
return fullName;
public double setGradePointAverage(double a){
gradePointAverage = a;
return gradePointAverage;
public int setEssayScore(int a){
essayScore = a;
return essayScore;
public int setCreditHours(int a){
creditHours = a;
return creditHours;
public boolean setScienceMajor(boolean a){
scienceMajor = a;
return scienceMajor;
public void scholarship(){
Random doubleGrade = new Random ();
Random intGrade = new Random ();
gradePointAverage = doubleGrade.nextDouble() + intGrade.nextInt(4);
Random score = new Random();
essayScore = score.nextInt(6);
Random hours = new Random();
creditHours = hours.nextInt(137);
Random major = new Random();
int num1 = major.nextInt(3);
if (num1 == 0)
scienceMajor = true;
else
scienceMajor = false;
public double getScore(){
totalScore = (gradePointAverage*5) + essayScore;
if (scienceMajor == true)
totalScore += .5;
if (creditHours >= 60 && creditHours <90)
totalScore += .5;
else if (creditHours >= 90)
totalScore += .75;
return totalScore;
public int compareTo(Object obj){
Scholar otherObj = (Scholar)obj;
double result = getScore() - otherObj.getScore();
if (result > 0)
return 1;
else if (result < 0)
return -1;
return 0;
public static Scholar max(Scholar s1, Scholar s2){
if (s1.getScore() > s2.getScore())
System.out.println(s1.getFullName() + " scored higher than " +
s2.getFullName() + ".\n");
else
System.out.println(s2.getFullName() + " scored higher than " +
s1.getFullName() + ".\n");
return null;
public static Scholar max(Scholar s1, Scholar s2, Scholar s3){
if (s1.getScore() > s2.getScore() && s1.getScore() > s3.getScore())
System.out.println(s1.getFullName() + " scored the highest" +
" out of all three students.");
else if (s2.getScore() > s1.getScore() && s2.getScore() > s3.getScore())
System.out.println(s2.getFullName() + " scored the highest" +
" out of all three students.");
else if (s3.getScore() > s2.getScore() && s3.getScore() > s1.getScore())
System.out.println(s3.getFullName() + " scored the highest" +
" out of all three students.");
return null;
public String toString(){
return "Student name: " + fullName + " -" + " Grade Point Average: "
+ gradePointAverage + ". " + "Essay Score: " + essayScore + "."
+ " Credit Hours: " + creditHours + ". " + " Science major: "
+ scienceMajor + ".";
}here's my code for the ScholarTester class:package project1;
import java.util.*;
public class ScholarTester {
public static void main(String [] args){
System.out.println("This program was written by Kevin Brown. \n");
System.out.println("--------Part 1--------\n");
Scholar abraham = new Scholar("Lincoln", "Abraham");
abraham.scholarship();
System.out.println(abraham);
/*kevin.setEssayScore(5);
kevin.setGradePointAverage(4.0);
kevin.setCreditHours(100);
kevin.setFullName("Brown", "Kevin J");
kevin.setScienceMajor(true);
System.out.println(kevin);*/
Scholar george = new Scholar("Bush", "George");
george.scholarship();
System.out.println(george + "\n");
System.out.println("--------Part 2--------\n");
System.out.println(abraham.getFullName() + abraham.getScore() + ".");
System.out.println(george.getFullName() + george.getScore() + ".\n");
System.out.println("--------Part 3--------\n");
if(abraham.compareTo(george) == 1)
System.out.println(abraham.getFullName() + " scored higher than " +
abraham.getFullName() + ".\n");
else
System.out.println(abraham.getFullName() + " scored higher than " +
abraham.getFullName() + ".\n");
System.out.println("--------Part 4--------\n");
Scholar.max(abraham, george);
Scholar thomas = new Scholar("Jefferson", "Thomas");
thomas.scholarship();
System.out.println("New student added - " + thomas + "\n");
System.out.println(abraham.getFullName() + " scored " +
abraham.getScore() + ".");
System.out.println(george.getFullName() + " scored " +
george.getScore() + ".");
System.out.println(thomas.getFullName() + " scored " +
thomas.getScore() + ".\n");
Scholar.max(abraham, george, thomas);
}everything runs like it should and the program is doing fine, i just need to change the format of the Scholar constructor and probably other things. Can someone please give me an idea how to fix this.
Thanks for taking your time reading this.then don't reply if you're not going to read it, i
just gave the url, Don't get snitty. I'm just informing you that most people here don't want to click a link and read your whole bloody assignment. If you want help, the burden is on you to make it as easy as possible for people to help you. I was only trying to inform you about what's more likely to get you help. If doing things your way is more important to you than increasing your chances of being helped, that's your prerogative.
so you can get an idea on what
it's about, and yeah i know how to add a constructor,
that's very obvious, That's what I thought, but you seemed to be saying, "How do I add this c'tor?" That's why I was asking for clarification about what specific trouble you're having.
i just want to know how to
implement everything correctly, so don't start
flaming people. I wasn't flaming you in the least. I was informing you of how to improve your chances of getting helped, and asking for clarification about what you're having trouble with. -
I'm a newbie to SSAS and am having trouble creating a calculated member. My goal is to calculate the number of requests based on status in a specific month/year, however I'd like to enable users to show all amounts on a single report.
An excerpt of my cube is as follows:
FACT REQUESTS
Measures.Request Count
DIM STATUS
Status Description (i.e. Active/Inactive)
I'd like to create calculated members that will produce the following type of report:
Month Year Total Active Total Inactive
Jan 2013 10 20
Feb 2013 10 25
I previously processed the following code:
CREATE MEMBER CURRENTCUBE.[Measures].[Total Active Requests]
AS NULL, VISIBLE = 1;
Scope [Measures].[Total Active Requests];
Scope [DIM STATUS].[Status Description].[ACTIVE];
THIS = SUM ([Measures].[Request Count]);
END SCOPE;
END SCOPE;
CREATE MEMBER CURRENTCUBE.[Measures].[Total Inactive Requests]
AS NULL, VISIBLE = 1;
Scope [Measures].[Total Closed Requests];
Scope [DIM STATUS].[Status Description].[INACTIVE];
THIS = SUM ([Measures].[Request Count]);
END SCOPE;
END SCOPE;
However when pulling the values over to the report, the users were unable to see both Active and Inactive at the same time (so I'm guessing Scope isn't the best approach). Is there another method I can follow? I appreciate any help you can offer.
Thanks!!no need for a scope statement, try the following with 2 different calc measures.
IIF(ISERROR([DIM STATUS].[Status Description].&[ACTIVE]), NULL,([DIM
STATUS].[Status Description].&[ACTIVE],[Measures].[Request Count]))
IIF(ISERROR([DIM STATUS].[Status Description].&[INACTIVE]),
NULL,([DIM STATUS].[Status Description].&[INACTIVE],[Measures].[Request
Count]))
you can ignore the iif statement, thats just for error handling. -
Help with calculated dimension member
I am trying to create a (custom) dimension member using a simple calculation (subtraction e.g. member1 - member2) in AWM 9.2.0.4 following the example given in the Oracle OLAP DML Reference 10g (using DML). I could not find any articles relating to this for 9i. Although the custom member is easily added to the dimension, I could not populate it with the specified calculation.
I need to enable the analytic workspace for OLAP API and BI Beans. Can anyone help?Hi,
Use the formula, I have tested by creating Months column with choice, Year column as numeric and Calculated column as DateTime returned.
=DATE(Year,IF([Months]="January", 1,IF([Months]="February",2,IF([Months]="March",3,IF([Months]="April",4,IF([Months]="May",5,IF([Months]="June",6,IF([Months]="July",7,IF([Months]="August",8,IF([Months]="September",9,IF([Months]="October",10,IF([Months]="November",11,12))))))))))),1)
Before applying the formula few things need to be noted.
DATE(YEAR, MONTH,DAY) will accepts three parameters all should be type numeric(integer).
Create the Year column of type numeric
Create the calculated column of type "DateTime" to return as date
Please mark it answered, if your problem resolved or helpful. -
Help with calculations in XMLP Template
Hi,
I would like to get some guidance on how the below could be done in XMLP. I am getting the 'Amount' column from FSG and would like to calculate the percentage in the template. Is it possible to calculate rows and store results in column like in the example below in XMLP? Many thanks for your help.
Type-------Amount-----%
Gross-----------10-----166.7 (Gross/Net*100)
Discount---------4-------66.7 (Discount/Net*100)
======================
Net (G-D)--------6-----100.0 (Net/Net*100) or (Gross% - Discount%)Hi Hazan,
I have done a similar Gross Margin Report using XMLP 5.5.
I have used the concept of variables to store temporary values in my report and carry out complex calculations.
Please let me know what version of XMLP are you using?
Some of my form fields containing variables look like this:
<?xdoxslt:set_variable($_XDOCTX, Sum1, CS_TCOST + CS_TCOST1)?>
<?xdoxslt:get_variable($_XDOCTX, Sno )?> <?xdoxslt:set_variable($_XDOCTX, Sno, xdoxslt:get_variable($_XDOCTX, Sno) + 1)?>
<?xdofx:if(CS_TSELL + CS_TSELL1) <= 0 then
xdoxslt:set_variable($_XDOCTX, Sum1, 1)
end if?>
I am not sure if you are looking at this or not. Do let me know if this solves the purpose and need be required some help :-o)
HTH,
Nitin -
Need help with algorithm for my paint program
I was making a paint program with using a BufferedImage where the user draws to the BufferedImage and then I draw the BufferedImage onto the class I am extending JPanel with. I want the user to be able to use an undo feature via ctrl+z and I also want them to be able to update what kind of paper they're writing on live: a) blank paper b) graph paper c) lined paper. I cannot see how to do this by using BufferedImages. Is there something I'm missing or must I do it another way? I am trying to avoid the other way because it seems too demanding on the computer but if this is not do-able then I guess I must but I feel I should ask you guys if what I am doing is logical or monstrous.
What I am planning to do is make a LinkedList that has the following 4 parameters:
1) previous Point
2) current Point
3) current Color
4) boolean connectPrevious
which means that the program would basically draw the instantaneous line using the two points and color specified in paintComponent(Graphics g). The boolean value is for ctrl+z (undo) purposes. I am also planning to use a background thread to eliminate repeated entries in the LinkedList except for the last 25 components of the LinkedList (that number might change in practice).
What do you guys think?
Any input would be greatly appreciated!
Thanks in advance!Look at the package javax.swing.undo package - UndoableEdit interface and UndoManager class.
Just implement the interface. Store all necessary data to perform your action (colors, pixels, shapes etc.). Add all your UndoableEdits in an UndoManager instance and call undo() redo() when you need. -
Need help with updates and new apple programs
something happened to my pc. having problems with my pc when it restarts.
wondered if anyone whichapple updates require a restart, and which don't?
if they require a restart to finish installation, they fail, and my pc crashes, and i have to resintall os.
i know the iwork does not require a restart, where ilife does. so for now, i can install iwork, but not ilife.
in anyone familiar with 10.5.6 knows which updates/add ond require a restart and which don't, please post. any help appreciated. 4th re install now.Hey network --
Sorry to hear of your problems . . .
What Mac are you running there?
Did the installation of 10.5.6 finally go well?
You're having problems with iLife, but what about Snow Leopard? -
Help with making photoshop the default program to open pictures.
I subscribe to Adobe Creative Cloud and use Photoshop the most. I of course want all my pictures to have Photoshop as the default application to open them but I can't get it to work. When I go to "open with" to change to photoshop it doesn't automatically show up as one of my options so I go to "browse" and find it under program files, adobe, Photoshop cc but when I click on it and accept it won't keep it. It keeps going back to a different program. I can't change to default to acrobat or other programs, just not Photoshop. What am I doing wrong?
Thank you.Working with your Operating System’s Tools | Mylenium's Error Code Database
Mylenium
Maybe you are looking for
-
hi in order to use this : is this a stand alone or i should have somthing on my server in order to use it? (i.e special extention) sorry if the question is dumb tx
-
IPod Causes Computer to Reboot
This happens on occasion, but it's starting to get to me... My computer will sometimes reboot when I plug in my iPod... I would like to point out a few things about my configuration. To make my computer faster, I disabled a lot of services in Windows
-
Multiple notification against single inspection lot (03 inspection type)
Dear friends While recording the defects multiple times against single inspection lot (03type) , all the defects are added in single notification, but my client requirement is they want different notification. if any body knows please tell me. Note
-
Help, I am under attack.
Today I have discovered some data in a database that makes me think that some is trying an sql injection attack on one of my websites. I use SP's and Cfqueryparam to protect myself against this type of attack and as a general rule before doing anythi
-
I can't watch a video that I Baught on my iPad . When I push play it flips &go back to play