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");
Related
this is my first question in this community as you can see I'm a beginner and I have very little knowledge about java and coding in general. however, in my beginner practices, I came up with a little project challenge for myself. as you can see in the figure, the loop starts and it prints out the number that is given to it through the scanner. the problem with my attempt to this code is that it gives me the output value as soon as I press enter. what I want to do is an alternative of this code but I want the output values to be given after the whole loop is done all together.
figure
So, basically what I want is to make the program give me the input values together after the loop ends, instead of giving them separately after each number is put.
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
calc(); }
public static int calc (){
Scanner scan = new Scanner(System.in);
int count = 1;
int pass = 0;
int notpass = 0;
System.out.println("how many subjects do you have? ");
boolean check = scan.hasNextInt();
int maxless = scan.nextInt();
if (check){
while(count <= maxless ){
System.out.println("Enter grade number " + count);
int number = scan.nextInt();
System.out.println("grade number" + count + " is " + number);
if (number >= 50){
pass++;
}else{
notpass++;
}
count++;
}
System.out.println("number of passed subjects = " + pass);
System.out.println("number of failed subjects = " + notpass);
}else{
System.out.println("invalid value!");
} return pass;
}
}
I think what you want to do is create an array of int numbers.
It would be something like this:
import java.util.Scanner;
public class Application {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int maxless = 5;
int[] numbers = new int[maxless];
int count = 0, pass = 0, notPass = 0;
while(count < maxless){
System.out.println("Enter grade number " + (count + 1) + ":");
numbers[count] = scan.nextInt();
if(numbers[count] >= 50){
pass++;
}
else{
notPass++;
}
count++;
}
for(int i=0; i<maxless; i++){
System.out.println("Grade number " + (i + 1) + " is " + numbers[i]);
}
}
}
The output is the following:
Enter grade number 1:
90
Enter grade number 2:
76
Enter grade number 3:
54
Enter grade number 4:
67
Enter grade number 5:
43
Grade number 1 is 90
Grade number 2 is 76
Grade number 3 is 54
Grade number 4 is 67
Grade number 5 is 43
When dealing with arrays, just remember that the indexation begins at 0. You can read more about arrays here: http://www.dmc.fmph.uniba.sk/public_html/doc/Java/ch5.htm#:~:text=An%20array%20is%20a%20collection,types%20in%20a%20single%20array.
A tip: it's gonna be easier to help if you post the code on your question as a text, not an image, so we can copy it and try it on.
Approach 1 :
You can use ArrayList from Collection Classes and store the result there and after the loop is completed, just print the array in a loop.
Example :
//Import class
import java.util.ArrayList;
//Instantiate object
ArrayList<String> output = new ArayList();
while(condition){
output.add("Your data");
}
for(i = 0; i < condition; i++){
System.out.println(output.get(i));
}
Approach 2 :
Use StringBuilder class and append the output to the string, after the loop is completed, print the string from stringbuilder object.
Example :
//import classes
import java.util.*;
//instantiate object
StringBuilder string = new StringBuilder();
while(condition){
string.append("Your string/n");
}
System.out.print(string.toString());
Approach 3 : (As mentioned by Sarah)
Use arrays to store the result percentage or whatever and format it later in a loop. (Not a feasible approach if you want to store multiple values for the same student)
Example :
int studentMarks[] = new int[array_size];
int i = 0;
while(condition){
studentMarks[i++] = marks;
}
for(int j = 0; j < i; j++)
System.out.println("Marks : " + studentMarks[j]);
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();
}
}
I'm trying to set up a program where the user(student) inputs how many courses they have left to graduate and and how many classes the intend to take per terms and the program will form this data into an array and print out how many terms they have left. The user is not allowed to take more than 5 courses per term so I want to prompt the user that the number they input is incorrect while also looping that input for that specific student without have to close the console and re-run the program. I've tried placing a while(true){} loop there in order to loop it but i can't seem to get the loop i desire.
I've tried placing the while(true){} loop in multiple spots of the code and can't get the desired result.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[][] students = new int[10][2];
for (int i = 0; i < students.length; i++) {
System.out.println("Enter classes remaining and taking each term for student " + (i + 1) + ": ");
for (int j = 0; j < students[i].length; j++) {
students[i][j] = input.nextInt();
if (students[i][1] > 5)
System.out.println("The number of classes per term for student " + (i + 1) + " is invalid.");
}
}
System.out.println();
for (int i = 0; i < students.length; i++) {
System.out.println("Student " + (i + 1) + " has " + (int) Math.round(students[i][0] / students[i][1]) + " terms left to graduate.");
}
}
I expect the output for the first input to print","The number of class per term for student n is invalid." and repeat the prompt to enter the numbers for that same student n without proceeding to the next student input.
Here is the updated one based on your new comments. You should be good from here, make changes whatever you need.
public class StudentInfo
{
public static int totalStudents = 6;
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int[][] Students = new int[totalStudents][3];
// Student[i][0] will hold the Remaining classes.
// Student[i][1] will hold the Classes per semester and
// Student[i][2] will hold the number of total Semesters to complete all courses.
for (int i = 0; i < totalStudents; i++)
{
System.out.print("\n\nEnter the information for " + (i + 1) + "-th student.");
System.out.print("\n\nEnter the total number of remaining courses: ");
Students[i][0] = input.nextInt();
System.out.print("\nEnter the total number of courses per semester: ");
Students[i][1] = input.nextInt();
while (Students[i][1] > 5)
{
System.out.println("\nStudents are not allowed to take more than 5 classes per semester.");
System.out.print("Enter the total number of courses per semester: ");
Students[i][1] = input.nextInt();
}
int ts = Students[i][0] / Students[i][1];
if (Students[i][0] % Students[i][1] != 0)
ts++;
Students[i][2] = ts;
System.out.println("\nThis student needs a total of " + ts + " semesters to finish all courses.");
}
input.close();
}
}
public static void main(String[] args) {
//scanner library
Scanner input = new Scanner (System.in);
//Initialize array
int[][] students = new int [10][2];
//iterate scanner and condition loop
for(int i=0; i<students.length; i++){
System.out.print("Enter classes remaining and taking each term for student "+ (i+1) +": ");
for (int j=0; j<students[i].length;j++){
students[i][j]= input.nextInt();
}
while(students [i][1] > 5) {
System.out.println("The number of classes per term for student " + (i+1) + " is invalid.");
i--;
break;
}
}
System.out.println();
//Print out results compiled from array
for(int i =0; i<students.length; i++) {
System.out.println("Student "+(i+1)+" has "+ (int) Math.ceil((double)students[i][0]/students[i][1]) + " terms left to graduate.");
}
}
import java.util.*;
public class Project5{
static Scanner console = new Scanner(System.in);
static final int ARRAY_SIZE = 5;
public static void main(String[] args){
Candidate[] candidateList = new Candidate[ARRAY_SIZE];
String name;
int votes;
int i = 0;
for (i = 0; i < ARRAY_SIZE; i++){
System.out.print("Enter Candidate #" + (i + 1) + " Name: ");
name = console.nextLine();
System.out.print("Please Enter the number of votes " + name + " Received: ");
votes = console.nextInt();
candidateList[i] = new Candidate(name, votes);
console.nextLine();
}
Candidate winner;
winner = candidateList[0];
This is where i have my issue, i have the for loop counting each of the five Strings i the Array but it doesn't seem to pick the String which has the most votes to be the winner. I feel like this is rather simple and it is simply flying over my head.
Also is what is the quickest way to simplify this part here?
System.out.print(" Candidate Votes Recieved % of Total Votes");
System.out.print("\n");
System.out.print("\n");
One more thing, is there a way to simply have a code like this but in one format? So like {System.out.print(candidateList[i].getCandidateInfo());}
System.out.print(candidateList[0].getCandidateInfo());
System.out.print(candidateList[1].getCandidateInfo());
System.out.print(candidateList[2].getCandidateInfo());
System.out.print(candidateList[3].getCandidateInfo());
System.out.print(candidateList[4].getCandidateInfo());
System.out.print("The winner is: " + winner);
}
}
Like Berger said "Remove the else winner = candidateList[0];".
System.out.print(" Candidate Votes Recieved % of Total Votes\n"\n"");
No. I would override the toString() method though in you Candidate class, to confirm more to standards. Then call candidateList[0].toString().
Or you could do it in a loop:
for (i = 0; i < ARRAY_SIZE; i++){
System.out.print(candidateList[i].getCandidateInfo());
}
I would suggest implement Comparable Interface to your Candidate class and implement the
public int compareTo(Candidate candidate) {
int votes = Candidate.getCVotes();
//descending order
//return votes - this.cVotes;
}
Instead of for loop do
Arrays.sort(candidateList)
The 0th element after sorting will be the winner.
This way if tomorrow you need to know the 2nd and 3rd position holder you can simply print 1 and 2 indexed element from your candidateList.
Does anyone know how to display the average race time for participants in this simple program?
It would also be great to display the associated runners name with the time.
I think that I have the arrays structure properly and have taken in the user input.
Thanks for any assistance you can provide. Here's my code...
import java.util.Scanner;
public class RunningProg
{
public static void main (String[] args)
{
int num;
Scanner input= new Scanner (System.in);
System.out.println("Welcome to Running Statistical Analysis Application");
System.out.println("******************************************************************* \n");
System.out.println("Please input number of participants (2 to 10)");
num=input.nextInt();
// If the user enters an invalid number... display error message...
while(num<2|| num >10)
{
System.out.println("Error invalid input! Try again! \nPlease input a valid number of participants (2-10)...");
num=input.nextInt();
}
// declare arrays
double resultArray [] = new double [num]; // create result array with new operator
String nameArray [] = new String [num];// create name array with new operator
// Using the num int will ensure that the array holds the number of elements inputed by user
// loop to take in user input for both arrays (name and result)
for (int i = 0 ; i < nameArray.length ; i++)
{
System.out.println ("Please enter a race participant Name for runner " + (i+1) );
nameArray[i] = input.next();
System.out.println ("Please enter a race result (time between 0.00 and 10.00) for runner " + (i+1) );
resultArray[i] = input.nextDouble();
}
This seems like a homework problem so here is how you can solve your problems, in pseudo-code:
Total average race time for participants is calculated by summing up all the results and dividing by the amount of results:
sum = 0
for i = 0 to results.length // sum up all the results in a loop
sum = sum + results[i]
average = sum / results.length // divide the sum by the amount of results to get the average
It would be even better to perform the summation while you read user input and store the runner's names and results. The reason is that it would be more efficient (there would be no need for a second loop to perform the sum) and the code would be cleaner (there would be less of it).
Displaying runners with theirs times can be done by iterating over the two arrays that hold names and results and print values at corresponding index:
for i = 0 to results.length
print "Runner: " + names[i] + " Time: " + results[i]
This works because you have the same amount of results and names (results.length == names.length), otherwise you would end up with an ArrayIndexOutOfBounds exception.
Another way to do this is to use the object-oriented nature of Java and create an object called Runner:
class Runner {
String name;
double result;
Runner(String n, double r) {
result = r;
name = n;
}
}
Then use an array to store these runners:
Runner[] runners = new Runner[num];
for (int i = 0 ; i < num ; i++) {
System.out.println ("Please enter a race participant Name for runner " + (i+1) );
String name = input.next();
System.out.println ("Please enter a race result (time between 0.00 and 10.00) for runner " + (i+1) );
double result = input.nextDouble();
runners[i] = new Runner(name, result);
}
Then you can just iterate over the array of runners and print the names and the results... Here is pseudo-code for this:
for i = 0 to runners.length
print runners[i].name + " " + runners[i].result