Is it possible to increase array index in a loop? - java

So my problem is that if you want to get a new calculation, the operaotr in my array should change. How can i do that? im trying this now for hours :/ this is how far i got.
so first it starts with + and whan you choose to get a new calculation the next one should be - and so on....
so i need to switch the "operator[0]"
private static void mathGame() {
char[] operator = {'+', '-', '*', '/'};
int x;
int y = 0;
Scanner input = new Scanner(System.in);
do {
int operand1 = (int) (Math.random() * (100 - 1) + 1);
int operand2 = (int) (Math.random() * (100 - 1) + 1);
System.out.println("Solve");
System.out.println(operand1 + " " + operator[0] + " " + operand2);
x = input.nextInt();
// operator [1]++;
if (x == evaluate(operand1, operator[0], operand2)) {
System.out.println("True!");
System.out.println("New Challange?");
y = input.nextInt();
//operator[1]++;
} else if (x != evaluate(operand1, operator[0], operand2)) {
System.out.println("False!");
System.out.println("New Challange?");
y = input.nextInt();
//operator[1]++;
}
} while (y == 1);
}

You need to define a variable outside of your loop (int i = 0;) and then have this instruction inside the loop (maybe before "} while (y == 1);":
i = (i + 1) % 4; (4 is size of your operators array).
p.s. I think you need to give more details about your question and elaborate your question in order to make it more clear for future readers.

Related

Java loop to ask 10 maths questions

Im currently trying to create a program thats asks the user to answer 10 multiplication questions and then output if the answer is correct or incorrect and then keep score of how many answers the user has got correct. My current code is shown below but I'm having trouble getting the score to increase as whenever I run it the score always stays at 1. I was wondering if anyone could help me with a solution to this
package Assignment1;
import java.util.Scanner;
import static java.lang.System.in;
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 11; i++) {
int number1 = (int) (Math.random() * 10) + 10;
int number2 = (int) (Math.random() * 10) + 10;
Scanner input = new Scanner(in);
System.out.print("What is " + number1 + " * " + number2 + " ?");
int answer = input.nextInt();
while ((number1 * number2) != answer) {
System.out.print("Incorrect");
answer = input.nextInt();
}
if ((number1 * number2) == answer) {
System.out.println("Correct");
int score = 0;
score = score + 1;
System.out.println("Score is currently: " + score);
}
}
}
}
In order to solve your problem, you need to understand the variable scope. The scope of a variable is in plain simple english: its lifecycle. And its lifecycle is defined between curly brackets, and by that I mean if the variable is created after "{", it only lives until "}". There are other cases, but don't mind them for now.
With this in mind, let's analyse what's the problem here. In your program you want the 'score' variable to live under all calculations and keep changing by adding the previous score to the new result, therefore producing a new score on every iteration. NOT to create a 'score' on every iteration.
Notice that you are creating the variable 'score' on every loop - resulting on its value being erased from memory (actually, its reference is what's being erased making its value lost in memory) at the end of every loop (when it dies) and a new 'score' variable is created over the next iteration.
So, I guess you'd know how to change your code now. You just change the creation of the variable 'score' to before the loop - so it's created before the "{" from the for loop instead of being erased and created on every iteration.
public class Main {
public static void main(String[] args) {
int score = 0;
for (int i = 0; i < 11; i++) {
int number1 = (int) (Math.random() * 10) + 10;
int number2 = (int) (Math.random() * 10) + 10;
Scanner input = new Scanner(in);
System.out.print("What is " + number1 + " * " + number2 + " ?");
int answer = input.nextInt();
while ((number1 * number2) != answer) {
System.out.print("Incorrect");
answer = input.nextInt();
}
if ((number1 * number2) == answer) {
System.out.println("Correct");
score = score + 1;
System.out.println("Score is currently: " + score);
}
}
}
}
You have declared score variable in the if block. So everytime there is a correct answer, the score is initialized with 0, then set to 1. Declare the score as an instance variable, or a local variable in main method (before the for loop)
If you want only 10 questions, the for loop should go from i = 1 to i < 11, not from i = 0. Also, you need to move the score outside the for loop, otherwise it will be declared as 0 every time the loop starts again. As Telmo Vaz correctly said, this is due to the scope of the variable. One other thing I noticed is that you can just use score++ to add 1 to score, instead of score = score + 1. I'll leave you to optimise your further.
import java.util.Scanner;
import static java.lang.System.in;
public class Main {
public static void main(String[] args) {
int score = 0;
for (int i = 1; i < 11; i++) { // 1 -> 10
int number1 = (int) (Math.random() * 10) + 10;
int number2 = (int) (Math.random() * 10) + 10;
Scanner input = new Scanner(in);
System.out.print("What is " + number1 + " * " + number2 + " ?");
int answer = input.nextInt();
while ((number1 * number2) != answer) {
System.out.print("Incorrect");
answer = input.nextInt();
}
if ((number1 * number2) == answer) {
System.out.println("Correct");
score++; // == (score = score + 1)
System.out.println("Score is currently: " + score);
}
}
}
}

Java: Min/Max/Average (4 variables) [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
Anyone knows how to run this program using 4 variables only? I tried using 1 variable for min and max "lowhigh" but I was having a hard time figuring out where to put the statements.
int numbers[] = new int[5];
int low = 0; int high = 0;
for(int count = 0; count < numbers.length; count++){
System.out.print("Please enter a number: ");
int number=s.nextInt();
if (count == 0) {
low = number;
high=number;
} else {
if(number < high) {
high= number;
}
if(number > low){
low = number;
}
}
numbers[count] = number;
}
double ave = numbers[0]+numbers[1]+numbers[2]+numbers[3]+numbers[4]/5;
System.out.println("Highest: " +high);
System.out.println("Lowest: " +low);
System.out.println("The average of all number is: " +ave); }}
Another way to do it in Java 8.
int numbers[] = new int[5];
for(int count = 0; count < numbers.length; count++){
System.out.print("Please enter a number: ");
int number=s.nextInt();
numbers[count] = number;
}
LongSummaryStatistics statistics = Arrays.stream(numbers)
.asLongStream()
.summaryStatistics();
System.out.println("Highest: " + statistics.getMax());
System.out.println("Lowest: " + statistics.getMin());
System.out.println("The average of all number is: " + statistics.getAverage());
Looks like your logic is backwards to finding high and low. Also your average wont work because order of operations. Need parens
int numbers[] = new int[5];
int low = Integer.MAX_VALUE; int high = Integer.MIN_VALUE;
for(int count = 0; count < numbers.length; count++){
System.out.print("Please enter a number: ");
int number=s.nextInt();
if (count == 0) {
low = number;
high=number;
} else {
if(number > high) {
high= number;
}
if(number < low){
low = number;
}
}
numbers[count] = number;
}
double ave = (numbers[0]+numbers[1]+numbers[2]+numbers[3]+numbers[4])/5;
System.out.println("Highest: " +high);
System.out.println("Lowest: " +low);
System.out.println("The average of all number is: " +ave); }}
You don't have to use an array if all you're doing is finding the min, max and mean.
final int COUNT = 5; //this is just to be neat, and not needed as a variable.
int low = Integer.MAX_VALUE;
int high = Integer.MIN_VALUE;
int sum = 0;
for(int i = 0; i < COUNT; i++){
int n = s.nextInt();//or whatever
if(n > high)
high = n;
if(n < low)
low = n;
sum += n;
}
System.out.println("Max: " + high);
System.out.println("Min: " + low);
System.out.println("Average: " + ((double) sum) / COUNT);
Based on what you mean by 4 variables, this may or may not work. final int COUNT is not really required and 5 can be put in directly instead.
This answer likely goes well beyond the scope of the question, but since the requirements/restrictions are not listed in full, it may still be a valid answer.
With a super strict interpretation of "4 variables", even the Scanner variable s counts.
Using streams, it can be done with 3 variables:
Scanner s; // variable 1
List<Double> values; // variable 2
String line; // variable 3
s = new Scanner(System.in);
values = new ArrayList<>();
while (true) {
System.out.print("Please enter a numbers, or press enter when done: ");
if ((line = s.nextLine().trim()).isEmpty())
break;
values.add(Double.valueOf(line));
}
if (values.isEmpty())
return;
System.out.println("Minimum: " + Stream.of(values.toArray(new Double[values.size()]))
.mapToDouble(Double::valueOf)
.min().getAsDouble());
System.out.println("Maximum: " + Stream.of(values.toArray(new Double[values.size()]))
.mapToDouble(Double::valueOf)
.max().getAsDouble());
System.out.println("Average: " + Stream.of(values.toArray(new Double[values.size()]))
.mapToDouble(Double::valueOf)
.sum() / values.size());
Sample output
Please enter a numbers, or press enter when done: 10
Please enter a numbers, or press enter when done: 42
Please enter a numbers, or press enter when done: 19
Please enter a numbers, or press enter when done: 88
Please enter a numbers, or press enter when done: 1
Please enter a numbers, or press enter when done: 3774
Please enter a numbers, or press enter when done:
Minimum: 1.0
Maximum: 3774.0
Average: 655.6666666666666
There is no point in the numbers[] array; so eliminate that.
You need a control variable for the loop, a temporary storage for the input, then three running variables for min, max and sum (average is sum devided by count, which seems to be fixed to 5).
Thats 5 variables, and you strictly need all of them. Its possible to stuff multiple values into a single variable, but I highly doubt thats what you're supposed to do.
Depending on what the requirements really are (I presume this is homework), one of the five I named above doesn't count as a variable per requirement (most likely the loop control or the temporary input storage).
Edit: Here's a variant using multiple values encoded in one variable that works with three variables (or four if you count the scanner, which I replaced with random for my convinience):
public class HighLowAverage {
public static void main(String[] args) {
long sum = 0;
long highLow = 0x8000_0000_7FFF_FFFFL;
long countNumber = 0;
for (; (countNumber >> 32) < 5; countNumber += 0x1_0000_0000L) {
countNumber = (countNumber & 0xFFFF_FFFF_0000_0000L)
| ((int) (Math.random() * 100) & 0xFFFF_FFFFL);
System.out.println(((countNumber >> 32) + 1) + ". number is: " + (int) countNumber);
sum += (int) countNumber;
if ((highLow >> 32) < (int) countNumber)
highLow = (highLow & 0xFFFF_FFFFL) | (countNumber << 32);
if (((int) highLow) > (int) countNumber)
highLow = (highLow & 0xFFFF_FFFF_0000_0000L) | (countNumber & 0xFFFF_FFFFL);
}
System.out.println("Average: " + ((double) sum) / (countNumber >> 32));
System.out.println("Min: " + (int) highLow);
System.out.println("Max: " + (highLow >> 32));
}
}
The techniques used are bit-shifting and masking to use the upper/lower half of the long datatype as independendly accessible values. Note amount of complicated expressions necessary as well as the numerous constansts in the expressions plus typecasts almost everywhere.
This is code you should never ever use - it works, but even an experienced programmer will need an excessive amount of thinking to figure out if its working correctly. My guess is that a typical beginner class teacher will have trouble understanding it at all.
Edit2: Scratch the above, it can be done with one variable. How? By replacing multiple variables with an array:
public static void main(String[] args) {
long[] vars = new long[5];
vars[1] = Long.MIN_VALUE;
vars[2] = Long.MAX_VALUE;
for (vars[0] = 0; vars[0] < 5; ++vars[0]) {
vars[4] = (int) (Math.random() * 100);
System.out.println((vars[0] + 1) + ". number is: " + vars[4]);
vars[3] += vars[4];
if (vars[4] > vars[1])
vars[1] = vars[4];
if (vars[4] < vars[2])
vars[2] = vars[4];
}
System.out.println("Average: " + ((double) vars[3]) / vars[0]);
System.out.println("Min: " + vars[1]);
System.out.println("Max: " + vars[2]);
}
Needless to say thats still confusing code. Each index of the vars array is used to hold one of the variables (0 = loop control, 1 = min, 2 = max, 3 = sum, 4 = number).
You see it all depends on what is considered a variable.

Why isn't java doing math correctly [duplicate]

This question already has an answer here:
Java Division error
(1 answer)
Closed 7 years ago.
I was trying to create a probability calculator for fun, but for some reason, java gets the incorrect answer when I divide two numbers. Here is my code....
import javax.swing.JOptionPane;
public class ProbabilityCalculator {
public static void main(String args[]) {
String a = JOptionPane.showInputDialog("One out of.....");
int x = Integer.parseInt(a);
int numLoops = 1000;
int y = 0;
int n = 0;
for (int i = 0; i < numLoops; i++) {
int result = (int) (Math.random() * x + 1);
int result2 = (int) (Math.random() * x + 1);
if (result == result2)
y++;
else
n++;
}
System.out.println(y);
System.out.println(numLoops);
System.out.println(y/numLoops);
double d = (y/numLoops) * 100; //get it? double d??
JOptionPane.showMessageDialog(null, "Out of " + numLoops + " trials, "
+ y + " times it worked, while " + n + " times it didn't.");
JOptionPane.showMessageDialog(null, "Your percentage was " + d
+ "%.");
System.exit(0);
}
}
When I ran this code one time, y was 514, numLoops was 1000, but d would be 0, when d is supposed to be 51.4 (514 / 1000 * 100). Why is this happening?
y/numLoops will be an integer since both arguments are ints. Try (double)y/numLoops or y/(double)numLoops instead.
If you decompose double d = (y/numLoops) * 100; you'll get something similar to those steps:
int r = y/numLoops; - according to the spec an operation having two integer operands will have an int result.
double d = r * 100 here r will be 0 due to being int.

Split number into several numbers

I wrote a programm to get the cross sum of a number:
So when i type in 3457 for example it should output 3 + 4 + 5 + 7. But somehow my logik wont work. When i type in 68768 for example i get 6 + 0 + 7. But when i type in 97999 i get the correct output 9 + 7 + 9. I know that i have could do this task easily with diffrent methods but i tried to use loops . Here is my code: And thanks to all
import Prog1Tools.IOTools;
public class Aufgabe {
public static void main(String[] args){
System.out.print("Please type in a number: ");
int zahl = IOTools.readInteger();
int ten_thousand = 0;
int thousand = 0;
int hundret = 0;
for(int i = 0; i < 10; i++){
if((zahl / 10000) == i){
ten_thousand = i;
zahl = zahl - (ten_thousand * 10000);
}
for(int f = 0; f < 10; f++){
if((zahl / 1000) == f){
thousand = f;
zahl = zahl - (thousand * 1000);
}
for(int z = 0; z < 10; z++){
if((zahl / 100) == z){
hundret = z;
}
}
}
}
System.out.println( ten_thousand + " + " + thousand + " + " + hundret);
}
}
Is this what you want?
String s = Integer.toString(zahl);
for (int i = 0; i < s.length() - 1; i++) {
System.out.println(s.charAt(i) + " + ");
}
System.out.println(s.charAt(s.length()-1);
The problem with the code you've presented is that you have the inner loops nested. Instead, you should finish iterating over each loop before starting with the next one.
What's happening at the moment with 68768 is when the outer for loop gets to i=6, the ten_thousand term gets set to 6 and the inner loops proceed to the calculation of the 'thousand' and 'hundred' terms - and does set those as you expect (and leaving zahl equal to 768 - notice that you don't decrease zahl at the hundreds stage)
But then the outer loop continues looping, this time with i=7. With zahl=768, zahl/1000 = 0' so the 'thousand' term gets set to 0. The hundred term always gets reset to 7 with zahl=768.
The 97999 works because the thousand term is set on the final iteration of the 'i' loop, so never gets reset.
The remedy is to not nest the inner loops - and it'll perform a lot better too!
You should do something like this
input = 56789;
int sum = 0;
int remainder = input % 10 // = 9;
sum += remainder // now sum is sum + remainder
input /= 10; // this makes the input 5678
...
// repeat the process
To loop it, use a while loop instead of a for loop. This a great example of when to use a while loop. If this is for a class, it will show your understanding of when to use while loops: when the number of iterations is unknown, but is based on a condition.
int sum = 0;
while (input/10 != 0) {
int remainder = input % 10;
sum += remainder;
input /= 10;
}
// this is all you really need
Your sample is a little bit complicated. To extract the tenthousand, thousand and the hundreds you can simply do this:
private void testFunction(int zahl) {
int tenThousand = (zahl / 10000) % 10;
int thousand = (zahl / 1000) % 10;
int hundred = (zahl / 100) % 10;
System.out.println(tenThousand + "+" + thousand + "+" + hundred);
}
Bit as many devs reported you should convert it to string and process character by character.

Write a program which reads two non-negative integers 'x' and 'y' (where x < y) and then prints three random integers in the range x...y

import java.util.Scanner;
import java.util.Random;
public class Lab04b
{
public static void main(String []args)
{
Random generator = new Random ();
Scanner scan = new Scanner(System.in);
int num1;
int num2;
int num3;
System.out.println("Enter X:");
num1 = scan.nextInt();
System.out.println("Enter Y:");
num2 = scan.nextInt();
num3 = generator.nextInt(num2) + num1;
System.out.println("3 random integers in the range " + num1 + ".." + num2 + " are: " + num3);
}
}
I am stuck on how to get 3 random integers between the x and y range. Y being the biggest integer.
The trick is finding the difference between x and y. Here is what you need to do -
int diff = Math.abs(num1 - num2);
num3 = generator.nextInt(diff) + Math.min(num1, num2);
Just do it 3 times and you get your 3 numbers.
From the docs
nextInt(int n)
Returns a pseudorandom, uniformly distributed int value between 0
(inclusive) and the specified value (exclusive), drawn from this
random number generator's sequence.
so random.nextInt(Y) would give you numbers 0..Y, I guess you are missing how to get the lower bound correctly.
X + random.nextInt(Y-X) does the trick.
Read the documentation. The nextInt(n) function returns an Integer in [0, n). So, in your case, you can use the formula min + nextInt(max-min), which will give you a number in [min, max).
Random generator = new Random();
int max = (x >= y ? x : y);
int min = (x < y ? x : y);
int aRandomNumber = min + generator.nextInt(max-min);
Firstly have a loop which will run 3 times, to generate 3 random numbers(as you said you need 3 random numbers, but you're just generating only 1).
Next, the pattern you've used to generate a random number seems to be flawed. You can use the below type 1 pattern to accomplish that.
min + Math.random() * ((max - min) + 1));
Or this type 2 pattern
rand.nextInt((max - min) + 1) + min;
So you can do something like this:-
for (int i = 0; i < 3; i++) {
// Type 1
num3 = num1 + (int)(Math.random() * ((num2 - num1) + 1));
// Type 2
// num3 = generator.nextInt((num2 - num1) + 1) + num1;
System.out.println("3 random integers in the range " + num1 + ".." + num2 + " are: " + num3);
}
P.S:- You need to first determine the max and min, yourself. I've just given the pattern and a sample.
import java.util.Scanner;
public class GenerateRandomX_Y_numbers {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the numbers x and y: ");
int x = Math.abs(sc.nextInt()), y = Math.abs(sc.nextInt());//we need //non-negative integers, that is why we use here Math.abs. which means the //absolute value
print3RandomNumbers_between_x_and_y(x, y);
}
public static void print3RandomNumbers_between_x_and_y(int x, int y) {//here //I create a method with void type that takes two int inputs
boolean isTrue = (x < y);//according to our conditions X should less //than Y
if (isTrue) {//if the condition is true do => generate three int in the //range x .... y
int rand1 = (int) (Math.random() * (y - x) + 1);// y - x means our //range, we then multiply this substraction by Math.random()
int rand2 = (int) (Math.random() * (y - x) + 1);//the productof this //multiplication we cast to int type that is why we have
int rand3 = (int) (Math.random() * (y - x) + 1);//(int) before //(Math.random() * (y - x));
System.out.println("rand1 = " + rand1);//
System.out.println("rand2 = " + rand2);//
System.out.println("rand3 = " + rand3);//here print our result
} else
System.out.println("Error input: X should be less than Y. Try it again!");//if the condition is not true, i mean if x is not less than or equal //to Y, print this message
}
}

Categories

Resources