Problems with comparison between two inputs in for loops in Java - java

I need help with this problem. I am supposed to be making a program where I need to compare 10 stock prices and find the largest increase in a day in the numbers using the program. The program can only use for loops/if else and main method. I am using scanner to obtain the ints for the stock prices. Everytime i run the code, all i get is the last values that i put into the scanner. PLEASE HELP. Code below.
import java.util.Scanner;
//48 54 49 47 62 64 59 70 75 82
class Increase
{
public static void main (String [] args)
{
Scanner in = new Scanner(System.in);
final int Days = 10;
int highval = 0;
int lowval = 0;
int increase = 0;
int day = 0;
System.out.print("Enter the stock prices for " + Days + " number of days.");
int x = in.nextInt();
for (int i = 0; i < Days-1; i++)
{
int y = in.nextInt();
if (increase < (y - x));
{
increase = (y - x);
highval = y;
lowval = x;
day = i;
}
x = y;
}
System.out.println("The largest increase is " + increase);
System.out.println("from " +lowval + " to " + highval );
System.out.println("between days " + day + " and " + (day + 1));
}
}

The issue is with the ; in the line
if (increase < (y - x)); (empty assignment)
which is causing the below loop to be executed always.
{
increase = (y - x);
highval = y;
lowval = x;
day = i;
}
to fix change as below.
import java.util.Scanner;
class Increase
{
public static void main (String [] args)
{
Scanner in = new Scanner(System.in);
final int Days = 10;
int highval = 0;
int lowval = 0;
int increase = 0;
int day = 0;
System.out.print("Enter the stock prices for " + Days + " number of days.");
int x = in.nextInt();
for (int i = 0; i < Days-1; i++)
{
int y = in.nextInt();
if (increase < (y - x))
{
increase = (y - x);
highval = y;
lowval = x;
day = i;
}
x = y;
}
System.out.println("The largest increase is " + increase);
System.out.println("from " +lowval + " to " + highval );
System.out.println("between days " + day + " and " + (day + 1));
}
}

Related

Wheel of fortune statistical simulation java

The task is to simulate a wheel of fortune, which you are allowed to turn ten times.
You can spin as many times as you like, but as soon as the 0 comes, all points are gone. The program should stop the round as soon as a score over 10 is reached or a 0 comes. The results should be added at the end.
We are now at the point where the points are added and fields are fixed, but we can't think of anything to do with stopping or adding the results.
Does anyone have an idea?
Thanks in advance!
import java.util.Map;
import java.util.LinkedHashMap;
public class RandomBeispielzwei {
private static final Map<Double, Integer> GRENZEN = new LinkedHashMap<Double, Integer>();
static {
GRENZEN.put(0.1, 1);
GRENZEN.put(0.2, 2);
GRENZEN.put(0.3, 3);
GRENZEN.put(0.4, 1);
GRENZEN.put(0.5, 2);
GRENZEN.put(0.6, 3);
GRENZEN.put(0.7, 1);
GRENZEN.put(0.8, 2);
GRENZEN.put(0.9, 3);
GRENZEN.put(1.0, 0);
}
private Integer naechsteZufallzahl() {
double random = Math.random();
for (Map.Entry<Double, Integer> entry : GRENZEN.entrySet()) {
if (random <= entry.getKey().doubleValue()) {
return entry.getValue();
}
}
throw new UnsupportedOperationException("Fuer die Zufallszahl wurde kein passender Wert in der Map gefunden");
}
public static void main(String[] args) {
int anzahl1 = 0;
int anzahl2 = 0;
int anzahl3 = 0;
int anzahl0 = 0;
RandomBeispielzwei b = new RandomBeispielzwei();
for (int i = 0; i < 10; i++) {
Integer z = b.naechsteZufallzahl();
if (z.intValue() == 1) {
anzahl1++;
} else if (z.intValue() == 2) {
anzahl2++;
} else if (z.intValue() == 3) {
anzahl3++;
} else {
anzahl0++;
}
}
int ges1 = anzahl1 * 1;
int ges2 = anzahl1 * 2;
int ges3 = anzahl1 * 3;
System.out.println("1: " + anzahl1);
System.out.println("Punktzahl 1: " + ges1);
System.out.println("2: " + anzahl2);
System.out.println("Punktzahl 2: " + ges2);
System.out.println("3: " + anzahl3);
System.out.println("Punktzahl 3: " + ges3);
System.out.println("0: " + anzahl0);
System.out.println("Gesamtzahl: " + (anzahl1 + anzahl2 + anzahl3 + anzahl0));
System.out.println("Gesamtpunktzahl: " + (ges1 + ges2 + ges3));
}
}
For exiting the for-loop (and any other loop), you can use the "break" statement, which simply ends the loop (similar to how "return" will exit a method). In order to be able to stop once the total score reaches ten, you of course need to keep track of the total score. To do this, the easiest way would be to introduce aa integer variable (e.g. "gesamtpunktzahl"), to which you add the amount of points scored in each turn. In all, it would look something like this:
import java.util.Map;
import java.util.LinkedHashMap;
public class RandomBeispielZwei {
private static final Map<Double, Integer> GRENZEN = new LinkedHashMap<Double, Integer>();
static {
GRENZEN.put(0.1, 1);
GRENZEN.put(0.2, 2);
GRENZEN.put(0.3, 3);
GRENZEN.put(0.4, 1);
GRENZEN.put(0.5, 2);
GRENZEN.put(0.6, 3);
GRENZEN.put(0.7, 1);
GRENZEN.put(0.8, 2);
GRENZEN.put(0.9, 3);
GRENZEN.put(1.0, 0);
}
private Integer naechsteZufallzahl() {
double random = Math.random();
for (Map.Entry<Double, Integer> entry : GRENZEN.entrySet()) {
if (random <= entry.getKey().doubleValue()) {
return entry.getValue();
}
}
throw new UnsupportedOperationException("Fuer die Zufallszahl wurde kein passender Wert in der Map gefunden");
}
public static void main(String[] args) {
int anzahl1 = 0;
int anzahl2 = 0;
int anzahl3 = 0;
int anzahl0 = 0;
int gesamtpunktzahl = 0; // this will store what the total score is so far
RandomBeispielzwei b = new RandomBeispielzwei();
for (int i = 0; i < 10000; i++) {
Integer z = b.naechsteZufallzahl();
if (z.intValue() == 1) {
anzahl1++;
gesamtpunktzahl++; // a 1 was scored, so we increase the total score by 1
} else if (z.intValue() == 2) {
anzahl2++;
gesamtpunktzahl += 2; // same with a 2
} else if (z.intValue() == 3) {
anzahl3++;
gesamtpunktzahl += 3; // same with a 3
} else {
anzahl0++;
break; // a 0 was rolled, so we end the game (by exiting the for-loop)
}
if (gesamtpunktzahl >= 10) break; // at least 10 points were scored so far, so we exit the for-loop
}
int ges1 = anzahl1 * 1;
int ges2 = anzahl1 * 2;
int ges3 = anzahl1 * 3;
System.out.println("1: " + anzahl1);
System.out.println("Punktzahl 1: " + ges1);
System.out.println("2: " + anzahl2);
System.out.println("Punktzahl 2: " + ges2);
System.out.println("3: " + anzahl3);
System.out.println("Punktzahl 3: " + ges3);
System.out.println("0: " + anzahl0);
System.out.println("Gesamtzahl: " + (anzahl1 + anzahl2 + anzahl3 + anzahl0));
System.out.println("Gesamtpunktzahl: " + gesamtpunktzahl); // since we calculated it anyway, we might as well just use it here
}
}
I suggest using the loop do ... while for the counting and printing.
And please check you code - does you need count the same variable anzahl1 for each ges?:
int ges1 = anzahl1 * 1;
int ges2 = anzahl1 * 2;
int ges3 = anzahl1 * 3;
if not - then replace ges[i] = anzahles[1] * (i+1); to ges[i] = anzahles[i+1] * (i+1);
public static void main(String[] args) {
int[] anzahles = new int[4];
int gesamtpunktzahl = 0;
Integer z = 0;
RandomBeispielzwei b = new RandomBeispielzwei();
do {
z = b.naechsteZufallzahl();
anzahles[z]++;
gesamtpunktzahl += z;
} while (!(z == 0 || gesamtpunktzahl >= 10));
int ges[] = new int[3];
for (int i = 0; i < 3; i++) {
ges[i] = anzahles[1] * (i+1);
System.out.println((i+1) + ": " + anzahles[i+1]);
System.out.println("Punktzahl " + (i+1) + ": " + ges[i]);
}
System.out.println("0: " + anzahles[0]);
System.out.println("Gesamtzahl: " + Arrays.stream(anzahles).sum());
System.out.println("Gesamtpunktzahl: " + Arrays.stream(ges).sum());
}

How do I add power in java?

I am new to Java and stackoverflow. I am writing a program that can add power in Java, for example: 2^1, 2^1+2^2, 2^1+2^2+2^3,.. so on.
I have written below program and I don't know what I am doing wrong when I am trying to add the powers. I just get 2^1 2^2 2^3,... as output. I hope you get the idea from my code and it will be a great help if you guys can help me learn.
Thank you in advance!
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a: ");
int a = sc.nextInt(); //a = first number
System.out.print("Enter b: ");
int b = sc.nextInt(); //b = second number
System.out.print("Enter t: ");
int t = sc.nextInt(); //t = no. of iterations
int x=0, sum = 0;
for (int i = 0; i < t;) {
for (int j = 0; j < t; j++) {
int pow = (int) Math.pow(2, i);
x = a + (pow * b);
i++;
System.out.printf("%d ", x);
sum = x;
}
sum = x + sum;
System.out.println(sum);
}
}
According to Mathematics rules, if it is addition among the numbers, for example 2^1 + 2^2 + 2^3 + 2^4... Then it is simple you don't need two loops and the t variable. You just need the base and the last exponent limit.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the base: ");
int a = sc.nextInt(); //a = first number
System.out.print("Enter iterations: ");
int b = sc.nextInt(); //b = No of iterations
int sum = 0;
for (int i = 1; i <= b; i++) {
sum += Math.pow(a, i);
}
System.out.println("The sum is " + sum);
}
But if there is multiplication among the numbers, then you will add the exponents if the base is same. Fox example 2^1 * 2^2 * 2^3 * 2^4.... Then you may do it as below.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the base: ");
int a = sc.nextInt(); //a = first number
System.out.print("Enter iterations: ");
int b = sc.nextInt(); //b = No of iterations
Double res;
int powerSum = 0;
for (int i = 1; i <= b; i++) {
powerSum += i;
}
System.out.println("Power sum is " + powerSum);
res = Math.pow(a, powerSum);
System.out.println("The result is " + res);
}
In your inner loop
int pow = (int) Math.pow(2, i);
shouldn't you be using j instead of i?
Very simply you can do it as below:
public static int getPow(int num, int pow) {
if (pow < 2) {
return num;
}
return (int) Math.pow(num, pow) + getPow(num, --pow);
}
Usage:
int pow = getPow(2, 4);// 2*1 + 2*2 + 2*2*2 + 2*2*2*2 = 2+4+8+16 = 30
System.out.println("pow = " + pow);
And Result:
pow = 30

Having trouble with a while loop that gets a certain series of numbers from an input

I'm trying to half the input if it % 12 == 0, but if it isn't then you multiply it by 3 and add 1 onto the sum.
The question that I'm working off is: http://i.imgur.com/VzuPtZJ.png
With the code I have currently(which is below), if I enter 12, like in the question I start off with 6, but then the results begin to go wrong and then they go insanely wrong with values in the millions and negative millions etc.
import java.util.*;
public class sheet12t3
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter a number: ");
int aNumber = Integer.parseInt(in.nextLine());
hailstone(aNumber);
}
public static void hailstone(int x)
{
int count = 1;
int max = 0;
String results = "Hailstone series for the number " + x + " is ";
while (x >= 1)
{
if (x % 12 == 0)
x = x / 2;
else
x = 3 * x + 1;
count++;
results += + x + ", ";
if (x > max)
max = x;
}
results += "a total of " + count + " numbers in this sequence with a maximum value of " + max;
System.out.print(results);
}
}
The question says divide by two if the number is even. But you divide by 2 only when it is dividable by 12.
Change this line
(x % 12 == 0)
to
(x % 2 == 0)
And change while (x >= 1) to while (x > 1)
Here is the code you are looking for:-
import java.util.*;
public class sheet12t3
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter a number: ");
int aNumber = Integer.parseInt(in.nextLine());
hailstone(aNumber);
}
public static void hailstone(int x)
{
int count = 1;
int max = 0;
String results = "Hailstone series for the number " + x + " is ";
while (x > 1)
{
if (x % 2 == 0)
x = x / 2;
else
x = 3*x + 1;
System.out.print(x+" ");
max++;
}
}
}

Passing array through average method, resulting in low percent

For some reason the average is being populated wrong when I pass the array to the method I get a really low percent. It almost seems like since the Array shotsMade is only recording integers for made shots and not misses it is not calculating off the right base.
import java.util.*;
public class Test {
public static void main(String[] args) {
int myGameCounter = 1;
int shotCount = 0;
int shotCount1 = 0;
int [] shotsMade = new int [5];
int sum = 0;
System.out.print("Enter Player's Free Throw Percentage: ");
Scanner input = new Scanner(System.in);
int percent = input.nextInt();
//Game #1
System.out.println("Game " + myGameCounter + ":");
Random r = new Random();
myGameCounter++;
shotCount = 0;
for (int i = 0; i < 10; ++i){
boolean in = tryFreeThrow(percent);
if (in) {
shotCount++;
System.out.print("In" + " ");
}
else {
System.out.print("Out" + " ");
}
}
System.out.println("");
System.out.println("Free throws made: " + shotCount + " out of 10");
shotsMade[0]= shotCount;
//Game #2
System.out.println("");
System.out.println("Game" + myGameCounter + ":");
myGameCounter++;
shotCount1 = 0;
for (int i = 0; i < 10; ++i){
boolean in = tryFreeThrow(percent);
if (in) {
shotCount1++;
System.out.print("In" + " ");
}
else {
System.out.print("Out" + " ");
}
}
System.out.println("");
System.out.println("Free throws made: " + shotCount1 + " out of 10");
shotsMade[1]= shotCount1;
System.out.println("");
System.out.println("Summary:");
System.out.println("Best game: " + max(shotsMade));
System.out.println("Total Free Throws Made: " + sum(shotsMade) + " " + "out of 20");
System.out.println("Average Free Throw Percentage: " + average(shotsMade) +"%");
}//main
public static boolean tryFreeThrow(int percent) {
Random r = new Random();
int number = r.nextInt(100);
if (number > percent){
return false;
}
return true;
}
public static float average(int nums[]) {
int total = 0;
for (int i=0; i<nums.length; i++) {
total = total + nums[i];
}
float f = (total / nums.length);
return (float)total /(float)nums.length;
}
public static int sum(int nums[]) {
int sum = 0;
for (int i=0; i<nums.length; ++i) {
sum += nums[i];
}
return (int)sum;
}
public static int max(int nums[]) {
int max=nums[0];
for (int i=1; i<nums.length; i++) {
if (nums[i] > max)
max = nums[i];
}
return max;
}
}//class
You are calculating the avarage of 5 numbers but you only set 2. So if all shots hit your array will look like this: 10, 10, 0, 0, 0 and the avarage will be 4.
Old issue, you are using integer arithmetic total / nums.length with returns you an int value. You later assign it to a float, but the value already has been truncated.
Just change one of the values to float before the division, v.g. ((float) total) / num
Among others, your expression
float f = (total / nums.length);
will yield an inaccurate result.
Both total and nums.length are integers, and any operation between integers always results in an integer.
Example: if total=10 and nums.length=3, you'd expect the result to be 3.333... but actually the result is just 3. Only after that do you cast it to a float, resulting in 3.0.
To get the required result, you need to cast both integers to floats before dividing:
float f = (float) total / (float) nums.length;

number of integers in output? simple java program

I'm working on a simple java code that outputs all factors of a user-inputted number. How do I count and then display the number of factors outputted?
System.out.println("Enter an integer to be factored:");
int d = Stdin.readInt();
System.out.println("The Factors of " + d + " are:");
for(int w = 1; w <= d; w++ ){
if(d % w == 0){
System.out.println(w);
}
}
In the code above, it's the number of integers outputted in 'w' For instance, if the number inputted is 8 and its factors are 1,2,4,8, how do I write a code that says '8 has 4 factors' ?
Thanks
You simply need a variable to count factors:
System.out.println("Enter an integer to be factored:");
int d = Stdin.readInt();
int nFactors = 0;
System.out.println("The Factors of " + d + " are:");
for(int w = 1; w <= d; w++ ){
if(d % w == 0){
System.out.println(w);
++nFactors;
}
}
System.out.println(d + " has " + nFactors + " factors");
You need a counter variable. Here is the code:
int counter =0;
for(int w = 1; w <= d; w++ ){
if(d % w == 0){
counter++;
System.out.println(w);
}
System.out.println(d + " has " + counter + "factors ");
Try with this code:
import java.util.Scanner;
public class EmbalzadoFactorial {
public static Scanner sc;
public static void main(String[] args) {
int Number, i;
sc = new Scanner(System.in);
System.out.print("Please Enter any number to Find Factors: ");
Number = sc.nextInt();
System.out.println("The factors are: ");
for(i = 1; i <= Number; i++) {
if(Number%i == 0) {
System.out.format(" %d ", i);
System.out.print ("and");
System.out.format("%s %n ", i);
}
}
}
}

Categories