Creating a loop to check array (java) - 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.

Related

What loop should I use? [duplicate]

This question already has answers here:
when to use while loop rather than for loop
(14 answers)
Closed 1 year ago.
I am supposed to do a word-quiz game between two languages in Java, and I am not sure what type of loop should be used when controlling the input from the user! I have three "conditions/terms"
if the user types the right answer
if the user has some spelling mistake
if the user types q to quit the game
I was first thinking of using a for loop, but I don't seem to figure it out!
My code looks like this right now
public static int takeTest(ArrayList<Sweng> Wordlist) {
int result = 0;
Scanner keyboardInput = new Scanner(System.in);
for (int i = 0; i < Wordlist.size(); i++) {
System.out.println(Wordlist.get(i).getSweWord());
String answer = keyboardInput.nextLine();
}
//...
}
If you don't know how many times the loop need to be executed, you can use a do-while loop.
This loop first execute the code inside the do brackets, and then check the condition.
This is an implementation example:
Scanner s = new Scanner(System.in);
String input; // a variable to store the input
do {
System.out.println(/*your question here*/);
input = s.nextLine();
// do something
} while(!input.equals("q")); // exit the loop if 'input' equals "q"
Otherwise, you can do something like that, but it's a very bad and rough way to do this. I don't recommend you to use it.
Note: You'll need to adjust this code with your ArrayList<Sweng> WordList. It's just an example!
ArrayList<String> questions = new ArrayList<String>();
ArrayList<ArrayList<String>> possibleAnswers = new ArrayList<ArrayList<String>>(); // list of a list because we need a set of strings for every questions
ArrayList<String> correctAnswers = new ArrayList<String>();
// init the lists
Scanner s = new Scanner(System.in);
int result = 0;
boolean quit = false; // if true, then quit the for loop
for(int i = 0; i < questions.size(); i++) { // repeat 'questions.size()' times
String answer = null;
do {
if(answer != null) System.out.println("This isn't a valid answer!"); // if 'answer' is null, don't show this output because it's the first time in the loop
System.out.println(questions.get(i));
answer = s.nextLine();
if(answer.equals("q")) { // if input is "q", set 'quit' to 'true' and break the do-while loop
quit = true;
break;
}
} while(!possibleAnswers.get(i).contains(answer)); // if the answer is a valid answer, quit the loop
if(quit) break; // if quit is true, break the for loop
if(answer.equals(correctAnswers.get(i))) { // check for correct answer
System.out.println("Correct!");
result++;
} else System.out.println("Wrong!");
}
System.out.println("You scored " + result + "!");
Since you actually know how often you want to loop at max (max. the amount of questions inside your wordList, since it's a quiz), you can actually keep the for loop.
You could use a while or do-while loop here, but then you would need a seperate index variable to keep track of the current question, and this fact alone indicates that a for loop is more suitable here.
I modified your code snippet to change / add the following things:
Variable names should start lowercase. So Wordlist -> wordList.
Added conditions regarding verification of the answer and quitting.
Added some print statements.
Example:
public static int takeTest(ArrayList<Sweng> wordList) {
int result = 0;
Scanner keyboardInput = new Scanner(System.in);
for (int i = 0; i < wordList.size(); i++) {
System.out.println(wordList.get(i).getSweWord());
System.out.println("Please enter the answer:");
String answer = keyboardInput.nextLine();
if (wordList.get(i).getResultWord().equals(answer)) { // correct answer
System.out.println("Correct answer!");
result++;
} else if ("q".equals(answer)) { // quitting
System.out.println("Thank you for playing!");
break;
} else { // incorrect answer
System.out.println("Incorrect answer!");
}
}
return result;
}
Sidenote: Since I don't know the structure of your Sweng class, I called the method to retrieve the result word getResultWord().

JAVA: if statement inside a for loop and exiting from a for loop

Good day guys, I am new in this. I am doing an assignment for my prog unit, so please bear with me.
So what I have to do is to write up a code that can input people's ages, from integers between 1 to 120 inclusive. The user then have to calculate the average age, and should be calculated as a real number. But the user has to input age values until the user enters 0, which is to stop the program then output the average. If the user enters an age that is invalid, then the program should continue to re-prompt the user until they enter a valid age.
So I did my part. I created a code and I come up with this:
public static void main(String[] args)
{
int ageValue = 0;
double getAge;
getAge = inputAge();
System.out.println("Average age is: " + getAge);
}
public static double inputAge()
{
int ageValue = 0;
double avgAge = 0;
Scanner sc = new Scanner(System.in);
for (int i = 1; i <= 120; i++)
{
System.out.println("Enter age");
ageValue += sc.nextInt();
avgAge = ageValue / (double) i;
if (ageValue == 0)
{
System.out.println("Average age is: " + avgAge);
System.exit(0);
}
while (ageValue < 0 || ageValue > 120)
{
System.out.println("Invalid input. Try again!");
ageValue = sc.nextInt();
}
}
return avgAge;
}
Now I laid down my code and I got my average formula somehow working. Now, the problem is that when I press 0, it doesn't prompt the "if" statement. However, when the first "Enter your age" prompt comes up and I pressed 0, the "if" statement worked. But for each iteration, the program won't let me execute the statement.
On the other hand, I am also struggling to figure out how to exit a loop without using break or System.exit() because that will give me zero marks. What I wanted is when I press 0, it should exit the loop and output the average, like what the task said.
I don't know if you guys can get it.. Is the code right? Am I on the right track? Am I missing something???
Cheers
You could consider a do while loop approach. This would allow your code to naturally run once, and exit once the user enters 0:
int ageValue = 0, numOfAges = 0, sumOfAges = 0;
do {
System.out.println("Enter age");
ageValue = sc.nextInt();
if (ageValue < 0 || ageValue > 120)
System.out.println("Bad value... try again");
else if (ageValue != 0) {
sumOfAges += ageValue;
numOfAges++;
}
} while (ageValue != 0);
return ((double)sumOfAges / numOfAges);
On the other hand, I am also struggling to figure out how to exit a loop without using break or System.exit() because that will give me zero marks.
You can have another condition in your for loop like this
boolean finished = false;
for (int i = 1; i <= 120 && finished == false; i++)
and replace
System.exit(0)
with
finished = true;
However, I would question why using "break" will score you zero marks. This is exactly the sort of scenario break was intended for.
you can try this approach.
i've corrected a bit the exit condition and the way averaging is done.
the "for" loop you show in your code is limiting the number of sample to 120, but the question don't say so, so i took the liberty to generalise you question to any number of sample to average.
first thing is you should look up "if-else" conditionnal structure, as that was the main point missing in your code.
https://en.wikipedia.org/wiki/Conditional_(computer_programming)
you can think the way the problem is expressed as :
calculate the average in a serie
the serie is keyboard inputted
when zero is inputted, exit the loop and return the current average
when any value out of bound [0,120] is inputted, give a message and continue the loop without changing anything to the serie
when any value inside the bound [1,119] is inputted add the value to the serie and recalculate the average
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Test
{
public static void main(String[] args)
{
System.out.println("Final Average age is: "+inputAge());
}
private static double inputAge()
{
int ageValue=0;
double avgAge=0;
boolean shouldExit=false;
Scanner sc=new Scanner(System.in);
List<Integer> samples=new ArrayList<Integer>();
// loop until flag is true
while(!shouldExit)
{
System.out.println("Enter age");
ageValue=sc.nextInt();
if(ageValue==0)
{
shouldExit=true;
}
else if(ageValue<0||ageValue>120)
{
System.out.println("Invalid input. Try again!");
}
else
{
// add current input in the samples and calculate average over all the samples
samples.add(ageValue);
avgAge=getAvg(samples);
System.out.println("Current Average age is: "+avgAge);
}
}
sc.close();
return avgAge;
}
private static double getAvg(List<Integer> samples)
{
double avgAge=0;
for(Integer tmp:samples)
{
avgAge+=tmp;
}
return avgAge/(double) samples.size();
}
}

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

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++;
}

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());

Using a single-dimensional array, ask the user for input and display only NON-duplicate values

in my java class we were learning about arrays and this question came up. I have tried to solve it and can't seem to fulfill the requirements. I can read in the user inputs and have it limited to only 5 elements (one of the other requirements), also the values have to be between 10 and 100 I have also done that. But I cannot seem to "not print" the duplicate values. The array accepts the duplicate values. They don't have to be taken out, just not printed. Here is my code so far:
import java.util.Arrays;
import java.util.Scanner;
public class ArrayTest {
static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
int size = 5;
int InpNum[] = new int[size];
for (int i = 0; i < InpNum.length; i++){
while (InpNum[i] <= i){
System.out.println("Please type a number between 10 and 100: ");
InpNum[i] = in.nextInt();
while (InpNum[i] < 10 || InpNum[i] > 100){
System.out.println("Error: Please type an integer between 10 and 100: ");
InpNum[i] = in.nextInt();
}
Arrays.sort(InpNum);
System.out.println(Arrays.toString(InpNum));
}
while (Search(InpNum, i) == true){
System.out.println("ERROR: Please enter a number that is not a duplicate of the other numbers you have entered");
InpNum[i] = in.nextInt();
}
}
}
// I can't seem to implement the method below in a useful manner.
public static boolean Search(int InpNum[], int searchedNum) {
for(int i : InpNum) {
if (i == searchedNum) {
return true;
}
}
return false;
}
}
I would consider restructuring your application.
Instead of placing the number the user inputs into the array immediately, store it in a local variable. Then run all the checks you need to run, and add it to the array only if it passes all of them.
You should only have one while loop in the whole program (the outer one). All those others are greatly confusing the issue and making the problem much harder than it has to be.
So, in psudo-code:
int index = 0;
while (true)
{
int num = in.nextInt();
// if not between 10 and 100, continue
// if it would make the array larger than 5, continue
// (or perhaps break out of the loop, since we've filled the array)
// if it is already in the array, continue
// all the checks passed, so add it to the array!
InpNum[index++] = num;
}
As a side note, what you really need is a Set. This is a collection which is guaranteed to have no duplicates and allows you to answer the question "do I contain this value?" in an efficient manner using the method Set.contains( Object ).
So I would create a TreeSet or HashSet and put every number the user types into it. Your Search function would then simply be a one liner calling contains( searchedNum ) on your set.
A lazy way is to just create a second array that can hold the values as you go.
Loop through the input array and put the current element into the new array IF that array doesn't have that element already.
Then replace the old array with the weened out one.
Easiest way
So what I do is first ask the number. Then save the number in a variable before entering it inside the array. Then I check if that number is already in it wih search. If it is I ask for a new number. If it is not I check if it is between 10 and 100, if it is not I ask for a new. I fit is I enter It inside the array. I have to check where an empty place is because the sort mixes up the array everytime
import java.util.Arrays;
import java.util.Scanner;
public class ArrayTest
{
static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
int size = 5;
int InpNum[] = new int[size];
for (int i = 0; i < InpNum.length; i++){
System.out.println("Please type a number between 10 and 100: ");
int number = in.nextInt();
//while (InpNum[i] <= i){
while (Search(InpNum, number) == true){
System.out.println("ERROR: Please enter a number that is not a duplicate of the other numbers you have entered");
number = in.nextInt();
}
while (number < 10 || number > 100){
System.out.println("Error: Please type an integer between 10 and 100: ");
number = in.nextInt();
}
int counter = 0;
for (int j = 0; j < InpNum.length && counter == 0; j++){
if(InpNum[j] == 0){
InpNum[j] = number;
counter++;
}
}
Arrays.sort(InpNum);
System.out.println(Arrays.toString(InpNum));
//}
}
}
// I can't seem to implement the method below in a useful manner.
public static boolean Search(int InpNum[], int searchedNum) {
for (int i = 0; i < InpNum.length; i++){
if (InpNum[i] == searchedNum) {
return true;
}
}
return false;
}
}

Categories

Resources