I've made a main method in one class and a lot of other small methods in another class. When I call on them in my main method using their location and making sure that they would outprint if I called on them, they still don't outprint. Only the print two methods show any output. I'm not sure how to go about fixing it so I haven't tried many things yet. Could you look at my code and check why they aren't working?
Update: I've managed to get all the line in the main method except for 28 working with the help I received. Now all that's left is that one output. I've changed the code so it works a bit better and will shut down if it doesn't output, but the output is still missing.package rational;
My Main Method
package rational;
/**
*
* #author Dominique
*/
public class Rational {
public static String number() {
rational1 number= new rational1(27, 3);
String r3= number.printRational(number);
return r3;
}
public static void main(String[] args) {
rational1 number= new rational1(27,3);
System.out.println(number());
String r3=number();
System.out.println(rational1.toDouble(27,3 ));
rational1.add(number);
rational1.invert(r3, number);
rational1.negate(r3, number);
rational1.toDouble(27, 3);
}
}
My Other Method Class
package rational;
/**
*
* #author Dominique
*/
public class rational1 {
public int top;
public int bottom;
public rational1 () {
this.top = 0;
this.bottom = 0;
}
public rational1(int top, int bottom){
this.top=top;
this.bottom=bottom;
}
public String printRational(rational1 r1){
String r3=("Your fraction is "+String.format(r1.top+" / "+r1.bottom));
return r3;
}
public static void invert(String r2, rational1 r1) {
int index = r2.indexOf('s');
if (index != -1) {
System.out.print(r2.substring(0, index+1));//works
System.out.println(" "+r1.bottom + "/" + r1.top);
index++;
}
else {
System.exit(0);
}
}
public static void negate(String r2, rational1 r1){
int index = r2.indexOf('-');
if (index != -1) {
String stringValueOf = String.valueOf(r1.top);
System.out.println(r2.substring(0, 17));//works
System.out.println(r1.bottom+"/"+stringValueOf.substring(1));
index++;
}
}
public static double toDouble(int one, int two){
int three= one/two;
return three;
}
public static double gcd( double a, double b)
{
double r = a % b;
if (r != 0)
{
return gcd(b, r );
}
else
{
return b;
}
}
public static double reduce(double t, double b){
double numberone=gcd(t, b);
double pick=numberone*(b/t);
return pick;
}
public static double add(rational1 r1){
double pickone=(r1.top);
double choice= pickone+pickone;
double choice2=reduce(choice, r1.bottom);
return choice2;
}
}
So the problem is in invert method:
public static void invert(String r2, rational1 r1){
int index = 0;
while (index < 1) {
if (r2.charAt(index) == '/') {
System.out.print(r2.substring(0, 17));
System.out.print(r1.bottom+"/"+r1.top);
index++;
}else{
System.exit(0);
}
`}
}
This method immediate checks the character at r2.charAt(index) == '/'), but this is never the case. Because the character at index = 0 is 'Y' from the printRational method. Because that's not the case then System.exit(0) gets called which immediately ends the program without running the rest of the program.
I believe that this code will work.
public static void invert(String r2, rational1 r1) {
int index = r2.indexOf('/');
if (index != -1) {
index++;
}
else {
System.out.print(r2.substring(0, index));//works
System.out.print(r1.bottom + "/" + r1.top);
}
}
The print method does not necessarily flush the buffer to the screen. Try replacing the print method with the println method.
Once this is in rational package., try to change the system.out.print to system.out.println .Basically all your codes are okay. Try look at this link.
Click [here] (http://introcs.cs.princeton.edu/java/92symbolic/Rational.java.html)!
Related
I want to reverse an int but it doesn't work. For example, 123 should return 321, but the printed number is 356.
public class x {
public static void main(String[] args) {
System.out.println(reverse2(123, 0));
}
static int reverse2(int a, int i) {
if(a == 0) {
return 0;
} else {
i = i*10 + a%10;
System.out.println(i);
return i += reverse2(a/10, i);
}
}
}
Your code should look like this:
public class x {
public static void main(String[] args) {
System.out.println(reverse2(123, 0));
}
static int reverse2(int a, int i) {
if(a == 0) {
return i;
} else {
i = i*10 + a%10;
System.out.println(i);
return reverse2(a/10, i);
}
}
}
You should return i when a is 0.
You shouldn't add i when you call the reverse2 function because you're adding i twice.
You are greatly complicating your recursive function for printing an integer in reverse. For one, there is no good reason for reverse2 to have two integer arguments, as you can achieve your desired results with a single argument. The trick is to access the rightmost digit with the % 10 operation then shift that digit off the number with the / 10 operation. Consider these revisions:
public class x {
public static void main(String[] args) {
System.out.println(reverse2(123));
}
static String reverse2(int number) {
if(number == 0) {
return "";
} else {
return number % 10 + reverse2(number / 10);
}
}
}
You can do it like this. You only need to pass the value you are reversing. The math computation computes 10 to the power of the number of digits in the argument.
public static int reverse(int v) {
int reversed = 0;
if (v > 0) {
int d = (int)Math.pow(10,(int)(Math.log10(v)));
reversed = reverse(v%d) * 10 + v/d;
}
return reversed;
}
Of course, if you can pass a second argument as a scratch pad, then it can be done like so. As you tear down the original value you build up the returned value.
public static int reverse(int v, int reversed) {
if (v > 0) {
return reverse(v / 10, reversed * 10 + v % 10);
}
return reversed;
}
I would like to write simple program which can offer me feature to print n even numbers starting from some firstNumber. Its number is totalNumber. I don't want to save them, just print them. This is my piece of code:
import java.util.Iterator;
public class EvenNumbers implements Iterable<Integer>{
private int firstNumber;
private int totalNumbers;
public EvenNumbers(int firstNumber, int totalNumbers) {
this.firstNumber = firstNumber;
this.totalNumbers = totalNumbers;
}
#Override
public Iterator<Integer> iterator() {
return new myNewIterator();
}
private static class myNewIterator implements Iterator<Integer>{
private int firstNumber;
private int totalNumbers;
private int tmp;
public myNewIterator() {
this.firstNumber = firstNumber;
this.totalNumbers = totalNumbers;
this.tmp = firstNumber - 2;
}
#Override
public boolean hasNext() {
if(totalNumbers > 0){
totalNumbers--;
return true;
}
return false;
}
#Override
public Integer next() {
return tmp + 2;
}
}
}
And Main:
public class Main {
public static void main(String[] args) {
EvenNumbers en = new EvenNumbers(14, 4);
for (Integer n : en) {
System.out.println(n);
}
}
}
As may you can see, I don't get any output for this program.
Can someone explain me what I doing wrong?
Many thanks!
Why do you have so much code?
public class Main {
public static void main(String[] args) {
int start = 14;
int count = 4;
for (int n = start; n < start + 2 * count; n += 2) {
System.out.println(n);
}
}
}
#fafl answer is a better and concise answer.
To point out why this code was not working:
1. The problem is with your myNewIterator constructor. You were assigning the variable with itself. Also as default value of int is zero and your iteration condition if(totalNumbers > 0) will always fail.
public myNewIterator() {
/** these two lines have to be changed**/
this.firstNumber = firstNumber;
this.totalNumbers = totalNumbers;
/** end **/
this.tmp = firstNumber - 2;
}
You have to take these two values from constructor. Following is the corrected code. I have corrected the constructor name as well.
2. you must not decrement totalNumbers in hasNext() method because say there is a only one next element if I call hasNext() 100 times without calling next() it should still return true i.e. it has next element. So decrement should happen when next() is called.
3. tmp must be updated for every next() call.
These changes also are reflected in following code.
import java.util.Iterator;
public class EvenNumbers implements Iterable<Integer>{
private int firstNumber;
private int totalNumbers;
public EvenNumbers(int firstNumber, int totalNumbers) {
this.firstNumber = firstNumber;
this.totalNumbers = totalNumbers;
}
#Override
public Iterator<Integer> iterator() {
/***** changed *****/
return new myNewIterator(this.firstNumber,this.totalNumbers);
}
private static class myNewIterator implements Iterator<Integer>{
private int firstNumber;
private int totalNumbers;
private int tmp;
/***** changed *****/
public myNewIterator(int firstNo,int totalNo) {
/***** changed *****/
/**** edited these lines *******/
this.firstNumber = firstNo;
this.totalNumbers = totalNo;
/***** ****/
this.tmp = firstNumber - 2;
}
#Override
public boolean hasNext() {
if(totalNumbers > 0){
/***** changed *****/
//totalNumbers--; //commenting this line as repeated calls of this line makes this call unsafe
return true;
}
return false;
}
#Override
public Integer next() {
/***** changed *****/
totalNumbers--;
tmp = tmp + 2
return tmp;
}
}
}
I made a test program to try the NewtonRaphsonSolver class through the Apache Commons Math library. Newton's method is used to find roots for a given function.
The test program that I wrote references the cos(x) function (I have a more difficult function to analyze and am looking at the cos(x) function first).
The code for the test program is
import org.apache.commons.math3.analysis.differentiation.DerivativeStructure;
import org.apache.commons.math3.analysis.differentiation.UnivariateDifferentiableFunction;
import org.apache.commons.math3.analysis.solvers.*;
import org.apache.commons.math3.exception.DimensionMismatchException;
public class Test3 {
public static void main(String args[]) {
NewtonRaphsonSolver test = new NewtonRaphsonSolver();
UnivariateDifferentiableFunction f = new UnivariateDifferentiableFunction() {
public double value(double x) {
return Math.cos(x);
}
#Override
public DerivativeStructure value(DerivativeStructure t) throws DimensionMismatchException {
return t.cos();
}
};
for (int i = 1; i <= 500; i++) {
System.out.println(test.solve(1000, f, i, i+0.1));
}
}
}
Not certain if I needed to reference Math.cos(x) and t.cos() twice
public double value(double x) {
return Math.cos(x);
}
#Override
public DerivativeStructure value(DerivativeStructure t) throws DimensionMismatchException {
return t.cos();
}
Newton's method finds all of the zeroes and displays them to the user.
1.5707963267948966
1.5707963267948966
-7.853981633974483
4.71238898038469
4.71238898038469
1.5707963267948966
7.853981633974483
7.853981633974483
10.995574287564276
10.995574287564276
10.995574287564276
10.995574287564276
14.137166941154069
14.137166941154069
14.137166941154069
127.23450247038663
17.278759594743864
17.278759594743864
23.56194490192345
20.420352248333657
20.420352248333657
39.269908169872416
23.56194490192345
23.56194490192345
14.137166941154069
26.703537555513243
26.703537555513243
23.56194490192345
29.845130209103036
29.845130209103036
26.703537555513243
32.98672286269283
32.98672286269283
32.98672286269283
36.12831551628262
36.12831551628262
36.12831551628262
23.56194490192345
39.269908169872416
39.269908169872416
45.553093477052
42.411500823462205
42.411500823462205
Is there some way to prevent printing out zeroes that are duplicates? For example, the above output would read
1.5707963267948966
4.71238898038469
7.853981633974483
10.995574287564276
14.137166941154069
17.278759594743864
20.420352248333657
23.56194490192345
26.703537555513243
29.845130209103036
32.98672286269283
36.12831551628262
39.269908169872416
42.411500823462205
45.553093477052
Can this be done inside a for loop or through an array which only prints out values which are not duplicates?
First question is , what are the same zeros. I would make a class:
class SolutionForZero{
public final double value;
final int hash;
static double tolerance = 1e-6;
public SolutionForZero(double value){
this.value = value;
hash = 1;
}
public boolean equals(Object other){
if( other instanceof SolutionForZero ){
double v = value - other.value;
return (v < 0) ? (-v > tolerance) : (v > tolerance);
}
return false;
}
public int hashCode(){
return hash;
}
}
This class will compare the doubles. To use this class:
Set<SolutionForZero> resultSet = new HashSet<>();
for(double d: yourAnswers){
if(resultSet.add(new SolutionForZero(d))){
System.out.println("'unique' zero at: " + d);
};
}
Now your resultSet will contain only values that are at least tolerance apart.
The hashcode is a bit tricky. The way I have provided will work as long as tolerance is smaller than 1.0. I would appreciate improvements.
import java.util.TreeSet;
import org.apache.commons.math3.analysis.differentiation.DerivativeStructure;
import org.apache.commons.math3.analysis.differentiation.UnivariateDifferentiableFunction;
import org.apache.commons.math3.analysis.solvers.*;
import org.apache.commons.math3.exception.DimensionMismatchException;
public class Test5 {
public static void main(String args[]) {
NewtonRaphsonSolver test = new NewtonRaphsonSolver(1E-10);
UnivariateDifferentiableFunction f = new UnivariateDifferentiableFunction() {
public double value(double x) {
return Math.sin(x);
}
public DerivativeStructure value(DerivativeStructure t) throws
DimensionMismatchException {
return t.sin();
}
};
double EPSILON = 1e-6;
TreeSet<Double> set = new TreeSet<>();
for (int i = 1; i <= 5000; i++) {
set.add(test.solve(1000, f, i, i + EPSILON));
}
for (Double s : set) {
if (s > 0) {
System.out.println(s);
}
}
}
}
I'm creating a program that has a requirement of three classes. The program reads an external text file filled with fractions, and is to return how many times each fraction is repeated. 4/2 has to be reduced to 2/1 and is +1 for the 2/1 count. I believe I am almost done, but I cannot figure out what I need to put into my compareAndIncrement() method in my FractionCounter class. It is suppose to be used to see if the newFraction passed into the function is the same as the Fraction being stored, and if so increments the counter by one and returns true (otherwise, returns false). Below are the codes for my classes.
FractionCounter
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class FractionCounter {
private Fraction theFraction;
private int counter = 0;
public FractionCounter(Fraction theFraction ){
}
public boolean compareAndIncrement(Fraction newFraction){
return false;
}
public String toString(){
return "";
}
public static void main(String[] args){
ObjectList num = new ObjectList();
ObjectList den = new ObjectList();
Scanner fractionFile = null;
try{
fractionFile = new Scanner(new FileInputStream("fractions.txt"));
}
catch (FileNotFoundException e){
System.out.println("File not found.");
System.exit(0);
}
while (fractionFile.hasNextLine()){
String[] part = (fractionFile.nextLine().split("/"));
num.add(Integer.parseInt(part[0]));
den.add(Integer.parseInt(part[1]));
}
}
}
Fraction
public class Fraction {
private int numerator;
private int denominator;
public Fraction() {
}
public Fraction(int num, int den) {
setNumerator(num);
setDenominator(den);
}
public void setNumerator(int num) { //sets numerator
numerator = num;
}
public int getNumerator() { //gets numerator
return numerator;
}
public void setDenominator(int den) { //sets denominator
if(den == 0) {
System.out.println("Error: Denominator = 0");
System.exit(0);
} else {
denominator = den;
}
}
public int getDenominator() { //gets denominator
return denominator;
}
public boolean equals(Fraction that) {
return ((double)this.numerator/this.denominator) == ((double)that.numerator/that.denominator);
}
}
ObjectList
public class ObjectList {
private int[] fraction = new int[100];
private int numElements = 0;
public void add(int n){
fraction[numElements] = n;
numElements++;
}
public String toString(){
String retVal = "";
for (int i = 0; i < numElements; i++){
retVal += fraction[i] + ",";
}
return retVal;
}
public int indexOf(int[] input, int target) {
//returns the index of the inputed value
if(contains(input,target) == true){
for(int i = 0;i <= target;i++) {
if(input[i] == target) {
return i;
}
}
}
return -1;
}
public boolean contains(int[] input, int target) {
//is the target in the inputed array?
for(int i=0;i<input.length; i++) {
if(input[i] == target) {
return true;
}
}
return false;
}
}
Any hints or tips for what I need to do to my method would be much appreciated. I can't figure out a way to do it without using numElements and fraction variables from my ObjectList class. Thank you
I would make a Map to make the counter :
private static final Map<Fraction, Integer> counter = new HashMap<Fraction, Integer>();
and for each Fraction element read for the file I would do :
if(counter.containsKey(fraction)){
Integer count = counter.get(fraction);
count++;
counter.put(fraction, count);
} else {
counter.put(fraction, 1);
}
Moreover, I would make a static parse fonction in the Fraction class which return a Fraction instance from the line you just read. And a toString function to print it easely.
I am practicing recursion and I can't see why this method does not seem to work.
Any ideas?
public void fact()
{
fact(5);
}
public int fact(int n)
{
if(n == 1){
return 1;
}
return n * (fact(n-1));
}
}
Thanks
Your code seems to work but you are not doing anything with the returned value, put method call fact or fact(5) inside of a System.out.println and see what you get.
The recursion part is fine; you're just not using its return value, which gets discarded. Here's a complete Java application of your factorial code, slightly jazzed-up for educational purposes:
public class Factorial {
public static String fact(int n) {
if(n == 1){
return "1";
}
return n + " * " + (fact(n-1)); // what happens if you switch the order?
}
public static void main(String[] args) {
System.out.println(fact(5));
// prints "5 * 4 * 3 * 2 * 1"
}
}
A simplified version of your code:
public int fact(int n)
{
if(n == 1){
return 1;
}
return n * (fact(n-1));
}
could be just:
public int fact(int n)
{
return n == 1 ? 1 : n * fact(n - 1);
}
but your code is not wrong, this is just another style (if you are not used to ternary operator keep the way it is). I prefer use the ternary operator in these cases (observe that the code is side effect free).
Works fine. You're not assigning it to anything. Here's a test that'll prove it works.
#Test
public void testYourFactorialMethod() {
assertEquals(120, fact(5));
}
public class Recursive {
public static void main(String[] argss) {
System.out.print(fac(3));
}
public static int fac(int n) {
int value = 0;
if (n == 0) {
value = 1;
} else {
value = n * fac(n - 1);
}
return value;
}
}
// out put 6
Try something like this:
(Or maybe try this directly)
public class factorial {
private static int factorial( int n ){
if (n > 1) {
return n * (factorial(n-1));
} else {
return 1;
}
}
public static void main(String[] args) {
System.out.println(factorial(100));
}
}
static int factorial(int x) {
int result;
if (x == 1) {
return 1;
}
// Call the same method with argument x-1
result = factorial(x – 1) * x;
return result;
}
For complete example check this
http://answersz.com/factorial-program-in-java-using-recursion/
It is totaly wrong to write Fibonacci with recursive methods!!
It is an old famous example for how a good/bad Algorythm affect any project
if you write Fibonatcci recursive, for calculating 120 you need 36 year toget the result!!!!!!
public static int Fibonacci(int x)
{ // bad fibonacci recursive code
if (x <= 1)
return 1;
return Fibonacci(x - 1) + Fibonacci(x - 2);
}
in dot net 4.0 there is a new type name BigInteger and you can use it to make a better function
using System;
using System.Collections.Generic;
using System.Numerics; //needs a ref. to this assembly
namespace Fibonaci
{
public class CFibonacci
{
public static int Fibonacci(int x)
{
if (x <= 1)
return 1;
return Fibonacci(x - 1) + Fibonacci(x - 2);
}
public static IEnumerable<BigInteger> BigFib(Int64 toNumber)
{
BigInteger previous = 0;
BigInteger current = 1;
for (Int64 y = 1; y <= toNumber; y++)
{
var auxiliar = current;
current += previous;
previous = auxiliar;
yield return current;
}
}
}
}
and you can use it like
using System;
using System.Linq;
namespace Fibonaci
{
class Program
{
static void Main()
{
foreach (var i in CFibonacci.BigFib(10))
{
Console.WriteLine("{0}", i);
}
var num = 12000;
var fib = CFibonacci.BigFib(num).Last();
Console.WriteLine("fib({0})={1}", num, fib);
Console.WriteLine("Press a key...");
Console.ReadKey();
}
}
}
and in this case you can calculate 12000 less than a second. so
Using Recursive methos is not always a good idea
Above code imported from Vahid Nasiri blog whiche wrote in Persian