Calculating Score [Java procedural] [closed] - java

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 8 years ago.
Improve this question
My program keeps adding up the score for each player, rather than keeping it seperate 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.
Upfront thanks!
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);

Reset the score variable within your loop and then place it in the corresponding element of playerscore. Here's the code:
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!");
score = 0; //reset the score variable
/* --------------------------- 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;
System.out.println("\nPlayer"+(i)+ "Name:"+name[i]+"\tScore"+score);
}
else{
JOptionPane.showMessageDialog(null,"Wrong!");
}
} // End for loop for Question
playerscore[i] = score; //assign the score for each player
}
Then whenever you want the score for name[i] you can just print playerscore[i]

Related

How do I stop this array from only printing/remembering the latest thing put into the array?

I don't know if the array itself is broken or if the code to print the array is broken
/*This is the main class that prints out everything */.
//Start the problems loop
for (int i = 0; i < session.getNumProb(); i++) {
//Set random values for factors
cards.setFactors();
//Create problems
cards.setProb(session);
//Determine correct/incorrect answer, update running score
cards.setResponse(session);
//Add the problem to the history array
session.setHistory(cards);
}
//Set score percentage
session.setScorePct();
//Print out summary
session.prtSummary();
//Print out history array and outro
session.prtHistoryAndOutro();
______________________________________________________________________________
/* This sets the history based on questions asked */
//setHistory
public void setHistory(Cards c) {
for (int i = 0; i < numProb; i++) {
history[i] = c.getA() + oper + c.getB() + " = " + c.getResponse() + ", " + c.getCorInc() + ", correct answer is " + c.getC();
System.out.println();
}
}
____________________________________________________________________________
/* This prints out the history array */
//prtHistoryAndOutro
public void prtHistoryAndOutro() {
System.out.println("Problems");
for (int i = 0; i < numProb; i++) {
System.out.println(history[i]);
}
System.out.println();
System.out.println();
System.out.println("Thank you for using the 3312 FlashCard System, " + name + ".");
System.out.println("Come back and play again real soon!");
}
I don't know where something is going wrong but it should be within these three pieces of code. Also the bottom two pieces are within the same class

I'm trying to add 25 every-time a user inputs "Yes" and then print the results but it keeps missing the first response when adding them up

I'm trying to add 25 every-time a user inputs "Yes" and then print the results but it keeps missing the first response when adding them up. So if I type "Yes" for dairy I'm only getting 75%? It's a work in progress for larger piece of code but basically at the moment if you type "Yes" for dairy then it should add them all up and equal a 100.
Tried so many different options and have gotten no where
import java.util.Arrays;
import java.util.Scanner;
public class question4 {
public static void main(String[] args) {
Scanner userTypes = new Scanner(System.in); //new object for user input
String[] respondents = {"Cormac", "Orla", "Paul", "Sarah"};
String[] questions = {"Are you allergic to Dairy?", "Are you allergic to nuts?", "Are you gluten intolerent?"};
String[] decisions = new String [4];
int dairy= 0;
int nuts= 0;
int gluten=0;
for (int i=0; i<= respondents.length -1 ;i++) {
System.out.println(respondents[i]);
for (int j=0; j<= questions.length -1; j++) {
System.out.println(questions[j]);
decisions[j]=userTypes.nextLine();
}
System.out.println(Arrays.toString(decisions));
}
System.out.println("Allergy Results");
for (int k=0; k <= respondents.length - 1; k++ ){
if (decisions[k].equals("Yes")) {
dairy= dairy + 25;
}
}
System.out.println("Dairy Allergy Results = " + dairy + "%");
}
}
The problem here is that for every respondent, you are recording their answers in decisions[j] where j is the question number; but then later you are counting the number of "Yes" responses by iterating over decisions[k] where k is the respondent number.
Either decisions[i] means some respondent's answer to question i, or it means the ith respondent's answer to question 1. It cannot mean both. You need to reconsider how you are storing this data.
Furthermore, since decisions[j] is being written for each j for each respondent, the array is overwritten each time, meaning you only end up storing the results for the last respondent.
A two-dimensional array may be a good solution, where decisions[i][j] means the ith respondent's answer to question j.
First of all, lets format the code. For storing the decision of 4 different users for 3 three different questions, you need your array (data structure) to be like that. Also, looks like you are only interested (for now) in the decision about the dairy question. So, just check for that in your calculation. I have updated the code and added the comments. Need to update the part where you are storing the results and how you are calculating the total for dairy.
import java.util.Arrays;
import java.util.Scanner;
public class Question {
public static void main(String[] args) {
Scanner userTypes = new Scanner(System.in); //new object for user input
String[] respondents = {"Cormac", "Orla", "Paul", "Sarah"};
String[] questions = {"Are you allergic to Dairy?", "Are you allergic to nuts?", "Are you gluten intolerent?"};
String[][] decisions = new String [4][3];//You have 4 respondents and You have 3 questions
int dairy= 0;
int nuts= 0;
int gluten=0;
for (int i=0; i<= respondents.length -1 ;i++) {
System.out.println(respondents[i]);
for (int j=0; j<= questions.length -1; j++) {
System.out.println(questions[j]);
decisions[i][j]=userTypes.nextLine();
}
System.out.println("Decisions :: "+Arrays.toString(decisions[i]));//Need to print the result per user
}
System.out.println("Allergy Results");//If you are only interested in dairy decision for the 4 user
for (int k=0; k <= respondents.length - 1; k++ ){
if (decisions[k][0].equals("Yes")) {//for all user check the first decision (as your first question is about dairy)
dairy= dairy + 25;
}
}
System.out.println("Dairy Allergy Results = " + dairy + "%");
userTypes.close();
}
}
Ok so my really basic solution in the end was the below, not ideal but hey I'm a beginner:)
public class question4 {
static void allergyTest() { //method for the allergy test
Scanner userTypes = new Scanner(System.in); //new object for user input
String[] respondents = {"Cormac", "Orla", "Paul", "Sarah"};//string array that contains the name of the people being surveyed
String[] questions = {"Are you allergic to Dairy?", "Are you allergic to nuts?", "Are you gluten intolerent?"};// string array to store the questions
String[] decisions = new String [3];//string array to store the responses to the questions
int dairy= 0; //int to store dairy percentage
int nuts= 0;// int to store nuts percentage
int gluten=0; //int to store gluten percentage
for (int i=0; i<= respondents.length -1 ;i++) { // for loop to go through each respondent
System.out.println(respondents[i]); //print their name
for (int j=0; j<= questions.length -1; j++) { //then a for loop to loop through the questions for each respondent
System.out.println(questions[j]); //print the actual question
decisions[j]=userTypes.nextLine(); //take the users input
while(!decisions[j].equals("yes")&& !decisions[j].equals("no")) { //check if the users input is valid, as in yes or no
System.out.println("please type yes or no as your answer"); //if not tell them to type it correctly
decisions[j]=userTypes.nextLine(); //store the yes or no once correctly typed
}
}
if (decisions[0].equals("yes")) { //add up the yes
dairy = dairy +25; //lazy way of getting a percentage because I know the amount of respondents & answers
}
if (decisions[1].equals("yes")) {
nuts = nuts +25;
}
if (decisions[2].equals("yes")) {
gluten = gluten +25;
}
}
System.out.println("Allergy Results");// print the results below
System.out.println("Percentage of people allergic to dairy= "+ dairy +"%");
System.out.println("Percentage of people allergic to nuts= "+ nuts +"%");
System.out.println("People who think they are allergic to gluten= "+ gluten +"%");
}
public static void main(String[] args) { //call the allergy test
allergyTest();
}
}

How input get stored when we repeatly asking in for loop [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 7 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Improve this question
public class Exercise_09 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of student: ");
int studentCount = input.nextInt();
input.nextLine();
String topSName = null;
double topSScore = 0;
String secondSName = null;
double secondSScore = 0;
for (int i = 0; i < studentCount; i++) {
System.out.print("Enter name for student #" + (i + 1) + ": ");
String s = input.next();
System.out.print("Enter score for student #" + (i + 1) + ": ");
double score = input.nextDouble();
if (score > topSScore) {
if (topSName != null) {
secondSName = topSName;
secondSScore = topSScore;
}
topSName = s;
topSScore = score;
} else if (score > secondSScore) {
secondSName = s;
secondSScore = score;
}
}
System.out.println("Top student " + topSName + "'s score is " + topSScore);
System.out.println("Second top student " + secondSName + "'s score is " + secondSScore);
}
}
Ok I got this code what it does is it ask for number of students, their names and score and displays the highest and 2nd highest score.
Now my question is that when I am repeating asking for name of the student and score how input keep the record of all the scores and names and how do i call it ? WHat the hell that if statement logic doing? i dont get that part.
You can use arraylist to store name and score.
After storing data into arraylist you can display data from arraylist.
Here http://www.careerbless.com/samplecodes/java/beginners/collections_ds/inertandretrieveArrayList.php you can get example how to insert and retrieve value from arraylist.
Here's what your if statements are doing in for loop.
But before First Initialize variable : topScore = 0; secondSScore= 0;(lowest).(My suggestion: Initialized it to -1).
Inside Loop: (Now here your logic is divided into two main parts)
FIRST ITERATION
Get the Students score.
if score is greater than topScore then assign topScore the value of score.
(Now here in First iteration the score of first student is set as the topScore and also the second topScore (secondSScore)).
Why ?... Because the value of topScore is initialized to 0 which is less than first student's score(only if first student has not scored zero). This tells us until now according to received data this is the top Score as well as the second topScore.(Pretty logical ..)
// First iteration
if (score > topSScore) { // topSScore = 0
topSName = s;
topSScore = score;
} else if (score > secondSScore) { //secondSScore = 0
secondSName = s;
secondSScore = score;
}
REST OF ITERATION
Now in further iteration if any student's score is greater than new topScore then
FIRST assign secondSScore the value of topSScore
if (topSName != null) {
secondSName = topSName;
secondSScore = topSScore;
}
and then assign the topSSCore the value of student's score and so on....phew
Hope I explained well.
Its like find largest and second largest from given data (commonly an array).
Here's some similar example:
Finding-the-second-highest-number-in-array
Find two-max-numbers-in-array
You would want to use an object that implements Map<T>, an interface in java that supports key with value, or you can simply use the interface Map<T> itself. You have a student and a score associated with the student, therefore you need a key and value.
https://docs.oracle.com/javase/tutorial/collections/interfaces/map.html
Store a key and value:
Map.put(key, value);
Get a value from a key:
Map.get(key);

Java, comparing value of two string arrays [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 7 years ago.
Improve this question
I am trying to complete an assignment for school and I'm having issues seeing if each element in two String arrays are equal. I have looked everywhere and it seems like I'm already doing it correctly but it is not.
Real quick, the assignment is user enters in the quiz number and the solutions to a T/F quiz (2 T T T F F...) and then enters in info for a student, a first, last name, student ID and their answers to that quiz.
If I enter in 1 T T T F F T T for the answer key and T T T F F F F for the students answers it counts them all as equal and I can't figure out why. I will post all my code but add stars around the appropriate for loop where I think the problem is... Thank you for any help, this is driving me crazy!
public class CST200_Lab4 {
public static void main(String[] args) throws IOException {
String inputValue = " ";
String answerKey [];
String firstName = " ";
String lastName = " ";
String IDnumber = " ";
int studentResults = 0;
int numStudents = 0;
double averageScore = 0;
InputStreamReader ISR = new InputStreamReader(System.in);
BufferedReader BR = new BufferedReader(ISR);
//Read in the Answer Key to the Quiz w/ quiz number at index 0.
String answers = BR.readLine();
answerKey = answers.split(" ");
/*Read in Students info and students quiz results.
*Set size of student array to length of the answer key */
String studentArr[] = new String [answerKey.length + 4];
inputValue = BR.readLine();
studentArr = inputValue.split("\\s+");
//Enter students info until 'zzzz' is entered.
while(!(inputValue.equalsIgnoreCase("ZZZZ"))) {
//Keep track of student(s) entered to calculate average scores.
numStudents++;
//quizResults = inputValue.replaceAll("^(\\S*\\s){4}", "");
//quizResultsArr = quizResults.split("\\s+");
//Set students info to first three indexes of studentArr.
lastName = studentArr[0];
firstName = studentArr[1];
IDnumber = studentArr[2];
/*Loop through answerKey and compare w/ student quiz results
*to determine how many questions the student got correct*/
//I THINK THE ISSUE IS IN HERE BUT I CAN'T FIGURE OUT WHY
******************************************************************************
for(int i = 1; i < studentArr.length - 2; i++) {
//ALL 'ANSWERS' ARE BEING COUNTED AS EQUAL
if((studentArr[i + 2]).equalsIgnoreCase(answerKey[i])); {
studentResults++;
averageScore++;
}
}
******************************************************************************
//Print out Students info and results.
lastName.replace(",", " ");
System.out.print(IDnumber + " ");
System.out.print(firstName);
System.out.print(lastName + " ");
System.out.println(studentResults);
System.out.println(averageScore);
//Enter a new students info or 'zzzz' to end
studentResults = 0;
inputValue = BR.readLine();
studentArr = inputValue.split("\\s+");
}
/*If no more students are being entered,
*calculate average score of test results.*/
System.out.println(numStudents);
System.out.println(averageScore);
if(inputValue.equalsIgnoreCase("ZZZZ")) {
averageScore = averageScore / numStudents;
System.out.println("The average score is " + averageScore );
}
}
}
if((studentArr[i + 2]).equalsIgnoreCase(answerKey[i]));
Should not end a conditional if statement with ;

Arrays counting

If my program gives the user about a team's championship history, for example, if the user enters Chelsea, my program will say, "They have won it in 2012,2010,2007,2008" (using parallel array list already provided and has to be used).
How would i display, from that result, the number of times they have won . So if that information is correct, i want my program to say, "Chelsea has won it 4 times".
This is what i have so far:
public static void showWinner(short years[], String winners[]){
Scanner kd = new Scanner (System.in);
String name;
System.out.println("Which teams result would you like to see?: " );
name = kd.next();
for (int i = 0; i < winners.length; i++) {
if (winners[i].equals(name)){
System.out.println(years[i]);
}
}
Try this: I am assuming that winners array and years array has mapping in which year which team won. I suggest you to use Map for this purpose. It will be more understandable and efficient.
int count = 0;
for (int i = 0; i < winners.length; i++){
if (winners[i].equals(name)){
count ++;
System.out.println(years[i]);
}
}
System.out.println(name + " has won it" + count + "times");

Categories

Resources