java printing outside of a loop - java

I'm a high school student learning to program, and I can't get around this problem right now. I'm trying to print the averages outside of the loop, but I don't know how.
for (int index = 0; index < temperature.length; index++) {
double tempSum = 0;
tempSum += temperature[index];
double averageTemp = tempSum / temperature.length;
double rainSum = 0;
rainSum += precipitation[index];
}
//Output: display table of weather data including average and total
System.out.println();
System.out.println(" Weather Data");
System.out.println(" Location: " + city + ", " + state);
System.out.println("Month Temperature (" + tempLabel + ") Precipitation (" + precipLabel + ")");
System.out.println();
System.out.println("***************************************************");
for (int index = 0; index < precipitation.length; index++) {
System.out.println(month[index] + " " + temperature[index] + " " + precipitation[index]);
}
System.out.println("Average Temperature: " + averageTemp + " Total Rainfall: " + rainSum);

The comments provide the right idea. Variables in Java have block scope, which means that they are unavailable outside the block in which they are declared. JavaScript has "hoisting," which means that, no matter where the var keyword is used, the variable will be defined.
Move your variable declarations outside of the "for" blocks. Then they will be available when the loop is done. You can also do that for the "index" variable if you need to know the its last value. Typically, that is not necessary.

In your code the variable averageTemp is only existing/ accessible within the for-loop.
To have it accessible outside of the loop, you need to the declare outside, in your case before the loop. Kind of
double averageTemperature;
for (....) {
In the for-loop you could sum up the temperatures to tempSum and after the loop is finished divide tempSumby the number of items you iterated over in the loop. If you would like to do so, keep in mind that also tempSum has to be declared before entering the loop.

Related

How do I sum string arrays in java

I am creating a simulated test that is ready to be graded. My main module request user input of 20 multiple choice answers (A,B,C,D). I am using a for loop to populate both arrays. I next have an If .equals statements that compares the two arrays for correct answer and in correct answer. `
My current out put is:
The correct answer to question 16 is: C
Your answer to question 16 is: C
Question 16 is correct
The correct answer to question 17 is: C
Your answer to question 17 is: A
Question 17 is incorrect
Next
I am attempting to simulate an out put of:
You passed the exam with a grade of 90%. Congratulations!
Number of correct answers: 18
Number of incorrect answers: 2
Here is the portion of code I am working on
int arraySize;
arraySize = 20;
// Declare and assign the variables to create the parallel array
int count;
// Access the contents of both arrays
for (count = 0; count <= arraySize - 1; count++) {
System.out.println();
// Message to diplay the Answerkey and testAnswer
System.out.println("The correct answer to question " + (count + 1) + " is: " + answerKeyArray[count]);
System.out.println("Your answer to question " + (count + 1) + " is: " + testAnswers[count]);
// Find the correct and incorrect answers
if (answerKeyArray[count].equals(testAnswers[count])) {
// Message to display the answer is correct
System.out.println("Question " + (count + 1) + " is correct ");
} else {
// Message to display the answer is incorrect
System.out.println("Question " + (count + 1) + " is incorrect ");
you can make a counter variable inside the for loop, which would make it a local variable, and it would be voided after it goes outside the for loop. Below is an example
for(int i = 0; i < arraySize; i++){
int correctCounter = 0;
int incorrectCounter = 0;
if(PretendThisIsAConditional){
counter++;
}
else{
incorrectCounter++;
System.out.println("Number of correct answers: " + correctCounter + "Number of incorrect answers: " + incorrectCounter);
}
If you have the number correct inside a string for whatever reason you can do
int numCorrect = Integer.parseInt(String);

How to print multiple variables from different methods?

I want to create a print statement that displays three values. 1) Counter variable which shows number of iterations. 2) Array recorder which records the values of the elements and 3) the value of these elements + 5.
There is a change method which takes all of the values in the array and adds 5 to them. I just can't understand how to print this value in line with the counter variable and Array Element counter. Is this possible to do?
int sam[] = {1,2,4,5,6,4,3,67};
change(sam);
for (int y:sam) {
for(int counter =0; counter<sam.length;counter++) {
//this is where I wish to print out the 3 elements
System.out.println(counter+ "\t\t" + sam[counter]+y);
}
}
public static void change(int x []) {
for(int counter=0; counter<x.length;counter++)
x[counter]+=5;
}
Everything is fine except that sam[counter] + y is evaluated as integer value because both arguments are integers. You need string concatenation instead:
System.out.println(counter + " " + sam[counter] + " " + y);
Or something like this (using formatter):
System.out.printf("counter = %d, sam[counter] = %d, y = %d\n", counter, sam[counter], y);
%d is a decimal argument, \n is a new line.
EDIT: Regarding your code. If you want to ouput the following row format for each element in the array
counter sam[counter] sam[counter] + 5
then just use
int sam[] = {1,2,4,5,6,4,3,67};
for (int counter = 0; counter < sam.length; counter++) {
System.out.println(counter + "\t\t" + sam[counter] + "\t\t" + (sam[counter] + 5));
}
This will print values in needed format.
0 1 6
1 2 7
2 4 9
...
Or, if you want to change array, but be able to print old values, try this:
int sam[] = {1,2,4,5,6,4,3,67};
for (int counter = 0; counter < sam.length; counter++) {
System.out.println(counter + "\t\t" + sam[counter] + "\t\t" + (sam[counter] += 5));
}
Here (sam[counter] += 5) will increment each elemnent by 5 and return the new value.
Get rid of this outer loop for (int y:sam)
This should work:
for(int counter =0; counter<sam.length;counter++) {
System.out.println(counter+ "\t\t" + sam[counter]+ "\t\t" + counter + sam[counter] + 5);
}
Your question was a little hard to interpret, but just drop the outer loop, and don’t “+y”
Scratch that. What do you think the change routine did for you? Did you want an array with the original value and another array with the changed value, and then have access to both of those arrays?

For Loop, the program will not follow my for loop

For Loop, I am trying to understand why the loop will not run. Does anyone have any loop examples I can see?
import java.util.Scanner;
public class Conversion
for (t = ttt; t >= ttt + 36; t +=5) //counter = counter + 5
{
}
System.out.println ("t \t ttt");
System.out.println(j + "\t\t " + i);
//Show result
Unless it overflows, i will never be greater or equal to i+36. You should use a different variable for your loop:
for (double j = i; j >= i + 36; j+=6)
First, i = i is redundant. If you already defined the variables, you can leave it empty.
Second, you are always asking if i is greater or equal to itself plus 36, in which is ALWAYS false. Try to pre calculate it.
double limit = i + 36;
for (; i >= limit ; i +=6) //counter = counter + 6
{ }
And by the way, be careful with iterating with double variables, you can have wrong outputs in Java, due to the way it treats the decimals. You could have an extra loop.
I hope I have helped.
Have a nice day :)
Your for loop has no body, and therefore it isn't doing what you want it to do. If you want to print out the conversion of inches to centimeters for every 6 inches between i and i+36 your for loop should be
System.out.println("Inches\tCentimeters");
for(double j = i; j <= i + 36; j += 6) {
System.out.printf("%f\t%f\n", j, inchesToCM(j));
}

Find the Max/Min of values within a for loop

I've searched for answers to this specific question, but haven't been able to find anything. I need to find the maximum and minimum of the input numbers but the values I need are inside the for loop and I can't figure out how to use them outside of it.
System.out.print("How many numbers do you want to input?");
int totalNumbers = console.nextInt();
int minMax = 0;
for(int i = 1; i <= totalNumbers; i++){
System.out.print("Number " + i + ": ");
int inputNumbers = console.nextInt();
}
System.out.println();
int smallest = Math.min(minMax);
System.out.println("Smallest = " + smallest);
int largest = Math.max(minMax);
System.out.println("Largest = " + largest);
I don't need changed code just something that will get me on the right track.Thank you!
Can you notice the problem with the following loop?
for(int i = 1; i <= totalNumbers; i++){
System.out.print("Number " + i + ": ");
int inputNumbers = console.nextInt();
}
You are running the loop totalNumbers times and every time you create a new int with name inputNumbers and store the value received from console. Also where are you changing the value of minMax? Also Math.min(or max) does not take single paramtere and wont even compile.
Now you have few options:
Either store all the numbers in an array and then traverse that for min and max elements using some utility method.
Set some min and max value and run a loop to get all items and also keep track of min and max in loop.
I am not writing any solution as I want you to try it yourself.
The Math.min() and Math.max() methods, according to the oracle documentation, can only compare two values. Importing the values into an array, and then performing operations on the array, should allow you to find minimums and maximums, as well as any other data operation quite easily.
int[] numbers = new int[totalNumbers];
for (int i = 0; i < totalNumbers; i++) {
numbers[i] = console.nextInt();
}
//Other Operations
Unless I'm misreading what you want, can't you just maintain a variable on the outside of the for loop and check them?
int minMax = 0;
int smallest = 0;
int largest = 0;
for(int i = 1; i <= totalNumbers; i++){
System.out.print("Number " + i + ": ");
int inputNumbers = console.nextInt();
if(inputNumbers > largest){
largest = inputNumbers;
} else if (inputNumbers < smallest){
smallest = inputNumbers;
}
}
System.out.println();
System.out.println("Smallest = " + smallest);
System.out.println("Largest = " + largest);
This is the most direct and logical way of checking the input values and deciding whether they're the smallest or largest currently known (Edit: Unless you require the use of Math.minMax)
Pseudocode:
smallest := +∞
largest := -∞
for each number read, n:
if n > largest:
largest := n
if n < smallest:
smallest := n
print the results
Hint:
Java ints can't represent ±∞. Use Integer.MIN_VALUE and Integer.MAX_VALUE instead.
You can do it by just put if else condition inside for loop... like
take 2 variable at outside loop one for max value and other for min value store.
inside loop assign input number to min and max first time.
after that comare next number with this and reassign values.
at end of loop you will find both min and max.

Scoring system and Arrays

My program keeps adding up the score for each player, rather than keeping it separate for example if first player gets 3/5 and the second gets 2/5 the score display for the second player will be 5. I know the answer is probably very simple however I'm not able to find it within the code.
public static void questions(String[] question, String[] answer, int n) {
String[] name = new String[n]; // Player Names
int[] playerscore = new int[n]; // Argument for Score
String[] que = new String[question.length]; //Questions for Loops
int score = 0; // Declare the score
/* --------------------------- For loop for number of players --------------------------- */
for (int i = 0; i < n; i++) {
name[i] = JOptionPane.showInputDialog("What is your name player" + (i + 1) + "?");
JOptionPane.showMessageDialog(null, "Hello :" + name[i] + " Player number " + (i + 1) + ". I hope your ready to start!");
/* --------------------------- Loop in Loop for questions --------------------------- */
for (int x = 0; x < question.length; x++) {
que[x] = JOptionPane.showInputDialog(question[x]);
if (que[x].equals(answer[x])) {
score = score + 1;
} else {
JOptionPane.showMessageDialog(null, "Wrong!");
}
} // End for loop for Question
playerscore[i] = score;
System.out.println("\nPlayer" + (i) + "Name:" + name[i] + "\tScore" + score);
}
}
You will need to reset the score to 0 before each player starts.
Add this after the loop for each player:
score = 0;
Alternatively you could increment the score directly in the array. Just change:
score = score + 1;
to:
playerscore[i] = playerscore[i] + 1;
or simply:
playerscore[i]++;
Assign score=0 after the line
playerscore[i] = score;
Every each and every player is assigned with his score in inner loop. Since score is declared as instance variable it will not differentiate between two different players. In order to have each and every individual player with his own scores, assign score with zero as soon as questions exceeds.

Categories