Making a quiz with Java using arrays. Need pointers with grading answers - java

This is for a class. I'm having trouble figuring out how to best compare the user input with the array answerkey and consequently grade the answers given. I tried searching for a while but wasn't able to find what I needed, so any pointers would be much appreciated!
The prompt for the exercise is:
Write a DMV program that grades the written portion of the driver's license exam. It should have 20 multiple choice questions. It should ask the user to enter the student’s answers for each of the 20 questions, which should be stored in another array. After the student’s answer have been entered, the program should display a message indicating whether the student passed or failed the exam.( A student must correctly answer 15 of the 20 questions to pas the exam). It should then display the total number of correctly answered questions, and the total number of incorrectly answered questions. Input validation: Only accept the letters A, B, C or D.
My code so far:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String[] answerkey = {"b","d","a","a","c","a","a","d","b","b","b","d","c","a","c","c","a","d","a","a"};
int n = 0;
int correct = 0;
int incorrect = 0;
String answer = "";
for (int i = 0; i < 20; i++){
System.out.println("Please enter your answers. Acceptable input is limited to A,B,C and D.\n");
answer = input.next();
if (answer.compareTo(answerkey[0])==0){
correct++;}
else {incorrect++;}
}
if (correct > 14){
System.out.println("You passed.");
} else {
System.out.println("You failed.");
}
System.out.println("You have " + correct + " correct answers.");
System.out.println("You have " + incorrect + " incorrect answers.");
}

Use a dynamic index accessing variable. Right now, every answer you have will be compared to the first answer ("b")
An example of this would be
String[] myArray = { //initialize values here
};
for (int index = 0; index <= myArray.length-1; index++){
if (answer.equals(myArray[index]){
correct++;}
else{
incorrect++;}
}

Try this code on comparing the user input with the array myArray.
Hope this helps.
String[] myArray= { //initialize values here
};
if ((myArray[0]).equals(answer)){
correct++;
} else{
incorrect++;
}

Related

What code should i add to print out "seat already taken" if user input seats that are taken already or input the same seat?

I am trying to make seat reservation or assignment using one dimensional array. A user input choose 2 sections whether economy class or first class but i dont wanna go that far since i dont understand yet the algorithm. Lets assume user inputs first class and choose seats from seat 1, the user input must be saved in the array. If user inputs the same seat again, it must print out seat already taken. how can i work printing out 'seat already taken' if user inputs seats that are taken or inputs the same seat?
int arr[] = new int[10];
for(int i=0;i<arr.length;i++)
{
System.out.println ("(1)First Class \n(2)Economy Class");
int section = input.nextInt();
if(section == 1)
{
System.out.println ("Welcome to First Class");
System.out.println ("Choose Seat from 1-2");
arr[i] = input.nextInt();
if(arr[i] == 1)
{
arr[0]=1;
System.out.println ("Seat #1");
}
else if(arr[i] == 2)
{
arr[1]=2;
System.out.println ("Seat #2");
}
else if(arr[i] == arr[0] || arr[i]==arr[1])
{
System.out.println ("Seat already taken");
}
}
I don't seem to understand the relation between the code you've provided and the problem you're trying to solve.
If I understand you correctly, you're trying to see if the array already contains an element which is input by a user. For that, you could do something like this
int a[] = new int[10];
for(int i=0;i<10;i++){
boolean seatTaken = false;
int seat = input.nextInt();
for(int j=0;j<i;j++){
if(a[j]==seat){
seatTaken = true;
break;
}
}
if(seatTaken){
System.out.println("The Seat has already been taken");
i = i - 1;
}else{
a[i] = seat;
}
}
Of course, this could be made a lot more efficient by using a HashSet which has a constant lookup time

Infinite multiplication questions

I am trying to make a program that randomly generates two single digit numbers, creates a multiplication question, asks the user for the answer, counts the amount of questions and correct answers, and after every question the user is able to stop the loop to see how many he got correct out of the number of questions that were given.
I believe that I should be using a while loop (probably the easiest way) but I don't know exactly how to go about doing that. Here is what I currently have:
int number = 0;
int number1 = (int)(Math.random() * 10); //Produce two single digit numbers
int number2 = (int)(Math.random() * 10);
Scanner input = new Scanner(System.in); //Create Scanner
System.out.print("What is " + number1 + " + " + number2 + "? ");
int answer = input.nextInt();
while (number <= 10) {
if (number1 + number2 != answer ) {
System.out.println(" Incorrect!\n Would you like to see your overall result? (yes or no)");
}
else {
System.out.println(" Correct, great job!\n Would you like to see your overall result? (yes or no)");
}
}
Since this seems like an assignment I'll just give you pseudocode
MainMethod
{
//Create a new Random to generate random numbers
//(Import java.util.random)
//You need variables for:
//Total number of questions asked
//Total number of correct answers
//Start the question loop
while(true){
//Generate your two random numbers
//Ask the question
//Index the total number of questions
//Get their answer
//Check their answer
if(answer is correct){
//Index correct answers
}
//Ask whether they want to continue
//Check whether they want to stop
if(they want to quit){
//Break out of the while loop (break;)
}
}
//Tell them how many they got correct out of the total
}
Maybe I gave a little too much, but I hope this helps.

Creating a loop to check array (java)

Homework assignment Suggestions only please as I wish very much to learn this as second nature!
The goal is to create an array with a user specified question amount (array size) followed by an answer key (said array size now filled). Then to have the user input the "students" answers to check against key.
I wrote all that no worries. Works lovely. The issue I am having is in two areas:
Create a loop that asks to grade another quiz.
Have it only check/score/calculate every other answer. ie: even answers only.
I have used a do/while loop to continue checking but couldn't get a sentinel value to stick. Also depending on where I placed it, the answers kept coming up as the first check. So I am unsure as to where to place and how to write it. I even tried to use a for loop boxing in the array and student answer portion to no avail.
As regards to having it check every other one, I thought of modifying the count of "i" to something like ((i+1)*2) instead of i++ for the two for loops but I just get errors as that seems to not be proper at all.
Thank you in advance!
import java.util.Scanner;
import java.text.NumberFormat;
public class EvenQuizzes {
public static void main(String[] args) {
int quizQuest = 0, count = 0;
double percentTotal = 0.0;
Scanner scan = new Scanner(System.in);
System.out.print("How many questions are in the quiz? Or enter 0 to quit. ");
quizQuest = scan.nextInt();
int[] answers = new int[quizQuest]; // scan in question total and apply
// to array
System.out.println("Enter the answer key: ");
for (int i = 0; i < answers.length; i++) {
answers[i] = scan.nextInt();
}
for (int i = 0; i < answers.length; i++) {
System.out.println("Enter the answer to be graded : ");
int toGrade = scan.nextInt();
if (toGrade == answers[i]) {
count++;
}
}
percentTotal = ((double) count / quizQuest);
NumberFormat defaultFormat = NumberFormat.getPercentInstance();
defaultFormat.setMinimumFractionDigits(2);
System.out.println("The questions answered correctly total: " + count);
System.out.println("The percentage correct is: " + defaultFormat.format(percentTotal));
System.out.println("\nAnother quiz to be graded?");
}
}
// do ( quizQuest != 0){ //condition check to run new quiz against KEY
// for (int j = 0; (quizQuest = scan.nextInt()) != 0; j++); {
At the bottom is what I had considered for the loop portion I am having trouble with.
As you asked for hints (and not the code), here it is:
For more than one quizzes, use do-while, as follows:
do{
//do something
//scan the value of quiz quest
//do something
}while(quizquest != 0)
Now, if only answers at even positions are to be checked, do following:
for (int i =0; i <answers.length; i++)
{
System.out.println("Enter the answer to be graded : ");
int toGrade = scan.nextInt();
if(i % 2 == 0 && toGrade == answers[i]){
count++ ;
}
}
Create a loop that asks to grade another quiz: You could use a do-while loop with a boolean indicating if the user (teacher?) wants to grade another quiz:
do{
boolean continue = false;
// check if the user wants to continue
while(continue);
Have it only check/score/calculate every other answer. ie: even answers only: You can check for even answers with the modulo operator:
if(i % 2 == 0){
// even answer
}
Hope this helps!
You should have a variable, perhaps named continue, whose default value is 'Y'. At the very beginning, create a while loop that checks the condition continue==Y, and at the end when you ask "Another quiz to be graded?", read in the input to the variable continue.

Is there a way to print a variable, alter the same variable and print the two of them in a list?

First off I'm sorry if this is a wierd one, but I don't exactly know what I'm trying to do in coding terms.
To clarify what I wish to do, I want to know a way to "Save" the value of receipt to either a list/set/array then go trough the process that determined the value of receipt and save that to the list again, and when I print the list the two different values of receipt are printed after eachoter.
Lets say first time the value of receipt was determined it was equal to x, then after I've saved that to a list and gone trough the same value determening process receipt= y and I add that to the list. Would it print: x and then y. Or y and y? And if it prints the new value of receipt twice, how do I make it print the two different values after eachother?
import java.util.Scanner;
public class TicketV005
{ // start of public class
public static void main (String [] args)
{ // start of main
Scanner keyboard = new Scanner(System.in);
int printedTickets,ticketTotal;
String fareType, purchaseLoc;
String answer1 =("null");
String receipt =("null");
int zoneAmount = 0;
double price = 0;
int answer2 = 0;
System.out.print("How many tickets do you wish to buy?(Answer with a number please.) ");
ticketTotal = keyboard.nextInt();
printedTickets = 0;
while (ticketTotal <= 0)
{
System.out.println("\nIncorrect input, try again.");
System.out.println("How many tickets do you wish to buy?(Answer with a number please.) ");
ticketTotal = keyboard.nextInt();
}
while(ticketTotal !=printedTickets )
{
System.out.print("Welcome! Are you buying a reduced fare ticket?(y/n) ");
answer1 = keyboard.next();
if (answer1.equals("y"))
fareType=("reduced fare");
else if (answer1.equals("n"))
fareType=("standard fare");
else
fareType=("null");
while (fareType.equals("null"))
{
System.out.println("\nIncorrect input, try again.");
System.out.println("Welcome! Are you buying a reduced fare ticket?(y/n) ");
answer1 = keyboard.next();
}
System.out.println("Would you like to purchase your ticket at 1. the automated services or at 2. the cashier? ");
answer2 = keyboard.nextInt();
if (answer2 ==1)
purchaseLoc=("automated services");
else if (answer2 ==2)
purchaseLoc=("cashier");
else
purchaseLoc=("null");
while (purchaseLoc.equals("null"))
{
System.out.println("\nIncorrect input, try again.");
System.out.println("Would you like to purchase your ticket at 1. the automated services or at 2. the cashier? ");
answer2 = keyboard.nextInt();
}
System.out.println("How many zones will you be travelling? (1-3) ");
zoneAmount = keyboard.nextInt();
while (zoneAmount <= 0 || zoneAmount > 3 )
{
System.out.println("\nIncorrect input, try again.");
System.out.println("How many zones will you be travelling? (1-3) ");
zoneAmount = keyboard.nextInt();
}
//Start of reduced fare
if (answer1.equals("y") && answer2 == 1 )
{ // Start of automated services reduced fare
for (int i= 1 ; i <= 3 ; i++)
{
if (zoneAmount == i)
price=(10*i)+10;
}
} //end off automated services reduced fare
if (answer1.equals("y") && answer2 == 2)
{ // Start of cashier reduced fare
for (int i= 1 ; i <=3 ; i++)
{
if (zoneAmount == i)
price=(14*i)+14;
}
} //End of cashier reduced fare
//End of reduced fare
//Start of standard fare
if (answer1.equals("n") && answer2==1)
{ //Start of standard fare automated services
for (int i = 1; i <=3 ; i++)
{
if ( zoneAmount ==i)
price=(18*i)+18;
}
} // end of standard fare automated servies
if (answer1.equals("n") && answer2==2)
{ // Start of standard fares cashier
for (int i = 1; i <=3 ; i++)
{
if( zoneAmount == i)
price=(22*i)+22;
}
} // End of standard fares cashier
//End of standard fare
System.out.println("");
receipt = (zoneAmount+" zone(s), "+ fareType+", bought at: "+ purchaseLoc+". Your price: "+price+" SEK.");
System.out.println(receipt);
printedTickets++;
System.out.println(""); //Empty line for when/if it repeats
} // end of while printedTickets is not equal to ticketTotal
}// end of main
}// end of public class
Edit1: Included full code for clarity.
Edit2: Better Clarification
It looks like you're asking two questions. One relates to whether you can save a variable and the other is about how to have a bunch of things aggregated together. From your code it's not clear what your aims are.
In java, the things you declare, like
String receipt
are references. This means they keep track of a piece of data. However, other things can also keep track of that same piece of data. So:
String receipt1 = "100EUR";
String receipt2 = receipt1;
In the above code, there's only one thing in memory with "100EUR" in it, and both receipt1 and receipt2 are looking at it. If something came along and modified one of them
receipt1 = "200EUR";
The other would be unaffected.
System.out.println(receipt1);
System.out.println(receipt2);
// output would be
200EUR
100EUR
In a lot of cases once something has been assigned to a reference via the = symbol, you can imagine that the reference is always going to have access to it, unchanged until the next time the = symbol is used to assign the reference to point to something else. However, in Java objects can change state, so if you had
List<String> myList = new ArrayList<String>():
and things started calling methods on myList to modify its contents, then the myList reference would feel like it's referring to something that changes. The reference itself is not changing, just the object it points to.
I brought the subject round to lists since you probably are trying to keep track of all receipts somewhere after creating them, and the list has an add function that will do that nicely for you.
If you want to print out the whole contents of the list, then you could have a loop:
for(String line:myList) {
System.out.println(line);
}
You can use a StringBuilder to append the new Strings. Alternatively, you can simply concatenate tow Strings with the +-Operator, but this is really inefficient in terms of execution time.
First you can declare an ArrayList of Strings:
ArrayList<String> receipts = new ArrayList<>();
Then add the value of the receipt variable:
receipts.add(receipt);
At the end you can print all elements of ArrayList
for (String s : receipts)
System.out.println(s);
I would use a StringBuilder, and keep on adding what you want in the loop, adding a newline to it at the end of the loop:
public static void main(String[] args)
{
StringBuilder receipt;
//Other variable initializations
Also, your while loop could probably be changed to a for loop:
for (int i = 0; i < ticketTotal; i++)
{
receipt.append(zoneAmount);
receipt.append(" zone(s), ");
receipt.append(fareType);
receipt.append(", bought at: ");
receipt.append(purchaseLoc);
receipt.append(". Your price: ");
receipt.append(price);
receipt.append(" SEK.\n");
}
Then when you need to just print your StringBuilder:
System.out.println(receipt.toString());

String cannot be converted to double error java [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
My code is suppose to read up to 100 string and store the values in an array.
When an empty string is entered it stops reading information from a user.
Then it validates the strings, converts to double numbers and is stored into a separate array.
Then the average of all valid numbers is found.
The only things that are printed are:
1) the number of valid strings entered
2) all valid strings in reverse order they were inputed
and
3) the average of all valid inputs.
I think I have it okay, except when converting the strings into double numbers. I placed that into a try/catch along with everything else after that because otherwise it can't find the valid inputs.
I am getting an error:(48: error: incompatible types: String cannot be converted to double).
I have tried adding an else to my if statement but it doesn't connect the if and else statements. Though when I add the else statement the error goes away and it just tells me the only error is that it cannot find the if for the else.
What can I do?
EDIT: Thank you, it works now. But I don't think I am finding the average correctly. Any suggestions?
import java.util.*;
public class Grades{
public static void main(String args[]){
int arraycount = 0;
final int SIZE = 10;
int validArraycount = 0;
final int ValidArraySize = 10;
int valuesinValidArray = 0;
Scanner reader = new Scanner(System.in);
String initialInput = new String ("");
String [] sArray = new String[SIZE];
double [] ValidArray = new double[ValidArraySize];
double sum = 0;
boolean exit = false;
System.out.println("You may enter up to 100 grades.");
System.out.println("When you are done entering grades, press the enter/return key.");
//Prints to user. Stops if nothing is entered.
while((arraycount < SIZE)&&(exit == false)){
System.out.println("Enter line " + (arraycount+1) + ": ");
initialInput = reader.nextLine();
if (initialInput.length()<1){
exit = true;
}
else{
sArray[arraycount]=initialInput;
arraycount++;
}
}
//convert string to double
try{
double convertedInput = Double.parseDouble(initialInput);
//validate strings entered by user
if(convertedInput >= 0 && convertedInput <=100){
ValidArray[validArraycount] = initialInput;
}
//Prints number of valid values entered
if(ValidArray.length>0){
System.out.println("The number of valid grades entered is " + ValidArray[0]);
}
//for printing array backwards
for (int i = (arraycount-1); i>=0; i--){
System.out.print(ValidArray.length);
}
//calculates sum of all values in array of ValidArray (of grades)
for(double d : ValidArray){
sum += sum;
}
//avergae of valid number array
double average = (sum/ValidArray.length);
System.out.println("Average: " + average);
}
catch(NumberFormatException e){
}
}
}
ValidArray[validArraycount] = initialInput;
is probably supposed to be
ValidArray[validArraycount] = convertedInput;
At this line:
ValidArray[validArraycount] = initialInput;
You are trying to assign a String to an array of doubles. This is where the error is coming. You can try calling double.parseDouble(initialInput) on this if you are sure it will be a double in String form.
It looks like you're assigning the wrong value to your array. Replace:
ValidArray[validArraycount] = initialInput;
With:
ValidArray[validArraycount] = convertedInput;
As previously mentioned, to fix your String conversion issue, you're assignment line should be:
ValidArray[validArraycount] = convertedInput;
To fix your average problem, your code should look like this:
//calculates sum of all values in array of ValidArray (of grades)
for(double d : ValidArray){
sum += d; // <-------- changed from sum += sum;
}
//avergae of valid number array
double average = (sum/ValidArray.length);

Categories

Resources