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);
Related
I made a program for the question and it's working fine, but in some cases it's not working like when I enter 656, it's showing like this:
The error
The code is showed below:
public static void main(String[] args) {
Scanner rx = new Scanner(System.in);
int ui,uiy,troll3,troll1;
float uix,uis,uiz,uit;
System.out.println("Enter a valid three digit number to calculate the frequency of the digits in it. \n");
ui = rx.nextInt();
if(ui>99&&ui<=999) {
uis = (float) ui;
//System.out.println(uis+" uis");
uix = uis / 10;
//System.out.println(uix+" uix");
uiy = (int) uix;
//System.out.println(uiy+" uiy");
troll3 = (int) ((uix - uiy) * 10); //1st digit
//System.out.println("3d " + troll3);
uiz = uix / 10;
//System.out.println(uiz+ " uiz");
troll1 = (int) uiz;
//System.out.println("1d " + troll1);
uit = (uiz - troll1) * 10;
//System.out.println(uit+" uit");
int troll2 = (int) uit;
//System.out.println("2d " + troll2);
if (troll1 == troll2 && troll1 == troll3) {
System.out.println("The number " + troll1 + " appears three times.");
} else if (troll1 != troll2 && troll2 != troll3 && troll1 != troll3) {
System.out.println("The number " + troll1 + " appears one time.");
System.out.println("The number " + troll2 + " appears one time.");
System.out.println("The number " + troll3 + " appears one time.");
} else if (troll1 == troll2) {
System.out.println("The number " + troll1 + " appears two times.");
System.out.println("The number " + troll3 + " appears one time.");
} else if (troll1 == troll3) {
System.out.println("The number " + troll3 + " appears two times.");
System.out.println("The number " + troll2 + " appears one time.");
} else if (troll2 == troll3) {
System.out.println("The number " + troll2 + " appears two times.");
System.out.println("The number " + troll1 + " appears one time.");
}
}
else{
System.out.println("The entered number is invalid");
}
}
It mostly gives an error when it consists of digit 5 in the middle. It shows an increment in values and swap in values. Please do help.
Thanks in advance! :-)
Why are you converting to float? float and double attempts to represent an infinite infinity of numbers (there are an infinite amount of integers. Between 2 integers, there are an infinite amount of numbers too: An infinite amount of infinities)... using only 32 bits. This is obviously impossible so instead only a few numbers are representable, and anything else is silently rounded to one of the select few. This means float and double introduce rounding errors.
After any math done to any double or float, == is broken. You can't use those; at best, you can try 'delta equality' (not a == b, but Math.abs(a - b) < 0.00001) but making the claim that your code works for all possible inputs becomes very difficult indeed, it's not going to be very fast, and the code readability isn't great either. So, don't.
Stop using floats, problem solved.
Your 'math' to get the individual digits is a bit circumspect and isn't going to just work if you replace things with int either. What you're missing is the % operator: Module (a.k.a. remainder).
Given, say, 656:
int in = 657;
int digit1 = in % 10;
in = in / 10;
System.out.println(in); // 65
System.out.println(digit1); // 7
int digit2 = in % 10;
in = in / 10;
System.out.println(in); // 6
System.out.println(digit1); // 5
int digit3 = in;
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?
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.
This question already has answers here:
Output in a table format in Java's System.out
(8 answers)
Closed 7 years ago.
My code is this:
// for loop for displaying multiple values
for (int index = 0; index < 5; index++) {
System.out.println("\t\t" + name[index] + "\t\t\t" + "$" + sales[index] + "\t\t\t" + "$" + comm[index] + " ");
}
This is the current output, but I want to display output with same spacing
Sales and Commission
======================================================
Salesperson Sales Amount Commission
-----------------------------------------------------
u ujuhygtfd $89000 $8900.0
uh uh $87000 $8700.0
t t $65000 $5200.0
f f $54000 $4320.0
u r $43000 $2580.0
Total: 9 Data entries
How can I display my data like this?
Sales and Commission
======================================================
Salesperson Sales Amount Commission
-----------------------------------------------------
u ujuhygtfd $89000 $8900.0
uh uh $87000 $8700.0
t t $65000 $5200.0
f f $54000 $4320.0
u r $43000 $2580.0
Total: 9 Data entries
As said in this answer (slightly modified):
Use System.out.format. You can set lengths of fields like this:
System.out.format("%32s%10d%16d", name[index], sales[index], comm[index]);
This pads name[index], sales[index], and comm[index] to 32, 10, and 16 characters,
respectively.
See the Javadocs for java.util.Formatter for more information on the
syntax (System.out.format uses a Formatter internally).
You could do something like
for (int index = 0; index < 5; index++) { // for loop for displaying multiple values
int numOfSpaces = 20 - name[index].length();
String spaces = "";
for (int i = 0; i<numOfSpaces; i++)
spaces += " ";
System.out.println("\t\t" + name[index] + spaces + "$" + sales[index] + "\t\t\t" + "$" + comm[index] + " ");
}
And change the arbitrary 20 to anything you want, eg. the longest string in names + 5.
My content data in Notepad is 1 to 25. How can I display the data that is marked in red below. The other values can be ignored.
change
int i = sc.nextInt();
System.out.println(i + " ");
to
int i = sc.nextInt();
if(i%10 <= 5) {
System.out.println(i + " ");
}
Idea is that i%10 will give the unit digit of a number. So if it is <= 5 print that number.