Adding And Subtracting Positive Or Negative Two Numbers Of Any Length With Strings?
Feb 3, 2014
You are to design a Java application to carry out additions and subtractions for numbers of any length. A number is represented as an object which includes a sign and two strings for the whole and decimal parts of the number. And, the operations must be done by adding or subtracting characters directly. You are not allowed to convert these strings to numbers before the operation.
The program must use a "Number" class which includes at least the following methods:
Number ( );
Number (double n);
Number add (Number RHS);
Number subtract (Number RHS);
String toString ( );
This is what i have but it only adds positive numbers and it doesn't subtract problems like 7.05-8.96. Also some of it was what our teacher gave us like alignwhole method
import java.util.Scanner;
public class Number{
private String whole;
private String decimal;
private String sign;
public static void main (String[] args){
System.out.println("Enter two numbers");
[code]....
View Replies
ADVERTISEMENT
Feb 5, 2014
You are to design a Java application to carry out additions and subtractions for numbers of any length. A number is represented as an object which includes a sign and two strings for the whole and decimal parts of the number. And, the operations must be done by adding or subtracting characters directly. You are not allowed to convert these strings to numbers before the operation.
The program must use a "Number" class which includes at least the following methods:
Number ( );
Number (double n);
Number add (Number RHS);
Number subtract (Number RHS);
String toString ( );
The below code is what our teacher gave us to start with, but it needs to add and subtract positive or negative numbers of any length. This code only adds positive numbers. Need to write code for subtraction .
Java Code:
import java.util.Scanner;
public class Number{
private String whole;
private String decimal;
private String sign;
[Code] .....
View Replies
View Related
Mar 10, 2015
Create an integer array with 10 numbers, initialize the array to make sure there are both positive and negative integers. Write a program to generate two arrays out of the original array, one array with all positive numbers and another one with all negative numbers. Print out the number of elements and the detailed elements in each array.
public class problem3 {
public static void main(String[]args){
int[] numbers = {1, 2, 3, 4, 5, -1, -2, -3, -4, -5};
for (int i = 0; i<numbers.length;){
if(i>0){
System.out.println(numbers);
}
else
System.out.println(numbers);
}
}
}
View Replies
View Related
Mar 10, 2014
For some reason, I'm getting the correct result, but my negative sign is having issues. For example, if I do 1/4 - (-2/4), I get (-3/4).
Here is my minus method for subtracting fractions.
/**
Subtracts a fraction from another fraction.
@param toUse, the fraction to subtract.
@return minusFraction, the result after subtraction.
*/
public Fraction minus(Fraction toUse)
[Code] .....
Here is my reduce() method, just in case...
/**
Reduces the fraction, if possible, to it's simplest form.
Converts negative fractions to the form -x/y, or if -x/-y --> x/y
*/
private void reduce() {
int lowest = Math.abs(numerator);
int highest = Math.abs(denominator);
[code]...
I only switched an operator from my previous addition method, given here as well. I think only switching the + to a - may have caused my issue.
/**
Adds two fractions together.
@param toUse, the fraction to be added.
@return plusFraction, the sum of the two fractions.
*/
public Fraction plus(Fraction toUse) {
[Code] .....
View Replies
View Related
Nov 5, 2014
I have started learning Java and have some across some difficulties. I'm trying to subtract two strings.
for example, with these strings;"032"&&"100". I want to be able to subtract each number individually so that the answer would be "032". 0-1;3-0;2-0;. if i get a negative number, the number would be zero. hence, the 0-1 staying zero in the answer.
I have tried using substring, and parsing the two values to ints, but don't know what to do next. I have also tries using a for loop, to go through each arrays of the strings. I am not allowed to use StringBuilder and I need to return "032".
Here's what i've done so far:
public static String appliquerCoup( String combination, String coup ) {
String nouveauCoup="";
if(combination!=null&&coup!=null){
for(int i=0;i>combinaison.length();i++){
[Code] ....
View Replies
View Related
Feb 4, 2015
The program work somehow, but it can't count the first input when user key in.
import java.util.Scanner;
public class DetermineValues {
public static void main( String[] args ) {
int sum;
int minus;
int data;
[code]....
View Replies
View Related
Feb 7, 2015
I have a problem where I am trying to re arrange the values in an array from negative to positive. I have it re arranged but I cannot figure out how to re arrange them in numerical order. I have to use O(n) and O(1) operations.
Java
import java.util.Arrays;
public class Task7 {
public static void main(String[] args){
int[] numbers = {-19, 6, 34, -3, -8, 23, 5, 678, -45, -12, 76}; //array of positive and negative numbers
int next = 0; //in no particular order
[Code] .....
View Replies
View Related
Dec 10, 2014
I'm taking a class in object oriented programming and we have a task to write a method that returns positive, negative or zero depending on the sum of two variables.
I've had a go at it and i've got to a certain point but i'm struggling to get past this on error - return outside method.
public class Test {
public int sumArgs;
public int arg1;
public int arg2;
[Code] ....
The error occurs on the line 'return "Positive";
View Replies
View Related
Apr 30, 2015
I am trying to make a method that generated a random number between two values that can be negative or positive.
So:
rand(-0.2, 0.2);
would give one of these: -0.2, -0.1, 0, 0.1, 0.2
View Replies
View Related
Mar 15, 2014
Budget program. Here is my situation, I have 2 tabs in a GUI, one tab adds a transactions when the add button is clicked, and in the other tab displays a table showing all the transactions. In my code, I want it so that when the user chooses a deposit(combo box variable name = cbType, indexnumber for deposit is 0) it will add to the total and when the user chooses withdraw(index number is 1) then it will subtract it from the total. Here is the code.... (note as well, the code also adds a new row to the table)
//add button clicked
private class BtnAddActionListener implements ActionListener {
public void actionPerformed(ActionEvent arg0) {
((DefaultTableModel)table.getModel()).addRow(new Object[]{
cbMonth.getSelectedItem() + "/" + txtDay.getText() + "/" + cbYear.getSelectedItem(),
cbCategory.getSelectedItem(),
[Code] .....
So when I tested the program with 2 transactions, the first transaction was a deposit and the 2nd transaction was a withdraw. The end product was that both amounts were subtracted from the total. When I did a withdraw first and a deposit second, the amounts were both added together.
View Replies
View Related
Nov 20, 2014
I am 4 weeks into my Intro to Java course and I am having a bit of trouble with my code. I need to make a program that will take a user inputted number, space the numbers out, then add them to a total sum. What I am having a hard time with is when I enter a negative number. I can't figure out what I need to do to have my program ignore the "-" in the string.
import java.util.*;
public class Week4_Programming_Problem
{
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
int number, digit, sum=0;
char digitPos;
[code]....
View Replies
View Related
Feb 18, 2015
Suppose s, t, and w are strings that have already been created inside main. Write a statement or statements, to be added to main, that will determine if the lengths of the three strings are in order by length, smallest to largest. That is, your code should determine if s is strictly shorter than t, and if t is strictly shorter than w. If these conditions hold your code should print (the boolean value) true. If not, your code should print false. (Strictly means: no ties)
View Replies
View Related
Mar 7, 2014
I need understanding why
1111 1101 = -3
View Replies
View Related
Mar 22, 2014
How do u find the binary of negative numbers? I already did it for positive numbers,?
View Replies
View Related
Oct 18, 2014
how to avoid getting negative numbers of coins, use casting and mod to show how many quarters, dimes, nickels, and pennies there are?
import java.util.Scanner;
public class VM
{
public static void main(String[] args)
{
//money deposit
Scanner input = new Scanner(System.in);
[code]....
View Replies
View Related
Feb 20, 2014
I am very new to Java. I have been working for a couple months on a program for school. It has not gone well. I finally was able to scrap together a working program, but i left something out that needs to be. I have to include input validation to check for negative values, prompting users to re-enter values if negative. I have included my current code, the program works perfectly, but what to do about the negative numbers.
Java Code:
package gradplanner;
import java.util.Scanner;
public class GradPlanner {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int numofclasses = 0;
int totalCUs = 0;
[Code] ....
View Replies
View Related
Feb 20, 2014
I am very new to Java. I have been working on a program. It has not gone well. I finally was able to scrap together a working program, but i left something out that needs to be. I have to include input validation to check for negative values, prompting users to re-enter values if negative.I have included my current code, the program works perfectly, but what to do about the negative numbers.
package gradplanner;
import java.util.Scanner;
public class GradPlanner {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int numofclasses = 0;
[Code] ....
View Replies
View Related
Apr 4, 2015
double CashInsert = Double.parseDouble(CashAmounttxt.getText());
System.out.println("Cash Received: " + "£" + CashInsert);
if (CashInsert<=0 &&(CashInsert <TotalPrice)){
ChangeLeft = CashInsert - TotalPrice;
System.out.println("Total: £" + TotalPrice);
System.out.println("Change Due: " + "£" + ChangeLeft);}
else {
System.out.println("Insuffient funds, please enter £"+ TotalPrice +" or More");}
}
#################################################
Cash Received: £-1.0
Total: £4.85
Change Due: £-5.85
It allows me to enter -1 I've already coded it so the person cannot enter less but -1 works.
View Replies
View Related
Feb 15, 2015
I was inquiring about selecting random numbers from a Fibonacci array, the original post for which is here: Exiting a 'for' Loop Early. I have managed to achieve this with the following code:
System.out.println("Random numbers from the Fibonacci array");
for(int i = 0; i < limit; i++) //Limit is an 'int' of 15 & is set as the length of the Fib. array. I'm calling it for the Random array, too!!
{
Random dice = new Random();
int randomIndex = dice.nextInt(array.length); //The Fib. array was simply called 'array'!!
if (array[randomIndex] < 100)
{
System.out.print(array[randomIndex]+ " ");
}
}
When the code prints I get a random set of numbers which occur in the Fibonacci sequence preceding it. However, the actual length of this Random array also changes each time, and never more than the limit of 15 specified in the 'for' loop. What I want to try and do is print the Random array with a specific length each time. I've tried changing the conditional statement of the 'for' loop in different ways to set the Random array's length, but had no luck.
View Replies
View Related
Nov 16, 2014
My verify method also always returns false. So I'm given three classes to begin with. Calculator, Expression, and InfixExpression and they are listed below.
The goal is to create a class called PostfixExpression that extends Expression and can read and calculate postfix expressions.
My evaluate() method works for most calculations but when it needs to return a negative value it just returns the positive equivalent.
Also, my verify method always returns false and I can't pinpoint why.
Here's my current code. Some things are commented out for debugging purposes.
import java.util.Scanner;
/**
* Simple calculator that reads infix expressions and evaluates them.
*/
public class Calculator
{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
[Code] .....
View Replies
View Related
Apr 3, 2014
I'm having some issues getting this code to reject negative numbers. What I'm doing wrong.
import java.util.Random;
import java.util.Scanner;
public class ForLoop
{
public static void main (String [] args) {
Random randomNumber = new Random();
[Code] ....
This is what I have so far..
View Replies
View Related
Feb 15, 2014
I've been writing a fraction class code below that does a number of arithmetic calcs and when I run it these are the results I get. My gcd doesn't work when it comes to negative fractions and I'm not quite sure how to print.out the boolean methods ((greaterthan)), ((equals))and ((negative)). I'm also not sure if I have implemented those 3 methods properly. I'm still learning how to do unit testing.
Enter numerator; then denominator.
-5
10
-5/10
Enter numerator; then denominator.
3
9
1/3
Sum:
-5/30
-0.16666666666666666
Product:
-5/30
-0.16666666666666666
Devide:
-15/30
-0.5
subtract:
-45/90
-0.5
negative:
1/6
0.16666666666666666
Lessthan:
1/6
0.16666666666666666
greaterthan:
1/6
0.16666666666666666
FRACTION CLASS
import java.util.Scanner;
public class Fraction
{
private int numerator; //numerator
private int denominator; //denominator
[Code] ....
View Replies
View Related
Nov 17, 2014
So I have re-written the code but it is still not running correctly. Any number i type in it throws an exception, also i need the program to add the totals that i type in and then once i type -1 into the prompt button list all the number i typed in and give me the average.
import java.awt.*;
import java.awt.event.*;
import javax.swing .*;
import javax.swing.text.*;
public class Averages extends JFrame
{
//construct components
JLabel sortPrompt = new JLabel("Sort By:");
[Code] .....
View Replies
View Related
Oct 12, 2014
Basically, there is a class "InfiniteInteger" which implements Comparable and can be used to store extremely long numbers as strings (i.e. "37493274839247923749234"). It has a couple functions such as "toString()", "compareTo()" and "isNegative()". Then there's the method I can't quite push through, "add(InfiniteInteger anInfiniteInteger)".Somewhere along the way, it just won't carry numbers correctly... It should work for positive and negative numbers but doesn't quite.
public InfiniteInteger plus(final InfiniteInteger anInfiniteInteger)
{
// TO DO
String number1 = new String(string).replaceAll("-", "");
String number2 = new String(anInfiniteInteger.string).replaceAll("-", "");
int[] firstDigits = new int[number1.length()];
int[] secondDigits = new int[number2.length()];
int place = 0;
for(int i = firstDigits.length - 1; i >= 0; i--) {
firstDigits[place] = Integer.parseInt(Character.toString(number1.charAt(i)));
place++;
}
place = 0;
for(int i = secondDigits.length - 1; i >= 0; i--) {
secondDigits[place] = Integer.parseInt(Character.toString(number2.charAt(i)));
[code]...
I can't use any external packages (i.e. Arrays, BigDecimal, ArrayList) and can't use long as a datatype either.
View Replies
View Related
Jan 13, 2015
It works when i do this ,
String a = "*";
for(int i = 0; i++; i<10){
System.out.println(a);
a = a +"*";
}
but it doesn't work the other way,
String a = "***************";
for(int i = 0; i++; i<10){
System.out.println(a);
a = a - "*";
}
I searched about this online and read strings are unmutable in java but what does that exactly mean ? If the string cannot be changed how i am able to add the characters but not remove them.
View Replies
View Related
Apr 10, 2015
Every time i try and add a new word to personalDictionary, it only replaces the first index. In my personalAdd method i had tried to add a running count to advance the position it would be saving in but it doesn't seem to be working correctly...
Java Code:
import java.util.Arrays;
import java.util.Scanner;
import java.io.File;
import java.io.PrintWriter;
import java.io.FileNotFoundException;
public class SpellingChecker
[Code] ....
View Replies
View Related