Iterating over data without saving it - java

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;
}
}
}

Related

Method that checks if the method was already executed with that input

public class CatalanNumbers {
private int howManyVariaties;
private int catalanNumber;
private int catalanNumber;
public int catalan(int a) {
if (Method was never executed with that input) {
howManyVariaties++;
int catalanNumber = 0;
for (int i= 0; i < n; i++) {
catalanNumber += catalan(i) * catalan( n- 1 -i);
return catalanNumber
To sum it up I only want to check how the maximum stack depth is.
Can someone help me?
Add a Set to your class that keeps track of what input was used and check that set inside the method
public class CatalanNumbers {
private int howManyVariaties;
private int catalanNumber;
private int catalanNumber;
private Set<Integer> alreadyHandled = new HashSet<>();
public int catalan(int a) {
if (alreadyHandled.add(a)) {
//rest of code
}
}
//...
}

Why won't my method print out?

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)!

Sum of Multiples of 3 and 5 using Methods: Incorrect sum coming

I have been trying to solve Project Euler Problem #1 using "methods" in Java. It is giving correct multiples. However, sum is not coming right. Here are my codes:
Method Class:
package lessons;
public class method {
int a,b, add;
public void multipleThree()
{
for (a=3; a<1000; a+=3)
{
System.out.println(a);
}
}
public void multipleFive(){
for (b=5; b<1000; b+=5)
{
System.out.println(b);
}
}
public void sum(){
add= a+b;
System.out.println("The sum is "+ add);
}
}
Main Class
package lessons;
public class Lessons {
public static void main(String[] args) {
method problem = new method();
problem.multipleThree();
problem.multipleFive();
problem.sum();
}}
Any helps???
a+b is calculated once - outside your loop. The result will be the sum of the final values of a and b. If you want to sum each element in each loop, you'll need to update add inside the loops:
public class method {
int add = 0;
public void multipleThree() {
for (int a=3; a<1000; a+=3) {
System.out.println(a);
add += a;
}
}
public void multipleFive(){
for (int b=5; b<1000; b+=5) {
System.out.println(b);
add += b;
}
}
public void sum(){
System.out.println("The sum is "+ add);
}
}
The output for multipleThree() and multipleFive() is 999 and 995 accordingly. However a and b are incremented in the for loops one more time to meet the exit condition therefor their sum is 2002 and not 1994.
You can change sum() to this
public void sum(){
add = a + b - 8;
System.out.println("The sum is "+ add);
}
Declare variables separately,
class method {
int i, j, add;
public void multipleThree() {
for (int a = 3; a < 1000; a = a + 3) {
System.out.println(a);
i = a;
}
}
public void multipleFive() {
for (int b = 5; b < 1000; b = b + 5) {
System.out.println(b);
j = b;
}
}
public void sum() {
add = i + j;
System.out.println("The sum is " + add);
}
}
Check below
package lessons;
public class method {
int a,b, add;
public void multipleThree()
{
for (a=3; a<1000; a+=3)
{
System.out.println(a);
}
a=a-3;//added this
}
public void multipleFive(){
for (b=5; b<1000; b+=5)
{
System.out.println(b);
}
b=b-5;//added this
}
public void sum(){
add= a+b;
System.out.println("The sum is "+ add);
}
}
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner z = new Scanner(System.in);
int N = z.nextInt();
while(N!=0)
{
long number = z.nextInt();
long p = (number-1)/3;
long sum1 = (p*(6+((p-1)*3)))/2;
long q = (number-1)/5;
long sum2 = (q*(10+((q-1)*5)))/2;
long r = (number-1)/15;
long sum3 = (r*(30+((r-1)*15)))/2;
System.out.println(sum1+sum2-sum3);
}
}
}
This is best way to solve the given problem passed all test cases.Happy coding

Check repetition of fractions of external file

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.

implementing a loop using final variables

Is there a way to implement a loop using final variables?
I mean a loop that would run for a specified number of iterations when you are not allowed to change anything after initialization!
Is recursion allowed, or do you literally need a loop construct like for or while? If you can use recursion, then:
void loop(final int n) {
if (n == 0) {
return;
} else {
System.out.println("Count: " + n);
loop(n-1);
}
}
One way is to create an Iterable<Integer> class representing an arbitrary range (without actually having to store all of the values in a list):
public static class FixedIntRange implements Iterable<Integer> {
private final int min;
private final int max;
public FixedIntRange(final int min, final int max) {
this.min = min;
this.max = max;
}
#Override
public Iterator<Integer> iterator() {
return new Iterator<Integer>() {
private Integer next = FixedIntRange.this.min;
#Override
public boolean hasNext() {
return next != null;
}
#Override
public Integer next() {
final Integer ret = next;
next = ret == max ? null : next + 1;
return ret;
}
#Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
}
and then iterate over it normally:
for (final int i : new FixedIntRange(-10, 20)) {
// this will be run for each i in the range [-10, 20]
}
Create an array whose size is the required number of iterations, then use it in a for-each loop:
public class Test {
public static void main(String[] args) {
final int N = 20;
final int[] control = new int[N];
for(final int i : control){
System.out.println(i);
}
}
}
The trick here is that the iteration indexing is generated by the compiler as part of the enhanced for statement, and does not use any user-declared variable.
Something like this -
final int max = 5;
for(int i=0; i<max; i++) {}
Or another interesting one-
final boolean flag = true;
while(flag) {
// keep doing your stuff and break after certain point
}
One more-
List<String> list = ......
for(final Iterator iterator = list.iterator(); iterator.hasNext(); ) {
}

Categories