Java nested loop. Trying to reiterate the inside loop - java

I'm practicing 2d array and stumbled upon on how to reiterate the inside loop of array to accept another set of inputs. I got stuck on how to reiterate the inputs without sacrificing the reinitialization of the loop variable so that it will not reset the index pointer of the array.
Here's the main class:
public class Games {
public static void main(String args[]) {
GamesClass data = new GamesClass();
List output[][] = data.createlist();
data.print(output);
}
}
class List {
private String Gamers, Status;
private int Score;
public List()
{
Gamers = "";
Score = 0;
Status = "";
}
public List(String name, int score, String status)
{
Gamers = name;
Score = score;
Status = status;
}
public void setGamers(String name)
{
Gamers = name;
}
public String getGamers()
{
return Gamers;
}
public void setScores(int score)
{
Score = score;
}
public int getScores()
{
return Score;
}
public void setStatus(String status)
{
Status = status;
}
public String getStatus()
{
return Status;
}
}
And here's the invoking class:
import java.util.*;
class GamesClass {
private int ngames,ngamers;
private String[] games;
public void nloops()
{
Scanner in = new Scanner(System.in);
System.out.print("Enter no. of games: ");
ngames = in.nextInt();
System.out.print("Enter number of gamers each game: ");
ngamers = in.nextInt();
games = new String[ngames];
}
public String[] inputgames()
{
Scanner in = new Scanner(System.in);
for(int i=0 ; i<ngames ; ++i)
{
System.out.print("Enter Game: ");
games[i] = in.next();
}
return games;
}
public List[][] createlist()
{
nloops();
inputgames();
List[][] list = new List[ngames*ngamers][3];
Scanner in = new Scanner(System.in);
int score, n, i=0;
for(n=0 ; n<ngames ; ++n)
{
System.out.println("\nGame#" + (n+1) + " " + games[n]);
for(; i<list.length/ngames ; ++i)
{
list[i][0] = new List();
System.out.print("Gamer " + (i+1) + ": ");
list[i][0].setGamers(in.next());
System.out.print("Score: ");
score = in.nextInt();
list[i][0].setScores(score);
if(score>=1 && score<=50) list[i][0].setStatus("Noob");
else if(score>=51 && score<=100) list[i][0].setStatus("Savage");
else if(score>=101 && score<=150) list[i][0].setStatus("Expert");
else if(score>=151 && score<=200) list[i][0].setStatus("Master");
else if(score>=201 && score<=250) list[i][0].setStatus("Veteran");
else if(score>=251 && score<=300) list[i][0].setStatus("Legendary");
}
i+=ngamers;
}
return list;
}
public void print(List[][] value)
{
int n, i=0;
for(n=0 ; n<ngames ; ++n)
{
System.out.println("\nGame#" + (n+1) + " " + games[n]);
System.out.println("\nGamer\t\tScore\t\tStatus");
for( ;i<value.length/ngames ; ++i)
{
System.out.println((i+1) + " " + value[i][0].getGamers() + "\t\t" + value[i][0].getScores() + "\t\t" + value[i][0].getStatus());
}
i+=ngamers;
}
}
}
The output keeps stucked after inputting the first set of inputs.
Enter no. of games: 2
Enter number of gamers each game: 2
Enter Game: VALORANT
Enter Game: LOL
Game#1 VALORANT
Gamer 1: Jrk
Score: 100
Gamer 2: Dash
Score: 200
Game#2 LOL
Game#1 VALORANT
Gamer Score Status
1 Jrk 100 Savage
2 Dash 200 Master
Game#2 LOL
Gamer Score Status

Change the condition in the loop from
i < list.length/ngames
to i < (list.length/ngames)*(n+1) and also remove this line at the end of the loop : i+=ngamers; The variable is being incremented in the loop itself, there's no need to change it again.
However, this will produce the output
Game#1 VALORANT
Gamer 1: Jrk
Score: 100
Gamer 2: Dash
Score: 200
Game#2 LOL
Gamer 3 : name
Score : 300
Gamer 4 : name2
Score : 400
If you want to display Gamer 1 and Gamer 2 for the second game as well, print (i - n*ngamers + 1) instead of just (i+1)
Make these same changes to the print function as well

Related

Why does my Mooc.fi ski jumping programm not print the correct score? Is it overwritten?

I am working on mooc.fi week 8, the last exercise: ski jumping. At the very bottomt of the page. Here is the link: https://materiaalit.github.io/2013-oo-programming/part2/week-8/
All tests are succesfull, except for the calculation of the output.
When the jumpers jump twice, the scores of the first and second jump are meant to be added. If the user decides to terminate the programm at this point, the jumpers are meant to be printed out, winner first, with their final scores assigned to them.
As the actual final scores printed can (based on the number) only be the result of one jump, I suspect that the programm overwrites the first jump with the second instead of adding them, but I am not sure.
The error message says, that the actual final score is supposed to be 275 but was actually 158, which with two rounds and therefore two executed jumps is just not a possible score if the jumper had actually been assigned the score of two jumps and not just one.
But it is difficult for me to assess that as the jump length and the points assigned by the judges (which together make up the jumper's score) are generated randomly.
The error message I receive when testing is the following:
"twoRoundsOneJumperCalculationCorrect Failed: Jumper Arto's points are printed incorrectly in the tournament results your programm prints.
I have tested the calculation in the programm while it is running and the points the jumpers receive while jumping are accurate. Only the final results seem to be off. I am not sure why that is the case though. They appear to be overwritten with new scores.
I have gone through the code again to find what I am doing wrong, but I just cannot see where the mistake is.
I have divided the programm in four classes:
-Main to execute the UserInterface
-UserInterface for the organizing and printing the programm
-Jumper for creating jumpers for the ski tournament and to execute everything related to them such as jumping and the calculation of the scores
-SortAgainstPoints to sort the jumpers in ascending order by score
Here is my code:
//Main:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
UserInterface ui = new UserInterface();
ui.start(reader);
}
}
//UserInterface:
import java.util.*;
import java.util.Set;
import java.util.TreeMap;
public class UserInterface {
private HashMap<String,Jumper> participants;
private Jumper participant;
public UserInterface()
{
this.participants = new HashMap<String,Jumper>();
}
public void start(Scanner reader)
{
System.out.println("Kumpula ski jumping week");
System.out.println("");
System.out.println("Write the names of the participants one at a time; an empty string brings you to the jumping phase.");
while(true)
{
System.out.print(" Participant name: ");
String name = reader.nextLine();
if(!name.isEmpty())
{
this.participant = new Jumper(name);
this.participants.put(name, participant);
}
if(name.isEmpty())
{
System.out.println("");
break;
}
}
System.out.println("The tournament begins!\n");
rounds(reader);
}
public void sortAgainstPoints(ArrayList<Jumper> list)
{
Collections.sort(list, new SortAgainstPoints());
}
public void rounds(Scanner reader)
{
int roundCounter = 0;
ArrayList<Jumper> list = new ArrayList<Jumper>(this.participants.values());
while(true)
{
sortAgainstPoints(list);//does that even work????
System.out.print("Write \"jump\" to jump; otherwise you quit: ");
String input = reader.nextLine();
System.out.println("");
roundCounter ++;
if(!input.equals("jump"))
{
break;
}
System.out.println("Round " + roundCounter + "\n");//Round 1 ...
System.out.println("Jumping order:");
int counter = 0;
for(Jumper p : list)
{
counter++;
System.out.println(" " + counter + ". " + p);
}
System.out.println("");
System.out.println("Results of round " + roundCounter);
for(Jumper p : list)
{
int jumpLength = p.jump();
p.addJumpLength(jumpLength);
int[] judgesScores = new int[5];
judgesScores = p.judgeScores();
int score = 0;
score += p.jumpScore(jumpLength, judgesScores);
p.setPoints(score);
System.out.print(" " + p.getName() + "\n" +
" length: " + jumpLength + "\n" +
" judge votes: " + p.printJudgesScores(judgesScores) +"\n"
);
}
sortAgainstPoints(list);
System.out.println("");
}
Collections.reverse(list);//highest scored jumper should now be first
System.out.println("Thanks!\n");
System.out.println("Tournament results:");
System.out.println("Position Name");
for(int i = 0; i < list.size(); i++)
{
System.out.println((i +1) + " " + list.get(i).getName() + " (" + list.get(i).getPoints() + ")\n"
+ " jump lengths: " + list.get(i).printJumpLengths());
}
//tournament result does not equal acutal points and jump lengths, assignment is most likely overwritten with each new jump
}
}
//Jumper:
import java.util.*;
public class Jumper {
private String name;
private int points;
private Random random;
private int[] judges;
private ArrayList<Integer> jumpLengths;
public Jumper(String name)
{
this.name = name;
this.points = 0;
this.jumpLengths = new ArrayList<Integer>();
}
#Override
public String toString()
{
return this.name + " (" + this.points + " points)";
}
public int getPoints()
{
return this.points;
}
public int jump()
{
this.random = new Random();
int jumpLength = random.nextInt(120 - 60 +1) + 60;
return jumpLength;
}
public int[] judgeScores()
{
this.judges = new int[5];
for(int i = 0; i< judges.length; i++)
{
int judgeScore = random.nextInt(20 - 10 +1) + 10;
judges[i] = judgeScore;//scores, unsorted
}
return judges;
}
//smallest and largest judge score are meant to be skipped as specified //by task
public int jumpScore(int jumpLength, int[] judges)
{
sort(judges);//sorted
//skip first and last:
int score = jumpLength;
for(int i = 1; i < judges.length-1; i++)//skips first and last index
{
score += judges[i];
}
return score;
}
public String printJudgesScores(int[] judges)
{
String judgesScores = "[";
for(int i = 0; i < judges.length-1; i++)
{
judgesScores += judges[i] + ", ";
}
judgesScores += judges[judges.length-1] +"]";
return judgesScores;
}
public String getName()
{
return this.name;
}
public void setPoints(int points)
{
this.points = points;
}
public int[] sort(int[] judges)
{
for(int i = 0; i < judges.length; i ++)
{
for(int j = i+1; j < judges.length; j++)
{
if(judges[i] > judges[j])
{
int temp = judges[i];
judges[i] = judges[j];
judges[j] = temp;
}
}
}
return judges;
}
public void addJumpLength(int jumpLength)
{
this.jumpLengths.add(jumpLength);
}
public String printJumpLengths()
{
String jumps = "jump lengths: ";
for(int i = 0; i < this.jumpLengths.size()-1; i++)
{
jumps += this.jumpLengths.get(i) + " m, ";
}
jumps += this.jumpLengths.get(this.jumpLengths.size()-1) + " m";
return jumps;
}
}
//SortAgainsPoints:
import java.util.Comparator;
public class SortAgainstPoints implements Comparator<Jumper> {
public int compare(Jumper jumper1, Jumper jumper2)
{
if(jumper1.getPoints() > jumper2.getPoints())
{
return 1;
}
else if(jumper1.getPoints() < jumper2.getPoints())
{
return -1;
}
else
return 0;
}
}
I would appreciate any help!
I have done my best to post a good question, I know there are many better ones out there. If there is anything I can do to make the question clearer, let me know!
Edit: In case anybody is wondering, it's because I did not update the points correctly, I just replaced the old score with the new. It should have been p.setPoints(p.getPoints() + score);
instead of p.setPoints(score);

Condition is not verifying the validity of the input

I'm doing an assignment that asks a user to input a student name, and then quiz scores until the user chooses to stop. It then calculates the total score and the average of all those scores and outputs them to the screen.
We are moving on to the subject of inheritance and now we are requested to make a class called MonitoredStudent which extends Student. The point of the MonitoredStudent class is to check if the average is above a user inputted average and display whether the student is off academic probation.
I have got most of the program written and when I input just one score (such as 71, when the average I set is 70) it is still displaying that I am on academic probation, even though the one quiz score is above the average I set of 70.
The main issue is that no matter what integer is set for the minimum passing average, I always get a return of false.
I added the "return false" statement in the isOffProbation method as when I add an if-else statement to check if the averageScore (from the Student class) is less than or equal to minPassingAvg eclipse tells me that the method needs a return type of boolean.
public class MonitoredStudent extends Student {
int minPassingAvg;
public MonitoredStudent(){
super();
minPassingAvg = 0;
}
public MonitoredStudent(String name, int minPassingAvg) {
super(name);
this.minPassingAvg = minPassingAvg;
}
public int getMinPassingAvg() {
return minPassingAvg;
}
public void setMinPassingAvg(int minPassingAvg) {
this.minPassingAvg = minPassingAvg;
}
boolean isOffProbation() {
if(getAverageScore() >= minPassingAvg)
return true;
return false;
}
}
This is the Student super class:
public class Student{
private String name;
private double totalScore;
private int quizCount;
public Student(){
name = "";
totalScore = 0;
quizCount = 0;
}
public Student(String n){
name = n;
totalScore = 0;
quizCount = 0;
}
public void setName(String aName){
name = aName;
}
public String getName(){
return name;
}
public void addQuiz(int score){
if(score >= 0 && score <= 100){
totalScore = totalScore + score;
quizCount = quizCount + 1;
}else{
System.out.println("Score must be between 0 and 100, inclusive");
}
}
public double getTotalScore(){
return totalScore;
}
public double getAverageScore(){
return totalScore / quizCount;
}
}
This is the main method:
import java.util.Scanner;
public class MonitoredStudentTester{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
MonitoredStudent monStu = new MonitoredStudent();
String repeat = "n";
int currentScore = 0;
int minPassAv;
System.out.println("Enter the student's name:");
String stuName = scan.next();
Student sName = new Student(stuName);
System.out.println("What is the minimum passing average score: ");
minPassAv = scan.nextInt();
Student stu = new Student();
do {
System.out.println("Enter a quiz score: ");
currentScore = scan.nextInt();
stu.addQuiz(currentScore);
monStu.setMinPassingAvg(currentScore);
System.out.println("Would you like to enter any more scores?: (Y for yes, N for no)");
scan.nextLine();
repeat = scan.nextLine();
}while(repeat.equalsIgnoreCase("y"));
String studName = stu.getName();
double totalScore = stu.getTotalScore();
double avgScore = stu.getAverageScore();
boolean offProb = monStu.isOffProbation();
System.out.println(studName + "'s Total Score is: " + totalScore);
System.out.println(studName + "'s Average Score is: " + avgScore);
System.out.println("Is " + studName + "off academic probation?: " + offProb);
}
}
You main class should be something like this.
public class MonitoredStudentTester {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
MonitoredStudent monStu = new MonitoredStudent();
String repeat = "n";
int currentScore = 0;
int minPassAv;
System.out.println("Enter the student's name:");
monStu.setName(scan.next());
System.out.println("What is the minimum passing average score: ");
minPassAv = scan.nextInt();
do {
System.out.println("Enter a quiz score: ");
currentScore = scan.nextInt();
monStu.addQuiz(currentScore);
monStu.setMinPassingAvg(minPassAv);
System.out.println("Would you like to enter any more scores?: (Y for yes, N for no)");
scan.nextLine();
repeat = scan.nextLine();
} while (repeat.equalsIgnoreCase("y"));
String studName = monStu.getName();
double totalScore = monStu.getTotalScore();
double avgScore = monStu.getAverageScore();
boolean offProb = monStu.isOffProbation();
System.out.println(studName + "'s Total Score is: " + totalScore);
System.out.println(studName + "'s Average Score is: " + avgScore);
System.out.println("Is " + studName + "off academic probation?: " + offProb);
}
}
When using inheritance you just need to create an object of child class.

Issue dropping credits from course in Java dropCourse Method

What I have is a two snippets of code. The question I have in particular is about my dropCourse method within the student driver. Everything in my code seems to work fine except when I drop a course it does not drop the courses credits. For example, if I drop a course named "Computer101" which had four credits, it will remove "Computer101" From the schedule, but will not remove the "4" credits when I choose option 5 to print the total credits. So if we have a full schedule of:
Computer101 in position 0 worth 4 credits
Physics105 in position 1 worth 4 credits
Art101 in position 2 worth 4 credits
Chem101 in position 3 worth 4 credits
And I decide to drop Computer101 from the schedule, all other classes will move up in their position in the array as they are supposed to, when printing the schedule that class will no longer show up and when it is searched for it will not be found, but the amount of credits it was worth will still be there. I feel like the solution is right in front of me, but I am so burned out I am not seeing it. I would really appreciate any help and I hope I was clear with what I am asking.
Here is where my dropCourse method will be found:
public class Student
{
//Instance Data
String studentName;
String studentID;
String streetAddress;
String city;
String state;
String zipCode;
String major;
final int MAX_CREDITS = 18;
int courseNumber = 0; //start out with no courses
int totalCredits;
final int SIZE = 6;
String [ ] schedule = new String [SIZE];
//Create Constructor:
//Initializes the student data at instantiation time.
//-------------------------------------------------------
// Sets up the student's information.
//-------------------------------------------------------
public Student (String name, String id, String address, String cityName, String stateName, String zip, String area )
{
studentName = name;
studentID = id;
streetAddress = address;
city = cityName;
state = stateName;
zipCode = zip;
major = area;
}//end Student Constructor
//Method to Return student information as string:
//-------------------------------------------------------
// Returns the student information as a formatted string.
//-------------------------------------------------------
public String toString()
{
String studentInfo;
studentInfo = "Name:\t\t\t" + studentName + "\n" + "ID:\t\t\t" + studentID + "\n" + "Address:\t\t" + streetAddress
+ "\n" + "City:\t\t\t" + city + "\n" + "State:\t\t\t" + state + "\n" + "Zip Code:\t\t" + zipCode
+ "\n" + "Major:\t\t\t" + major + "\n";
return studentInfo;
}// end toString
//Method to determine if maximum allowed credits have been exceeded
//-------------------------------------------------------
// Returns true if total credits does not exceed 18.
//-------------------------------------------------------
private boolean checkCredits(int numCredits)
{
if (numCredits + totalCredits <= MAX_CREDITS) //make sure max credits not exceeded
{
return true; //return a true if still less than 18 credits
}
else
{
return false; //return a false if 18 credit limit is exceeded
}//end numCredits
}//checkCredits
//Method to add a course to the student’s schedule
//-------------------------------------------------------
// Adds a course to the array if total credits does not exceed 18.
//-------------------------------------------------------
public void addCourse(String course, int numCredits)
{
if (courseNumber < SIZE ) //make sure array is not full.
{
if (checkCredits(numCredits) == true) //if we’re under 18 credits
{
//add course
schedule [courseNumber] = course + ":\t\t" + numCredits + "\tCredits\n";
//increment number of credits
totalCredits = totalCredits + numCredits;
//increment number of courses
courseNumber = courseNumber + 1;
System.out.println("The course has been added!");
}
else //oops – can’t do more than 18 credits
{
System.out.println("You have exceeded the maximum allowed credits.");
}//end checkCredits
}
else //oops – can’t do more than 6 courses
{
System.out.println("You have exceeded 6 courses.");
}//end courseNumber
}//addCourse
public void displaySchedule( )
{
for (int index = 0; index < courseNumber; index++)
{
System.out.println("Course #" + (index + 1) + " " + schedule[index] + "\n");
}//end for
}//end display schedule
public int searchCourse(String courseName)
{
String course;
boolean flag = false;
int index = 0;
while(index < courseNumber && flag == false)
{
String extract = schedule[index].substring(0,6);
if (extract.contains(courseName) == true)
{
flag = true;
}
else
{
index++;
}
}
if (flag == false)
{
return -1;
}
else
{
return index++;
}
}
public void dropCourse(String courseName)
{
int found;
found = searchCourse(courseName);
int index = 0;
if (found == -1)
{
System.out.println("Course not in schedule");
}
else
{
if (found == 5)
{
courseNumber = courseNumber -1;
}
else
{
for (index = found; index < courseNumber; index ++)
{
schedule[index] = schedule[index + 1];
}
courseNumber = courseNumber -1;
System.out.println("The course has been dropped!");
}
}
}
public int totalCredits()
{
System.out.println("The total credits are " + totalCredits);
return totalCredits;
}
}//end class Student
This is where my menu that works with the above code is:
//This is a Driver program to test the external Class named Student
import java.util.Scanner;
public class TheMenu //BEGIN Class Definition
{
//**************** Main Method*************************
static Scanner scan = new Scanner(System.in);
public static void main (String[] args)
{
//Data Definitions:
//Instance Data
String name;
String id;
String street;
String city;
String state;
String zip;
String major;
String courseName;
int courseCredits;
int menu = 0;
//Initialize first Student
name = "Florence Welch";//look her up
id = "7777";
street = "777 Heaven Street";
city = "Witchville";
state = "NY";
zip = "12345";
major = "Arts";
//instantiate the Student object
Student student1 = new Student(name, id, street, city, state, zip, major);
while (menu < 6)//begin while for menu options
{
System.out.println("1. Add a course ");
System.out.println("2. Search for a course");
System.out.println("3. Drop a course");
System.out.println("4. Print out a student's schedule");
System.out.println("5. Print out total credits");
System.out.println("6. Exit");
System.out.println("Enter an option: ");
menu = scan.nextInt();
if (menu == 1)//option to add course
{
System.out.println("Please enter the name of the course: ");
courseName = scan.next();
System.out.println("How many credits is the course? ");
courseCredits = scan.nextInt();
student1.addCourse(courseName, courseCredits);//uses method to store course information in array
}
else if (menu == 2)//option to search for course
{
int x;
System.out.println("Please enter the name of the course: ");
courseName = scan.next();
student1.searchCourse(courseName);
x = student1.searchCourse(courseName);
if (x == -1)//course is not found if value returns -1
{
System.out.println("Course not found");
}
else
{
System.out.println("Course found in position " + student1.searchCourse(courseName));//shows user the position of course
}
}
else if (menu == 3)//will drop course from users schedule
{
System.out.println("Please enter the course you wish to drop: ");
courseName = scan.next();
student1.dropCourse(courseName);
}
else if (menu == 4)//displays the users schedule
{
System.out.println(name + "'s Schedule:\n\n");
student1.displaySchedule();
}
else if (menu == 5)//will display users credits for semester
{
student1.totalCredits();
}
else
{
System.out.println("Enjoy your semester!");//option 6 will exit program
}
}
}
}

Cannot run the Threshold correctly Java

Main.java
import java.util.*;
public class Main{
static Student[] students = new Student[10];//creates an array of 10 students to be entered
public static int inputThreshold(){
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the Threshold: \n");
int threshold = scan.nextInt();
return Threshold();
}
public static Student inputStudent(){
Scanner scan = new Scanner(System.in);
System.out.println("Enter students surname: \n");//instructs the user to enter a surname
String name = scan.nextLine();//allows the user to input sdtudents surname
System.out.println("Enter student score between 0 and 30: \n");
int score = scan.nextInt();//allows the user to input students score
return new Student(name, score);
}
public static void printStudent(Student student){
int percentage = student.getScore()*10/3;//retrieves the percentage of the score submitted out of 30
System.out.println("Surname: " + student.getName() + " Score: " + student.getScore() + " Percentage: " + percentage + "%");
//prints out the surname, score and percentage achieved by the student
}
public static void printThreshold(int threshold){
int percentage = student.getScore()*10/3;//retrieves the percentage of the score submitted out of 30
if (percentage < threshold){
System.out.println("Surname: " + student.getName() + " Score: " + student.getScore() + " Percentage: " + percentage + "%");
//prints out the surname, score and percentage achieved by the student
}
}
public static Student getWinner(Student[] student){
Student x = student[0];
for(int i = 1; i < 10; i++){
if(student[i].getScore() > x.getScore()){
x = student[i];
}
}
return x;
}
public static void main(String[] args){
for (int i = 0; i = 1; i++){
threshold = inputThreshold;
}
for (int i = 0; i < 10; i++){
students[i] = inputStudent();
}
for(int i = 0; i < 10; i++){
printStudent(students[i]);
}
for(int i= 0; i < 1; i++){
printThreshold(students[i]);
}
Student winrar = getWinner(students);//retrieves the winner from getWinner into a variable
System.out.println("AND WE HAVE OUR WINNER! \n" + "Name: " + winrar.getName() + " Score: " + winrar.getScore());
//prints out the highest scoring students surname, with their score
}
}
Student.java
public class Student{
private String name;//sets name to characters
private int score;//sets score to numbers
private int threshold;//sets the threshold of the score
private int max = 30;//sets max score to 30
public Student(String name, int score){
this.name = name;
if (score <= max && score >= 0) //if the score is equal to 30 or less than 0
this.score = score;//the score can be stored
else{
System.out.println("This number is too big ");//if it is larger than 30 it cannot be stored and shows errors message
System.exit(1);//this will end the program
}
}
public String getName(){
return name;
}
public int getScore(){
return score;
}
public int getThreshold(){
return threshold;
}
public void setScore(int s){
this.score = s;
}
public void setName(String n){
this.name = n;
}
public void setThreshold(int t){
this.threshold = t;
}
}
Is returns Cannot Find Symbol - method Threshold()
I'm not sure what to refer to or how to call the method to get it to run correctly. Brief: 10 users, 10 scores. There's a threshold to be achieved by each entrant. The program outputs their names, scores achieved and the percentage of their score. But it should also announce the overall winner.
Not sure here
return Threshold();
should be
return threshold;
change Threshold() to threshold.
I strongly advice you to read this article before writing another program
Objects, Instance Methods, and Instance Variables
public static int inputThreshold(){
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the Threshold: \n");
int threshold = scan.nextInt();
return Threshold();
}
public static void main(String[] args){
for (int i = 0; i = 1; i++){
threshold = inputThreshold;
}
...rest of code in main
}
threshold is a local variable defined in inputStudent(), you can't access it in main() .Also return Threshold();, there is no Threshold() method defined in the code you've provided

Java: Use an Array over a Linked list

I am relatively new to Java. And I am a Student in the second semester.
The following has been my last task, and I have already presented it. Everything was fine, and the task that was neccessary for me to accomplish has been completely fulfilled.
The task over the semester was making a little game (My choice was guess a number game), and the tasks were simply build upon eachother. (e.g. use at least 5 functions, at least 3 classes, show all four examples of OOP and make a Computer Player)
So having that said I do not mean for people to solve these task because as you will see they have been completed.
Just one additional thing gives me trouble.
I use a Linked list to store the guessed numbers and recall them when needed.
So finally my question is:
How would I go about switching the Linked list with an Array?
Here the code:
Here the Run Class:
package fourfive;
public class Run {
/*
The Game Initializing class!
>>>> "game.getNumPlayers()" //can be uncommented if you want to play
if left commented, you can watch the bots fight to the death.
------------------------------------------------------
game.setBotPlayers //Same as getNumPlayers - defines how many (Bot) players you want to add
------------------------------------------------------
game.setTopNum() // defines the maximum range of numbers
which you want to guess. Starting from 0!
-----------------------------------------------------
*/
public static void main(String[] args){
Game game = new Game(0);
//game.getNumPlayers();
game.setBotPlayers(100);
game.setTopNum(2000);
game.start();
}
}
Game Class:
package fourfive;
import java.util.Random;
import java.util.Scanner;
public class Game {
/*
Some Variables being defined here.
*/
private static Scanner input = new Scanner(System.in);
private int MAX_Tries;
private int TOP_Num;
private int numPlayers;
private int numBots;
private boolean gameWinner = false;
private Random rand = new Random();
private int num;
private Participants[] players; //inheritance 1
private Participants currentPlayer; //polymorphism 1
public Game(int numPlayers) {
this(numPlayers, 10);
}
public Game(int numPlayers, int maxTries) {
this(numPlayers, maxTries, 1000);
}
public Game(int numPlayers, int maxTries, int topNum) {
MAX_Tries = maxTries;
TOP_Num = topNum;
this.numPlayers = numPlayers;
resetPlayers();
resetTheNumber();
}
/*
Inheritance Example 1
The following is a piece of inheritance. Whereas an array of Players whenever of the type
"Participants". Which is then resolved into the type "Human" and that is being inherited from
"Participants". And whenever Bots or Human players are joined, they will be joined within
the same array
*/
public void resetPlayers() {
players = new Human[numPlayers + numBots];
for (int i = 0; i < numPlayers; i++) {
players[i] = new Human(i + 1);
}
for (int i = numPlayers; i < (numBots + numPlayers); i++) {
players[i] = new Computer(i + 1, TOP_Num);
}
}
public void setNumPlayers(int numPlayers) {
this.numPlayers = numBots;
resetPlayers();
}
public void setBotPlayers(int numBots) {
this.numBots = numBots;
resetPlayers();
}
public int getMaxTries() {
return MAX_Tries;
}
public void setMaxTries(int maxTries) {
this.MAX_Tries = maxTries;
}
public int getTopNum() {
return TOP_Num;
}
public void setTopNum(int topNum) {
this.TOP_Num = topNum;
resetTheNumber();
resetPlayers();
}
private void resetTheNumber() {
num = rand.nextInt(TOP_Num);
}
public void start() {
resetPlayers();
System.out.println("Welcome to the Guess a Number Game!\n");
System.out.println("Guess a number between 0 and " + (TOP_Num - 1) + "!");
currentPlayer = players[0];
System.out.println("The num " + num);
/*
Polymorphism example.
Any object that can pore than one IS-A test is considered to be Polymorphic.
In this case we are setting up a condition in which any given player has
the ability to win, which is depicted from the "isCorrect()" Method.
*/
while (!gameWinner && currentPlayer.getNumTries() < MAX_Tries) {
for (int i = 0; i < players.length; i++) {
//currentPlayer = players[i];
players[i].guess();
if (isCorrect()) {
gameWinner = true;
printWinner();
break;
} else
printWrong();
}
if (!gameWinner) {
printTriesLeft();
}
}
if (!gameWinner)
printLoser();
}
public boolean isCorrect() {
return currentPlayer.getLastGuess() == num;
}
public void printWinner() {
if (currentPlayer instanceof Computer)
System.out.println("Sorry! The Bot " + currentPlayer.getPlayerNum() + " got the better of you, and guessed the number: [" + num + "] and won! Perhaps try again!");
else
System.out.println("GG Player " + currentPlayer.getPlayerNum() + "you guessed the Number [" + num + "] right in just " + currentPlayer.getNumTries() + " tries!");
}
public void printLoser() {
System.out.println("Too Sad! You didn't guess within " + MAX_Tries + " tries! Try again!");
}
public void printWrong() {
String word = "too high";
if ((Integer.compare(currentPlayer.getLastGuess(), num)) == -1)
word = "too low";
System.out.println("Nope! " + word + "!");
}
public void printTriesLeft() {
System.out.println(MAX_Tries - currentPlayer.getLastGuess() + " tries left!");
}
public void getNumPlayers() {
System.out.print("Enter number of Persons playing => ");
while (!input.hasNextInt()) {
input.nextLine();
System.out.println("Invalid input! It must be a number!");
System.out.print("Enter the number of Players => ");
}
numPlayers = input.nextInt();
System.out.print("Enter number of Bots! =>");
while (!input.hasNextInt()) {
input.nextLine();
System.out.println("Invalid input! It must be a number!");
System.out.print("Enter number of Bots! =>");
}
numBots = input.nextInt();
resetPlayers();
}
}
Participants class:
package fourfive;
import java.util.LinkedList;
public abstract class Participants extends Run {
protected int numTries;
protected int playerNum;
protected LinkedList<Integer> guesses;
abstract void guess();
public int getLastGuess(){
return guesses.peek();
}
public int getPlayerNum(){
return playerNum;
}
public int getNumTries(){
return guesses.size();
}
}
Now the Human class: (basically the human player)
package fourfive;
import java.util.LinkedList;
import java.util.Scanner;
public class Human extends Participants {
protected static Scanner input = new Scanner(System.in);
public Human(int playerNum) {
numTries = 0;
this.playerNum = playerNum;
guesses = new LinkedList<Integer>();
}
public void guess(){
System.out.print("Player " + playerNum + "guess =>");
while(!input.hasNextInt()){
input.nextLine();
System.out.println("Invalid input!");
System.out.print("Player " + playerNum + "guess =>");
}
guesses.push(input.nextInt());
}
}
And Last the Computer class:
package fourfive;
import java.util.Random;
public class Computer extends Human {
protected static Random rand = new Random();
protected int maxGuess;
Computer(int playerNum) {
super(playerNum);
maxGuess = 1000;
}
Computer(int playerNum, int topNum){
super(playerNum);
maxGuess = topNum;
}
#Override
public void guess() {
int guess = rand.nextInt(maxGuess);
System.out.println("Bot " + playerNum + " turn *" + guess + "*");
guesses.push(guess);
}
public int getMaxGuess() {
return maxGuess;
}
public void setMaxGuess(int num) {
maxGuess = num;
}
}
You would initialize the Array with a fixed size, e.g. 4 and resize if needed. For this, you need an extra attribute to store the fill level of the array.
int[] guesses = new int[4];
int guessFilling = 0;
[...]
#Override
public void guess() {
int guess = rand.nextInt(maxGuess);
System.out.println("Bot " + playerNum + " turn *" + guess + "*");
if (guessFilling == guesses.length) {
resizeGuesses();
}
guesses[guessFilling++] = guess;
}
private void resizeGuesses() {
int[] newGuesses = new int[guesses.length > 0 ? 2 * guesses.length : 1];
System.arraycopy(guesses, 0, newGuesses, 0, guesses.length);
guesses = newGuesses;
}

Categories

Resources