I'm attempting to write a method that allows the user to input the number of players on a sports team, the number of games played, the names of the players, and the amount of points scored per player per game.
Basically, I want the following display output where all information has been provided by the user:
Player Game 1 Game 2 Game 3 Game 4
Tom
Dick
Harry
Matthew
John
... and then points scored by each player in each game.
I admit that this little project originated from a homework assignment, but I've already turned the assignment in and the assignment didn't even ask for user supplied input. I really just want to know how to do this.
Below is my code. A few problems.
I assign each player's name to an array called playerRoster. Don't all array initialize at arrayName[0]? But when I print out playerRoster[0], nothing displays. When I print out playerRoster[1], the first name I enter for the array (which should be indexed at playerRoster[0]) displays. Why?
Related to above: I am prompted to enter the number of players on roster, and say I enter the number 5. But the prompt then allows me to only enter 4 names. Why?
The display above is what I'm looking for, and I'm sure there are built in Java methods for displaying a table of values. I actually don't want that. I kind of want to go forward with loops, like I'm doing now. (I know, I know - beggars can't be choosers)
Here is my code
import java.util.*;
public class BasketballScores
{
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println ("Enter the number of players on roster: ");
int numPlayers = input.nextInt();
System.out.println();
System.out.println ("Enter the number of games played: ");
int numGames = input.nextInt();
System.out.println();
int[][] arrayScores = new int[numPlayers][numGames];
String[] playerRoster = new String[numPlayers];
System.out.println ("Enter player names: ");
for (int j = 0; j < numPlayers; j++)
{
playerRoster[j] = input.nextLine();
}
for (String element: playerRoster)
{
System.out.println (element);
}
System.out.println();
System.out.println ("Enter the points scored per player per game: ");
System.out.println();
System.out.print (playerRoster[1]);
for (int i = 0; i < numPlayers; i++)
{
for (int k = 0; k < numGames; k++)
{
arrayScores[i][k] = input.nextInt();
}
}
System.out.println();
for (int i = 0; i < numPlayers; i++)
{
System.out.println();
for (int k = 0; k < numGames; k++)
{
System.out.print (arrayScores[i][k] + ", ");
}
}
}
}
First, before you get your player names, you are still on the line with the numGames. You need to call input.nextLine() before attempting to parse your names. This should solve your first 2 questions. What happens with #nextLine is you are going to the end of the line of the current line you are on. After you get your numGames you are still on that line. Call input.nextLine() to advance to the lines with your player names.
System.out.println ("Enter the number of players on roster: ");
int numPlayers = input.nextInt();
System.out.println();
System.out.println ("Enter the number of games played: ");
int numGames = input.nextInt();
input.nextLine(); //You need this to go to the next line before attempting to get your player names.
System.out.println();
int[][] arrayScores = new int[numPlayers][numGames];
String[] playerRoster = new String[numPlayers];
System.out.println ("Enter player names: ");
for (int j = 0; j < numPlayers; j++)
{
playerRoster[j] = input.nextLine();
}
For formatting your print you can use System.out.printf. Here is a quick example for your situation that you should be able to utilize. Quick reference guide
String[] players = new String[]{"Tom", "Dick", "Harry", "Matthew", "Johh"};
System.out.printf("%-10s%6s%6s%6s%6s","Player", "Game1 ", "Game2 ", "Game3 ", "Game4 ");
System.out.println();
Random r = new Random();
for (String player : players){
System.out.printf("%-10s%3d%6d%6d%6d",player, r.nextInt(10), r.nextInt(10), r.nextInt(10), r.nextInt(10));
System.out.println();
}
Output:
Player Game1 Game2 Game3 Game4
Tom 2 9 7 3
Dick 8 1 8 4
Harry 9 2 0 2
Matthew 5 1 3 2
Johh 8 4 0 2
Once you share how you are trying to input your data, I can help a little more. Hope this helps!
Related
I have a program that is supposed to simulate a game of poker in java. I have a method class called Poker and a check class called CheckPoker which calls the methods in the method class. I haven't even been able to check if the algorithmic part works because while asking if the user would like to switch out any cards. The loop should quit after 5 cards have been entered or if the user enters "1" but in running the program, the for loop doesn't quit until 5 card values have been entered and then throws a "java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 56" error. I have tried a for loop, a while loop, a do-while loop, but none have seemed to work thus far.
import java.util.*;
public class Poker {
private String[] deck = {
"D1","D2","D3","D4","D5","D6","D7","D8","D9","D10","DJ","DQ","DK","DA",
"C1","C2","C3","C4","C5","C6","C7","C8","C9","C10","CJ", "CQ","CK","CA",
"H1","H2","H3","H4","H5","H6","H7","H8","H9","H10","HJ", "HQ","HK","HA",
"S1","S2","S3","S4","S5","S6","S7","S8","S9","S10","SJ", "SQ","SK","SA"};
private List<String> hand = new ArrayList<>();
public Poker(){
Collections.shuffle(Arrays.asList(deck));
}
public void playGame(){
System.out.print("The first five cards are: ");
for(int i = 0; i<5; i++){
System.out.print(deck[i] +", ");
}
System.out.println(" ");
int k = 0;
String j;
List<String> discard = new ArrayList<>();
Scanner in = new Scanner(System.in);
System.out.println("Enter up to 5 cards you want to get rid of (1 to quit): ");
while (k<5) { //this is the loop I'm having trouble with
j = in.next();
if(!j.equals("1")){
j = in.next();
discard.add(j);
k++;
}else{
break;
}
}
List deckList = Arrays.asList(deck);
String[] discard1 = discard.toArray(new String[0]);
for(int l = 0; l<k; l++){
int m = deckList.indexOf(discard1[l]);
String n = deck[m];
deck[m] = deck[l+5];
deck[l+5] = n;
}
System.out.print("Your new hand is: ");
for(int i = 0; i<5; i++){
System.out.print(deck[i] +", ");
hand.add(deck[i]);
}
System.out.println(" ");
}
Try the code below. It seems you were grabbing two cards per iteration and not capturing them all in the ArrayList.
Scanner in = new Scanner(System.in);
System.out.println("Enter up to 5 cards you want to get rid of (1 to quit): ");
while (k<5) { //this is the loop I'm having trouble with
j = in.nextLine();
if(j.equals("1") {
break;
}
discard.add(j);
k++;
}
Can someone point out what is wrong with my program?
I have done most of it but I can't seem to find what's wrong with it.
It doesn't ask the user for the "enter your grade" prompt for each course.
This is for an array assignment for school. Here is my code.
I am having difficulties figuring out what is wrong with the for loop I made specifically the for loop.
This program is supposed to ask the user for their courses and then the user enters their grades for that course.
If possible, please provide me hints on what I am doing wrong.
import java.io.*;
public class StudentMarks {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException{
// TODO code application logic here
//Declare BufferedReader
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//declare variables
int x=0, y=0;
double grade=0.0;
String course;
//ask user how many courses they completed
System.out.println("How many courses have you completed?");
//obtain answer
int completed=Integer.parseInt(br.readLine());
//declare array for course
String courses[]=new String[completed];
//ask user to enter the course names use a FOR loop for this
for(int i=0;i<courses.length;i++)
{
i++;
System.out.println("Please enter course name " + i);
course = br.readLine();
for(int j=i--;j<i;j++)
{
j++;
System.out.println("What is the grade you got for " + course+ " " + j);
//get their answer
grade = Double.parseDouble(br.readLine());
}
}//end for loop
//display to the user the high achievement award qualifiers:
System.out.println("High-Ahcievement Award Qualifiers: \n");
if(grade>93)
{
//output
}
else if(grade<70)
{
System.out.println("Needs Improvement:");
//output
}
}
}
Instead of i++ use
System.out.println("Please enter course name " + (i+1));
you do not need any nested loop
for(int j=i--;j<i;j++)
{
j++;
System.out.println("What is the grade you got for " + course+ " " + j);
//get their answer
grade = Double.parseDouble(br.readLine());
}
instead use
System.out.println("What is the grade you got for " + course);
//get their answer
grade = Double.parseDouble(br.readLine());
HERE is the Full code if you still having trouble understanding it let me know .
import java.io.*;
public class sort {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException{
// TODO code application logic here
//Declare BufferedReader
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//declare variables
int x=0, y=0;
double grade=0.0;
String course;
//ask user how many courses they completed
System.out.println("How many courses have you completed?");
//obtain answer
int completed=Integer.parseInt(br.readLine());
//declare array for course
String courses[]=new String[completed];
//ask user to enter the course names use a FOR loop for this
for(int i=0;i<courses.length;i++)
{
System.out.println("Please enter course name " + (i+1));
course = br.readLine();
System.out.println("What is the grade you got for " + course);
//get their answer
grade = Double.parseDouble(br.readLine());
//end for loop
//display to the user the high achievement award qualifiers:
System.out.println("High-Ahcievement Award Qualifiers: \n");
if(grade>93)
{
//output
}
else if(grade<70)
{
System.out.println("Needs Improvement:");
//output
}
}
}
}
I think you didnt intend to have the i++ / j++ in your for loops (first statement).
The third “parameter” of the loop head actually tells the program what to do, when it reaches the end of the loop. Therefore you increment twice each time.
Your inner loop (with int j = i--) has a condition that is always false, and so it's body is never executed.
The line of code:
j = i--
isn't as simple as it seems and can be broken down into two lines:
j = i;
i = i - 1;
Note that j is set to the value of i, and only after that does i get decremented. So if j is set to i, and then i becomes i - 1, i will be one less than j. So the condition of the for loop i.e. j < i, will always be false, and so the body of the loop will never be executed.
Example:
i = 5;
j = i--;
this boils down to
i = 5;
j = i; //j is 5
i = i - 1; //i is 4
j < i; //5 < 4 is false, inner for loop not executed
Hope this helps!
im trying to write a program that will accept input of "put name mark", "get name mark" and "quit"
upon the user entering "put name mark" the program will prompt them to enter a student name and mark and then stores it at the next available array index.
the "get name" command will accept a name input from the user and they iterate through the array and display any mark matching the name entered.
the "quit" command will end the program and return the mean mark and the highest mark in the display.
the problem im having is that it dosent seem to be entering the loop when i type the required words in. it just jumps to where it asks the question again and wont even accept input
im still a beginner and ive been working on this program for 4 weeks so any help would be greatly appreciated.
package week14;
import java.util.Scanner;
public class week {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//sets number of string inputs
{
String[] names = new String[50];
double[] scores = new double[50];
// Enter student name and score
System.out.print("please enter either: quit, put name mark, get name");
input.next();
if(input.next() == "put name mark" )
{
System.out.print("Enter Student Name");
names[50] = input.next();
System.out.print("Enter Score");
scores[50] = input.nextInt();
}
System.out.println("please enter either: quit, quit, put name mark, get name");
input.next();
if(input.next() == "get name")
{
System.out.print("please enter the name you would like to display the score for");
String get = input.next();
}
// Sort
for (int i = 50 - 1; i >= 1; i--) {
// Find the maximum in the scores[0..i]
double currentMax = scores[0];
int currentMaxIndex = 0;
for (int j = 1; j <= i; j++) {
if (currentMax < scores[j]) {
currentMax = scores[j];
currentMaxIndex = j;
}
}
// Swap scores[i] with scores[currentMaxIndex];
// Swap names[i] with names[currentMaxIndex] ;
if (currentMaxIndex != i) {
scores[currentMaxIndex] = scores[i];
scores[i] = currentMax;
String temp = names[currentMaxIndex];
names[currentMaxIndex] = names[i];
names[i] = temp;
}
if (input.equals("quit")){
System.out.print(names[i] + scores[i]);
System.out.println();
System.out.print(currentMax);
break;
}
}
}
}
}
That's what i got for now maybe there are some errors if there is any problem say what's it and I'll fix it.
import java.util.Scanner;
public class Week
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in); //Scanner used to get input from the user
String[] names = new String[50]; //The array for names remember arrays index began with 0 not 1
int[] scores = new int[50]; //Again arrays began with 0 not 1 and the last is n-1
int last = 0; //Used to store the last added ID
String command; //The command from the user
boolean running = true; //Whenever the program is running or not
while(running)
{
System.out.println("please enter either: quit, put name mark, get name"); //Print the command list
command = input.nextLine(); //The next input line (This will make the Thread pause untill it get and input)
if(command.equals("put mark")) //If the command is "put mark"
{
if(last == 49) //Check because we can create and Exception by adding too much element to and array
System.out.println("Max number of people reached"); //So we can't add more people
else
{
System.out.println("Enter Student Name"); //Print the questin
names[last] = input.nextLine(); //The name
System.out.println("Enter Score"); //Ask for the score
scores[last] = input.nextInt(); //Get the score ,because score is a double we should use double so it can take numbers like 0.1
last++; //Increment last with 1
}
}else if(command.equals("get name"))
{
System.out.println("please enter the name you would like to display the score for");
String name = input.nextLine(); //Get the name
for(int i = 0; i < last; i++) //Loop untill we hit the last added name's ID
if(names[i].equals(name)) //Check if the names[i] is the name that we're searching for
System.out.println(name + " 's score is " + scores[i]); //If it's then we print it out
}else if(command.equals("quit"))
{
running = false; //The loop will never run again
//Implement sorting for youself I would use Map<K, V> but you didn't learned it so..
//In this case you have to make 1 loop to sort both of the arrays by sorting the second array
//and when you move anything must it in both arrays I can't help you to make this sorry
for(int i = 0; i < last; i++) //We print the sorted arrays of the people and their scores
System.out.println(names[i] + " 's score is " + scores[i]); //Let's print it
}
}
}
}
Write a program to calculate the current grade based on the CSE 1341 syllabus. The program should prompt the user for their first and last name. It will then pass those names as Strings to the second method of the CSE1341Grade class. The name of the second method will be calcGrade. This method will prompt the user for the count of exam scores, count of quiz scores, and count of lab scores to entered by the user.
It will then utilize repetition structure to prompt for exam grades, quiz grades and lab grades based on the previous counts entered. For example, if the user entered count of exam scores to be 2; then the program will loop 2 times to input the two exam grades; and similarly for the count of quiz and count lab grades.
Assume you have a 100% attendance record and you will get all 5% of the attendance grade.
Use the syllabus to determine the weights of each of the categories such as the exams, quizzes and labs. Add 5% to the total score since you had perfect attendance.
Assume: all exams, labs and quiz scores are out of 100 points.
Sample Run:

java CSE1341Grade
First name: James
Last name: Bond
How many exam grades do you have? 1
How many quiz grades do you have? 2
How many lab grades do you have? 2
Enter exam 1 score: 90
Enter quiz 1 score: 80
Enter quiz 2 score: 80
Enter lab 1 score: 90
Enter lab 2 score: 90
Total Score: 84.55
James Bond your grade is a: B
^^That is my homework assignment, and this is what I have done so far
import java.util.Scanner;
public class CSE1341Grade
{
public static void main(String [] args)
{
//set up Scanner for user input, prompt for first name, define variable, and print response
Scanner s = new Scanner(System.in);
System.out.print("First name: ");
String first = s.nextLine();
System.out.printf(" %s\n", first);
//prompt user for last name, define variable, and print response
System.out.print("Last name: ");
String last = s.nextLine();
System.out.printf(" %s\n", last);
}
public static void calcGrade(String first, String last)
{
//prompt user for number of exam grades, define exam variable, print response
System.out.print("How many exam grades do you have? ");
String exam = s.nextLine();
System.out.printf(" %s\n", exam);
//prompt user for number of quiz grades, define quiz variable, print response
System.out.print("How many quiz grades do you have? ");
String quiz = s.nextLine();
System.out.printf(" %s\n", quiz);
//prompt user for number of lab grades, define lab variable, print response
System.out.print("How many lab grades do you have? ");
String lab = s.nextLine();
System.out.printf(" %s\n", lab);
while (exam != -1)
{
System.out.print("Enter " exam 1 " score: ", ++exam)
//define variables for computations
int score = 0;
int grade = 0;
//if statement to determine the final letter grade
if(score >= 90 && score <=100){
grade = 'A'; }
else if(score >=80 && score < 90){
grade = 'B'; }
else if(score >= 70 && score < 80){
grade = 'C'; }
else if(score >=60 && score < 70){
grade = 'D'; }
else {
grade = 'F'; }
}
}
My problem is figuring out how to create a loop that will prompt the user for however many exam grades needed.
I have performed few changes to your code based in the comments ..
Here you can see the diff
http://www.mergely.com/LIckVifT/
Note: It still does not finish your homework :-)
Update: Since the index in the foor loop does not really matters you could use it as this:
for (int i = 1; i <= examsCount; i++) {
// using i+1 to print starting from 1 instead of 0
System.out.print("Enter " + i + " score: ");
instead of
for (int i = 0; i < examsCount; i++) {
// using i+1 to print starting from 1 instead of 0
System.out.print("Enter " + (i + 1) + " score: ");
I like to do a loop and continue to ask the user for input until I get the result I want:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean shouldContinue = true;
while(shouldContinue) {
// do program logic
System.out.print("Should we continue? [Y or N] >> ");
if (input.nextLine().equalsIgnoreCase("N")) {
shouldContinue = false;
}
}
}
This is a relatively "structured" way to do an interaction loop and continue running a program over and over so long as the user wants.
-- UPDATE --
To do a number of iterations that you know ahead of time, simply pipe that into your counter for the loop:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Number of grades to enter [number] : ");
int numberOfTimesToIterate = input.nextInt();
for (int i = 0; i < numberOfTimesToIterate; i++) {
// do stuff here
}
}
Pseudo-code:
function(int n) {
for (i = n, i > 0, i--) {
\\prompt user
}
}
That should give you the general idea of how to do it, namely taking the amount, and subtracting 1 from it until you reach 0, each time getting the data and doing what it needs to do with it. Don't forget to make sure that n never equals less than zero (invalid), and that n is an integer. Otherwise, it is desirable that you have the function simply prompt the user for an amount, then pass that amount to the function that actually uses it. Alternatively, create a function which iterates n times and calls a function passed to it as an argument that many times (much harder to correctly do).
Something like this should work for you.
System.out.println("Please enter the number of exam grades you want to enter");
int grade_count = s.nextInt();
int [] grades = new int[grade_count];
for(int i =0; i<grade_count; i++){
System.out.println("Enter grade for "+i+1 +"Exam");
grades[i] = s.nextInt();
}
I'm having a few problems with my code, this is the over all goal of the program.
One of your professors hears of your emerging programming expertise and asks you to write a SINGLE program that can be used to help them with their grading. The professor gives three 50-point exams and a single 100-point final exam. Your program will prompt the user for the student’s name, entered as Firstname Lastname (i.e. Bob Smith), the student’s 3-exam scores and 1-final exam score (all whole numbers). Class size varies from semester to semester, but 100 is the limit (declare as a constant).
Read in information for ALL students before doing any calculations or displaying any output. Verify that the 3 exam scores are between 0-50 points and that the final is between 0-100 as they are entered. Declared minimums and maximums as constant so that they can easily be updated, as needed. If invalid, display an error message and allow the user to re-enter that invalid score. Once all student info is read in, display each student’s name in the format LASTNAME, FIRSTNAME (all uppercase), the student’s exam percentage (total of all exams plus final / total possible) to 1 decimal and the student’s final grade.
This is what I have:
import java.util.*;
import java.text.*;
public class Proj4 {
public static void main(String[] args){
Scanner s= new Scanner(System.in);
String input;
String again = "y";
final int MAX_STUDENTS = 100;
final int MIN_EXAM = 0;
final int MAX_EXAM = 50;
final int MIN_FINAL = 0;
final int MAX_FINAL = 100;
String[] names = new String[MAX_STUDENTS];
int [] exams = new int[MAX_STUDENTS * 4];
int student = 1;
do
{
System.out.print("PLease enter the name of student " + student + ": " );
for (int k = 0; k < 1; k++) {
names[k] = s.nextLine().toUpperCase();
}
for ( int i = 0; i < 4; i++){
if(i==3){
System.out.print("Please enter score for Final Exam: ");
exams[i] = s.nextInt();
}
else{
System.out.print("Please enter score for Exam " + (i+1) + ": ");
exams[i] = s.nextInt();
if((exams[0]<MIN_EXAM||exams[0]>MAX_EXAM)||(exams[1]<MIN_EXAM||exams[1]>MAX_EXAM)||(exams[2]<MIN_EXAM||exams[2]>MAX_EXAM)){
System.out.println("Invalid enter 0-50 only...");
System.out.print("Please re-enter score: ");
exams[i] = s.nextInt();
}
else if(exams[3]<MIN_FINAL||exams[3]>MAX_FINAL){
System.out.println("Invalid enter 0-100 only...");
System.out.print("Please re-enter score: ");
exams[i] = s.nextInt();
}
}
}
System.out.print("do you wish to enter another? (y or n) ");
again = s.next();
if(again!="y")
student++;
}while (again.equalsIgnoreCase ("y"));
System.out.println("***Class Results***");
System.out.println(names[1] + "," + names[0] + " " + "Exam Percentage: "+ ((exams[0]+exams[1]+exams[2]+exams[3])/(MAX_EXAM*3+MAX_FINAL)));
}
}
The problems i have have are:
figuring out how to assign the user entered test scores beyond just the first student, i believe i have it set up correct for just one, but it runs into a problem when i would move on to the second student.
For some reason that I cannot figure out the line
System.out.print("do you wish to enter another? (y or n) ");
again = s.next();
doesn't allow me to enter anything, not y not n not anything, so my program effectively ends there, it doesn't make sense to me because I've done it exactly like that before and it has worked.
other than that, if there are any other problems that you can see with my code pointing them out would be extremely helpful.
Thank you
EDIT-
new problem i am having, after changing to
if(!again.equalsIgnoreCase("y"))
student++;
}while (again.equalsIgnoreCase ("y"));
it lets me type things in now, but after i type in y it prints the next line as
Please enter the name of student 1: Please enter score for Exam 1:
I don't know why or what i need to change to fix it, any suggestions?
`if(again!="y")` is the culprit here
You should use equals() method to check string equality.
if(!again.equals("y"))
If you compare Strings in Java using the == or != operators then you are not actually comparing the values. Instead you are testing if the two Strings are the same Object.
This post explains String comparison well.
To do what you want, change if (again != "y") to if(! (again.equalsIgnoreCase("y")) )
EDIT
I believe your new problem stems from the first for loop you do inside your do loop. Each time you type "y" at the end of your do/while you are going to execute the entire
for (int k = 0; k < 1; k++) {
loop again. This is why after you type "y" you are seeing Please enter the name of student 1: Please enter score for Exam 1:
A "solution" to your new issue would be to make it so the outer for enclosed the inner one, looping through 4 exams for each student usually referred to as a "double for" or "nested for loop".
That said you would then be presented with the issue of having all the exams for ALL students in a single array.
I think now is the time to sit down and put some serious thought into the design of your program. It would be much easier for you if you used a Student object to represent a student and hold their exam scores, IMO. Then you could create an array of Students as opposed to two different arrays you have now.
Here are some "starter" steps (Not necessarily a complete list):
Make a Student class that has variables for the student's first & last name, as well as an array to hold that Students exam scores
In your main class create an ArrayList to hold all of the new Student objects you will be creating.
Do your do/while loop. At the beginning of the loop create a new Student object. Then ask for the Students name and exam scores (note that if you KNOW there will only be the 4 exam scores you don't have to do any extra logic there. You can simply ask for the 4 exam scores using a for loop, or if you want all at one time. if there are a variable number of scores you will have to do some sort of check)
Add the new Student you have created to the ArrayList of Students.
Once the person selects "n", loop through the ArrayList and print the information for each Student!
Your for (int k = 0; k < 1; k++) loop will execute only once (for one student) because you have it set up to execute only while k < 1, which will happen only once. As soon, as you increase k to 1, the loop will stop. I would change it to for (int k = 0; k < MAX_STUDENTS; k++) to make sure it will loop through until you reach the max number of students allowed.