Thursday 6 April 2017

Checking if a value is equal to another within a loop(java)

I need to do find values 10 different times or until the value of difference is found twice. Im not really sure how to break the loop if found.



Here goes the code:



public class Algorithm {
private static int small; //global field so it is usable in zeros method

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
int number = 0;
// object array to use collections class
Integer [] digit = new Integer [4];
// loop for handling 10 different numbers
for (int index=0; index<10; index++){
number = random();
String smaller =""; String bigger=""; // strings used to display zeros/ easier processing
for (int i = 3; i >= 0; i--) {
digit[i] = number % 10;
number /= 10;
}
// prints initial random number
System.out.println(digit[0] + " " +digit[1] + " " +
digit[2]+ " "+ digit[3] + " Random Number");
// sorts the digits increasingly
Arrays.sort(digit);
// adds the numbers to the smaller string
for (int i=0; i smaller += digit[i];

}
// convert string to int
int small = Integer.parseInt(smaller);
String zerosNr = null;
zerosNr = zeros();
System.out.printf(" smaller " +zerosNr, small );
// Reverse sort order and adds results to bigger for displaying
Arrays.sort(digit, Collections.reverseOrder());
for (int i=0; i < digit.length; i++){
bigger += digit[i];
}
int big = Integer.parseInt(bigger);

System.out.println("bigger " + big);
int difference = 0;
int [] copy;
copy = new int[11];
difference = big - small;
copy[index] = big - small;
// here i tried to do it
System.out.println( index + " Difference "+ difference);
if (difference == copy[index+1])
break;
}
}
//method that creates random numbers
public static int random(){
final int n = 9999;
Random rad = new Random();
int number = rad.nextInt(n);
return number;

}
//method that adds zeros where necesarry to smaller
public static String zeros(){
String zerosNr = null;
if (small < 1000)
return " %04d\n ";
else if (small < 100)
return " %03d\n ";
else
return " %02d\n ";

}
}

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...