Print a for-loop, Java - java

I'm trying to learn java on my own. I am now re-doing some programs I've done before, but in a different way.
Now I am stuck with a for-loop.
I have the following code:
public class Head {
public static void main(String[] args) {
int a = 0;
int b = 0;
int c = 0;
int d = 0;
int e = 0;
int f = 0;
for(int i=0; i<1000; i++){
int dice1 = 1 + (int)(Math.random() * ((6 - 1) + 1));
if (dice1 == 1){
a++;
}
else if(dice1 == 2){
b++;
}
else if(dice1 == 3){
c++;
}
else if(dice1 == 4){
d++;
}
else if(dice1 == 5){
e++;
}
else if(dice1 == 6){
f++;
}
}
System.out.println("Ones: " + a);
System.out.println("Twos: " + b);
System.out.println("Threes: " + c);
System.out.println("Fours: " + d);
System.out.println("Fives: " + e);
System.out.println("Sixes: " + f);
}
}
This works all fine and do what I want it to.
Now I want to create a constructor with a method that do all the countings for me. So far so good. But when it comes to printing it out, the output returns everything the number of times it does the calculation.
i.e, if I set i<5 it prints
1
2
3
4
5
6
five times, and not only one time.
Here is the bad code:
public class Head {
public static void main(String[] args) {
int a=0;
int b=0;
int c=0;
int d=0;
int e=0;
int f=0;
for(int i=0; i<5; i++){
int dice1 = 1 + (int)(Math.random() * ((6 - 1) + 1));
Dice diceObject = new Dice(dice1, a, b, c, d, e, f);
diceObject.CountNumbers();
// System.out.println(diceObject);
}
}
}
public class Dice {
private int a=0, b=0, c=0, d=0, e=0, f=0;
private int dice1;
public Dice(int dice1, int a, int b, int c, int d, int e, int f){
this.dice1 = dice1;
this.a = a;
this.b = b;
this.c = c;
this.d = d;
this.e = e;
this.f = f;
}
public int getDice1(){
return dice1;
}
public void CountNumbers(){
if (dice1 == 1){
a++;
}
else if(dice1 == 2){
b++;
}
else if(dice1 == 3){
c++;
}
else if(dice1 == 4){
d++;
}
else if(dice1 == 5){
e++;
}
else if(dice1 == 6){
f++;
}
}
}
Any help on this?
Thank you very much for your time!

There are multiple things.
One is that some of your code is unnecessary.
public Dice(int dice1 /*, int a, int b, int c, int d, int e, int f*/ ){
this.dice1 = dice1;
//this.a = a;
//this.b = b;
//this.c = c;
//this.d = d;
//this.e = e;
//this.f = f;
}
You don't need the commented lines of code because they will reset the integers a-f and that is already being done. That also means that you don't need the variables a-f in the Head class.
public class Head {
public static void main(String[] args) {
//int a=0;
//int b=0;
//int c=0;
//int d=0;
//int e=0;
//int f=0;
for(int i=0; i<5; i++){
int dice1 = 1 + (int)(Math.random() * ((6 - 1) + 1));
Dice diceObject = new Dice(dice1 /*, a, b, c, d, e, f*/ );
diceObject.countNumbers();
diceObject.saveResults();
}
System.out.println("A B C D E F");
Dice.displayResults();
} }
Again, the snips of code not needed are commented out.
The next thing is that when you write the code
System.out.println(diceObject);
that doesn't work because diceObject is an instance of a class (Dice) and it isn't a variable.
The way I got everything to work was by having the variables sa, sb, sc, sd, se, and sf added.
private static int sa = 0, sb = 0, sc = 0, sd = 0, se = 0, sf = 0;
I added these so that the results from each time the loop runs will be saved. I created a void to do this called saveResults(); The variables had to be static because the void was static too. I made the displayResults void (i'll get into that later) static so it could be accessed from a the Head class.
public void saveResults() {
sa += a;
sb += b;
sc += c;
sd += d;
se += e;
sf += f;
}
The += just means to add;
The last thing I did was make the displayResults void. It just displays the variables sa-sf using System.out.println();
public static void displayResults() {
System.out.println(sa + " " + sb + " " + sc + " " + sd + " " + se + " " + sf);
}
This all went together to make the final product. Here is the code:
Head class:
public class Head {
public static void main(String[] args) {
for(int i=0; i<5; i++){
int dice1 = 1 + (int)(Math.random() * ((6 - 1) + 1));
Dice diceObject = new Dice(dice1);
diceObject.countNumbers();
diceObject.saveResults();
}
System.out.println("A B C D E F");
Dice.displayResults();
}
}
Dice class:
public class Dice {
private int a=0, b=0, c=0, d=0, e=0, f=0;
private static int sa = 0, sb = 0, sc = 0, sd = 0, se = 0, sf = 0;
private int dice1;
public Dice(int dice1){
this.dice1 = dice1; }
public int getDice1(){
return dice1;
}
public void countNumbers(){
if (dice1 == 1){
a++;
}
else if(dice1 == 2){
b++;
}
else if(dice1 == 3){
c++;
}
else if(dice1 == 4){
d++;
}
else if(dice1 == 5){
e++;
}
else if(dice1 == 6){
f++;
}
}
public void saveResults() {
sa += a;
sb += b;
sc += c;
sd += d;
se += e;
sf += f;
}
public static void displayResults() {
System.out.println(sa + " " + sb + " " + sc + " " + sd + " " + se + " " + sf);
} }
I am a beginner at java too. And a coincidence, for some time I was trying to teach it to myself. There is a course on codecademy.com that teaches you the basics. I recommend it and it is free. Sorry it took long to post this answer, it took a while to figure out what was wrong.

Related

Print Consecutive numbers by comparing two parameters

input 3,5 output should be 3,4,5
input 5,3 output should be 5,4,3
And the code
public static void test(int a, int b) {
if(a>b) {
for (int i = a; i >= b; i--) {
System.out.print(i + "\t");
}
}else if(a<b) {
for (int i = a; i <= b; i++) {
System.out.print(i + "\t");
}
}
}
It works but looks a little messy. Is it possible to do without if else thing? Only one loop.
One solution which handle also boundary values correctly could be
public static void test(int start, int end) {
int current = start;
int stepWidth = current <= end ? +1 : -1;
while (current != (end + stepWidth)) {
System.out.print(current + "\t");
current += stepWidth;
}
System.out.println("");
}
edit Another one using a for loop.
public static void test(int start, int end) {
int stepWidth = start <= end ? 1 : -1;
for (int current = start; current != end + stepWidth; current += stepWidth) {
System.out.print(current + "\t");
}
System.out.println("");
}
executions
test(3, 5);
test(5, 3);
test(Integer.MAX_VALUE - 3, Integer.MAX_VALUE);
test(Integer.MIN_VALUE, Integer.MIN_VALUE + 3);
output
3 4 5
5 4 3
2147483644 2147483645 2147483646 2147483647
-2147483648 -2147483647 -2147483646 -2147483645
How about this version?
public static void test(int a, int b) {
int d = b > a ? 1 : -1;
for (int i = a; i != b; i+=d) {
System.out.print(i + "\t");
}
System.out.println(b);
}
This my solution, feedback appreciated.
public static void test(int a, int b) {
int middle = (a < b) ? (b - 1) : (a - 1);
System.out.println(a + "," + middle + ","+b);
}
Above will work only when a != b.

Armstrong Number java

I've got a problem with some simple code. I haven't seen where is the problem in my code. It returns false when it should return true, since 153 is an Armstrong Number.
Following is my code:
public class Armstrong {
static double nArms, unidad, decena, centena, aux;
Armstrong(){
}
Armstrong(double nArms){
this.nArms = nArms;
}
public boolean esArmstrong(double nArms){
aux = nArms % 100;
centena = nArms / 100;
decena = aux / 10;
unidad = aux % 10;
this.nArms = Math.pow(unidad, 3) + Math.pow(decena, 3) +Math.pow(centena, 3);
if(this.nArms == nArms){
return true;
}else{
return false;
}
}
public static void main(String[] args) {
Armstrong arms = new Armstrong();
System.out.println(arms.esArmstrong(153));
}
}
You are using double when you intend to do integer arithmetic. For example, when you write
centena = nArms / 100;
you are doing floating point division, (and centena is assigned the value 1.53) but you want to perform integer division. Use int, long (or BigInteger) instead.
As others already mentioned never use Double for Integer calculation
Now If I were you I would have optimized my code to this
int check=0;
int n=num; // num is user-input number
while(n>0)//suppose n =153
{
int rem=n%10;
check=check+(int)Math.pow(rem,3);
n=n/10;
}
if(check==num)
System.out.println(num+" is Armstrong");
/*First time while loop runs rem = 3 and n= 15
So check = 0+3*3*3=27
Second time while loop runs rem = 5 and n= 1
So check = 27+5*5*5 = 152
Again n =1 so rem = 1 and check = 152+1*1*1 = 153
This time the thw while fails the exits
ultimately check == num so it is armstrong */
import java.util.Scanner;
public class Armstrong {
public static void main(String args[]) {
System.out.println("Input number of digit to find out Armstrong");
Scanner sc = new Scanner(System.in);
int r = sc.nextInt();
String s[] = new String[r];
System.out.println("Please enter digits");
StringBuilder sb = new StringBuilder(r);
for (int i = 0; i < r; i++) {
String userInput = sc.next();
s[i] = userInput;
sb.append(s[i]);
}
int e = Integer.parseInt(sb.toString()); //this is the Integer value entered to check Armstrong number
int d;
int k[] = new int[r];
for (int j = 0; j < r; j++) {
d = Integer.parseInt(s[j]);
k[j] = d * d * d * d* d* d;
}
int m[] = new int[r + 1];
int n[] = new int[r];
for (int l = 1; l <= r; l++) {
n[l - 1] = m[l - 1] + k[l - 1];
m[l] = n[l - 1];
}
if (e == m[r]) {
System.out.println("Entered number is Armstrong number");
} else {
System.out.println("Entered number is not an Armstrong number");
}
}
public void isArmstrong(String n)
{
char[] s=n.toCharArray();
int sum=0;
for(char num:s)
{
int i=Integer.parseInt(Character.toString(num));
int cube=i*i*i;
sum +=cube;
}
if(sum==Integer.parseInt(n))
{
System.out.println("Its an Armstrong Number");
}
else
{
System.out.println("Its not an Armstrong Number");
}
}
import java.util.*;
public class Main
{
public static void check_armstrong(int n)
{
/*Function to check whether a number is an armstrong number or not
Print true if yes else false */
int sum=0;
int temp=n;
while(n>0){
int remainder=n%10;
sum+=remainder*remainder*remainder;
n=n/10;
}
if(temp==sum){
System.out.println(true);
}else
System.out.println(false);
/* Do not change the code beyond this point*/
}
public static void main(String[]args)
{
Scanner sc=new Scanner(System.in);
int n =sc.nextInt();
check_armstrong(n);
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number");
int a, c, d, e = 0, temp = 0;
a = sc.nextInt();
c = a;
int z = a;
while (c > 0) {
c = c / 10;
temp++;
}
System.out.println("//");
int temp2 = temp;
while (temp2 > 0) {
int temp1 = 1;
d = a % 10;
for (int i = 0; i < temp; i++) {
temp1 = temp1 * d;
}
e = e + temp1;
a = a / 10;
temp2--;
}
if (z == e) {
System.out.println("number is armstrong");
} else {
System.out.println("number is not armstrong");
}
}

Can you quickly tell me if this pseudocode makes sense or not?

I believe my code is now foolproof. I will write up the pseudocode now. But I do have one question. Why does DRJava ask that I return something outside of my if statements? As you can see I wrote for ex: "return 1;" just because it asked. It will never return that value however. Can someone explain this to me?
public class assignment1question2test {
public static void main(String[] args) {
int[] a = new int[50];
int l = 0;
int r = a.length;
for(int i=0; i<r; i++) {
a[i] = 1;
}
a[0] = 10;
for (int i=0; i<r; i++) {
System.out.println(a[i]);
}
System.out.print(recursiveSearch(a,l,r));
}
public static int recursiveSearch (int[] a, int l, int r) {
int third1 = (r-l)/3 + l;
int third2 = third1*2 - l + 1;
System.out.println("i will be checking compare from " + l + " to " + third1 + " and " + (third1 + 1) + " to " + third2);
int compareResult = compare(a,l,third1,third1 + 1, third2);
if(r-l == 1) {
if (compareResult == 1) {
return l;
}
else {
return r;
}
}
if (compareResult == 0) {
return recursiveSearch(a,third2 + 1, r);
}
if (compareResult == 1) {
return recursiveSearch(a,l,third1);
}
if (compareResult == -1) {
return recursiveSearch(a,third1 + 1, third2);
}
return 1;
}
public static int compare(int[] a, int i, int j, int k, int l) {
int count1 = 0;
int count2 = 0;
for(int g=i; g<=j; g++) {
count1 = count1 + a[g];
}
for(int g=k; g<=l; g++) {
count2 = count2 + a[g];
}
if (count1 == count2) {
return 0;
}
if (count1 > count2) {
return 1;
}
if (count1 < count2) {
return -1;
}
return 0;
}
}
UPDATED FINAL PSEUDOCODE:
Algorithm: recursiveSearch (a,l,r)
Inputs: An array a, indices l and r which delimit the part of interest.
Output: The index that has the lead coin.
int third1 ← (r - l + 1)/3
int third2 ← third1*2 - l + 1
if (r-l = 0) then
return l
int compareResult ← compare(a,l,third1,third1 + 1,third2)
if (r-l = 1) then
if (compareResult = 1) then
return l
else
return r
if (compareResult = 0) then
return recursiveSearch(a, third2 + 1, r)
if (compareResult = "1") then
return recursiveSearch(a,l,third1)
if (compareResult = "-1") then
return recursiveSearch(a,third1 + 1,third2)
You seem to be including mid in the following search regardless of which side is larger. The recursive calls should both exclude mid from their search space.
Also, for the comparison to be meaningful, the two groups being compared need to be of equal size. That will require some extra odd/even logic.

Consecutive factor test

A positive number n is consecutive-factored if and only if it has factors, i and j where i > 1, j > 1 and j = i +1. I need a function that returns 1 if its argument is consecutive-factored, otherwise it returns 0.For example, 24=2*3*4 and 3 = 2+1 so it has the function has to return 1 in this case.
I have tried this:
public class ConsecutiveFactor {
public static void main(String[] args) {
// TODO code application logic here
Scanner myscan = new Scanner(System.in);
System.out.print("Please enter a number: ");
int num = myscan.nextInt();
int res = isConsecutiveFactored(num);
System.out.println("Result: " + res);
}
static int isConsecutiveFactored(int number) {
ArrayList al = new ArrayList();
for (int i = 2; i <= number; i++) {
int j = 0;
int temp;
temp = number %i;
if (temp != 0) {
continue;
}
else {
al.add(i);
number = number / i;
j++;
}
}
System.out.println("Factors are: " + al);
int LengthOfList = al.size();
if (LengthOfList >= 2) {
int a =al(0);
int b = al(1);
if ((a + 1) == b) {
return 1;
} else {
return 0;
}
} else {
return 0;
}
}
}
Can anyone help me with this problem?
First check if its even, then try trial division
if(n%2!=0) return 0;
for(i=2;i<sqrt(n);++i) {
int div=i*(i+1);
if( n % div ==0) { return 1; }
}
return 0;
very inefficient, but fine for small numbers. Beyond that try a factorisation algorithm from http://en.wikipedia.org/wiki/Prime_factorization.
I have solved my problem with the above code. Following is the code.
public class ConsecutiveFactor {
public static void main(String[] args) {
// TODO code application logic here
Scanner myscan = new Scanner(System.in);
System.out.print("Please enter a number: ");
int num = myscan.nextInt();
int res = isConsecutiveFactored(num);
System.out.println("Result: " + res);
}
static int isConsecutiveFactored(int number) {
ArrayList al = new ArrayList();
for (int i = 2; i <= number; i++) {
int j = 0;
int temp;
temp = number % i;
if (temp != 0) {
continue;
}
else {
al.add(i);
number = number / i;
j++;
}
}
Object ia[] = al.toArray();
System.out.println("Factors are: " + al);
int LengthOfList = al.size();
if (LengthOfList >= 2) {
int a = ((Integer) ia[0]).intValue();
int b = ((Integer) ia[1]).intValue();
if ((a + 1) == b) {
return 1;
} else {
return 0;
}
} else {
return 0;
}
}
}

How to write an "all these numbers are different" condition in Java?

OK, I have this problem to solve but I can’t program it in Java correctly. See the picture below, you’ll see a 6 pointed star were every point and intersection of lines is a letter.
The assignment is to position the numbers 1 to 12 in such a way that the sum of all lines of four balls is 26 and the sum of all the 6 points of the star is 26 as well.
This comes down to:
(A+C+F+H==26)
(A+D+G+K==26)
(B+C+D+E==26)
(B+F+I+L==26)
(E+G+J+L==26)
(H+I+J+K==26)
(A+B+E+H+K+L==26)
So I started programming a program that would loop through all options brute forcing a solution. The loop is working, however, it now shows solutions where one number is used more than once, which is not allowed. How can I make it in the code that it also checks whether all variables are different or not?
if ((A!= B != C != D != E != F != G != H != I != J != K != L)
I tried the above, but it doesn't work, because it says:
incomparable types: boolean and int.
How can I make a check within 1 or a small statement for whether or not all the numbers are different?
(instead of making a nested 12*12 statement which checks every variable combination)
This is my code so far:
public class code {
public static void main(String[] args){
for(int A = 1; A < 13; A++){
for(int B = 1; B < 13; B++){
for(int C = 1; C < 13; C++){
for(int D = 1; D < 13; D++){
for(int E = 1; E < 13; E++){
for(int F = 1; F < 13; F++){
for(int G = 1; G < 13; G++){
for(int H = 1; H < 13; H++){
for(int I = 1; I < 13; I++){
for(int J = 1; J < 13; J++){
for(int K = 1; K < 13; K++){
for(int L = 1; L < 13; L++){
if ((A+C+F+H==26) && (A+D+G+K==26) && (B+C+D+E==26) && (B+F+I+L==26) && (E+G+J+L==26) && (H+I+J+K==26) && (A+B+E+H+K+L==26)){
if ((A= C != D != E != F != G != H != I != J != K != L)){
System.out.println("A: " + A);
System.out.println("B: " + B);
System.out.println("C: " + C);
System.out.println("D: " + D);
System.out.println("E: " + E);
System.out.println("F: " + F);
System.out.println("G: " + G);
System.out.println("H: " + H);
System.out.println("I: " + I);
System.out.println("J: " + J);
System.out.println("K: " + K);
System.out.println("L: " + L);
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
If I get it correctly, you want to check if all A to L are unique. So just put them in a set and find the size of the set:
if ((new HashSet<Integer>(
Arrays.asList(A, B, C, D, E, F, G, H, I, J, K, L)))
.size() == 12) {
//do your stuff
}
I strongly advise using recursion instead, which would vastly simplify the code. Do something like this:
function generate(set used, array list):
if list.size() == 12:
if list matches criteria:
yield list as solution
else:
for next = 1; next < 13; next++:
if next not in used:
used.add(next)
generate(used, list + next)
used.remove(next)
However, to answer you question directly: You can throw all the values into a set and check that it's size is equal to the number of items you threw in. This works because a set will count duplicates as one.
Before looking for a good solution for you, I would like to help with the error you get.
if ((A= C != D != E != F != G != H != I != J != K != L)){
This line does not makes much sense. The first thing the compiler will check is:
if (A=C)
You probably wanted to code if (A!=C), but let's consider what you really type. A=C is an attribution, so A will receive C value.
Then, the compiler will go on. After attributing C's value to A, it will check the comparison:
if (A=C != D)
This will compare A's value to D, which will result in a boolean -- let's say that the result is false.
The next comparison would be:
if (false != E)
At this point, there is a comparison between a boolean and an int, hence the error incomparable types: boolean and int..
Well, as you need to check wheter your numbers are unique, a nice solution would be the one proposed by #abhin4v.
Your nested loops will execute 12^12 = 8.91610045E12 IF-Statements, many of them invalid because of wrong combinations of numbers. You need permutations of 1,2,3,..,12 as candidates of your bruteforcing approach. The number of permutations of 12 Elements is 12!= 479 001 600, so the bruteforcing will be much faster I guess. With only generating valid permutations you don't need any check for valid combinations.
Here is some sample code, the code in nextPerm() is copied and modified from Permutation Generator :
import java.util.Arrays;
public class Graph26 {
private static final int A = 0;
private static final int B = 1;
private static final int C = 2;
private static final int D = 3;
private static final int E = 4;
private static final int F = 5;
private static final int G = 6;
private static final int H = 7;
private static final int I = 8;
private static final int J = 9;
private static final int K = 10;
private static final int L = 11;
private final static boolean rule1(final int[] n) {
return n[A] + n[C] + n[F] + n[H] == 26;
}
private final static boolean rule2(final int[] n) {
return n[A] + n[D] + n[G] + n[K] == 26;
}
private final static boolean rule3(final int[] n) {
return n[H] + n[I] + n[J] + n[K] == 26;
}
private final static boolean rule4(final int[] n) {
return n[B] + n[C] + n[D] + n[E] == 26;
}
private final static boolean rule5(final int[] n) {
return n[B] + n[F] + n[I] + n[L] == 26;
}
private final static boolean rule6(final int[] n) {
return n[E] + n[G] + n[J] + n[L] == 26;
}
private final static boolean rule7(final int[] n) {
return n[A] + n[B] + n[E] + n[H] + n[K] + n[L] == 26;
}
private final static boolean isValid(final int[] nodes) {
return rule1(nodes) && rule2(nodes) && rule3(nodes) && rule4(nodes)
&& rule5(nodes) && rule6(nodes) && rule7(nodes);
}
class Permutation {
private final int[] o;
private boolean perms = true;
public boolean hasPerms() {
return perms;
}
Permutation(final int[] obj) {
o = obj.clone();
}
private int[] nextPerm() {
int temp;
int j = o.length - 2;
while (o[j] > o[j + 1]) {
j--;
if (j < 0) {
perms = false;
break;
}
}
if (perms) {
int k = o.length - 1;
while (o[j] > o[k]) {
k--;
}
temp = o[k];
o[k] = o[j];
o[j] = temp;
int r = o.length - 1;
int s = j + 1;
while (r > s) {
temp = o[s];
o[s] = o[r];
o[r] = temp;
r--;
s++;
}
}
return o.clone();
}
}
public static void main(final String[] args) {
int[] nodes = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
final Graph26 graph = new Graph26();
final Permutation p = graph.new Permutation(nodes);
int i = 0;
while (p.hasPerms()) {
if (isValid(nodes)) {
System.out.println(Arrays.toString(nodes));
}
i++;
nodes = p.nextPerm();
}
System.out.println(i);
}
}

Categories