java- I got wrong results of counting - java

I wrote a program which counts the number of rooms for each class (art, sport, etc).
For example, each class contains a maximum of 3 students. If I have 9 students, with 6 music students and 3 art students,the results have to be: 1 room for art and 2 rooms for music.
When I run the code, I get these wrong results: the number of rooms for art equals 2 instead of 1 and the number of rooms for music equals 1 instead of 2.
Here is the result of execution of this program:
Insert numbers of participants:
9
Insert student in class:
1
Insert student in class:
1
Insert student in class:
1
The number of rooms for Music is:1
Insert student in class:
1
Insert student in class:
1
Insert student in class:
1
Insert student in class:
2
Insert student in class:
2
Insert student in class:
2
The number of rooms for Art is:2
This is my code:
import java.util.Scanner;
public class GroupActivity
{
public static void main()
{
Scanner GActivity=new Scanner(System.in);
System.out.println("Insert numbers of participants:");
int participantNo= GActivity.nextInt();//Insert numbers of participants
int music= 1;int art=2; int theatre= 3; int sport= 4; // Representation of each class by numbers.
int countM=0; //This variable contains the number of the participants in music class.
int countA=0; //This variable contains the number of the participants in art class.
int countT=0; //This variable contains the number of the participants in theatre class.
int countS=0; //This variable contains the number of the participants in sport class.
int countOFR=0;
for(int i=0;i<participantNo;i++)
{
System.out.println("Insert student in class:");
int p= GActivity.nextInt();// // Representation of student by number.int
if(p==music)
//for(
{
countM++;
int M=countM;
//System.out.println("student in class:"+music);
//System.out.println("Total music class:"+M);
if(M==3)
{
countOFR++;
int countOfRoom=+countOFR;
System.out.println("The number of rooms for Music is:"+countOfRoom);
}
}
else if(p==art)
{
countA++;
int A=countA;
// System.out.println("student in class:"+art);
if(A==3)
{
countOFR++;
int countOfRoom=+countOFR;
System.out.println("The number of rooms for Art is:"+countOfRoom);
}
//System.out.println("Total student in art class:"+A);
}
else if(p==theatre)
{
countT++;
int T=countT;
// System.out.println("student in class:"+theatre);
//System.out.println("Total thaetre class:"+T);
if(T==3)
{
countOFR++;
int countOfRoom=+countOFR;
System.out.println("The number of rooms for Theatre is:"+countOfRoom);
}
}
else{
countS++;
int S=countS;
if(S==3)
{
countOFR++;
int countOfRoom=+countOFR;
System.out.println("The number of rooms for Sport is:"+countOfRoom);
}
//System.out.println("Total sport class:"+S);
}
}
}
}

The problem is with countOFR. You are using this to store the no of rooms for all classes, instead of any one. Thus when you read data for class, the older value of countOFR gets added.
if(M==3)
{
countOFR++; // This should not be common for all
int countOfRoom=+countOFR;
System.out.println("The number of rooms for Music is:"+countOfRoom);
}
instead use different variables
int countOFR_music = 0;
int countOFR_art = 0;
int countOFR_theatre = 0;
int countOFR_sport = 0;
then use it like this
if(M==3)
{
countOFR_music++; // This should not be common for all
int countOfRoom=+countOFR_music;
System.out.println("The number of rooms for Music is:"+countOfRoom);
}
likewise for arts class
if(A==3)
{
countOFR_art++;
int countOfRoom=+countOFR_art;
System.out.println("The number of rooms for Art is:"+countOfRoom);
}

I think you should count students on each class, then process them at the end.
First, declare one or more object to hold number of student. Your declaration could work fine, but to shorten your code, you should use an array:
int numOfStudent[] = new int[4]; // 4 is for 4 types of class
Then in the for loop, do a check before increase counter, may be ask use input again (it's up to you):
// ...
int p= GActivity.nextInt();
int idx = p - 1; // Convert to zero-base index
if (idx >= 0 && idx < numOfStudent.length()) {
numOfStudent[idx]++;
}
Finally, out of for loop, just process them. Because each class contains maximum 3 student, we have:
int numOfMusicClass = (int)Math.ceil(numOfStudent[music - 1] / 3.0);
// ... Do the same for other class
Hopefully, this solution help you!
In addition, your class type is defined by number, thus, you should print out what number represents. For example:
Insert student in class (1 - music, 2 - art, 3 - theatre, 4 - sport):
It will make user aware what he/she input.

Here is a much shorter code:
public class GroupActivity
{
public static void main()
{
Scanner GActivity=new Scanner(System.in);
System.out.println("Insert numbers of participants:");
int participantNo= GActivity.nextInt();//Insert numbers of participants
int music= 1;int art=2; int theatre= 3; int sport= 4; // Representation of each class by numbers.
int[] counts = new int[4]; //This variable contains the number of the participants in music, arts, theatre and sports classes in its 4 cells.
for(int i=0;i<participantNo;i++)
{
System.out.println("Insert student in class:");
int p= GActivity.nextInt();// // Representation of student by number.int
if(p<=4)
counts[p-1]++;
}
System.out.println("The number of rooms for Music is:" + Math.ceil(counts[music-1]/3.0));
System.out.println("The number of rooms for Art is:" + Math.ceil(counts[art-1]/3.0));
System.out.println("The number of rooms for Theatre is:" + Math.ceil(counts[theatre-1]/3.0));
System.out.println("The number of rooms for Sports is:" + Math.ceil(counts[sport-1]/3.0));
}
}

Write smaller functions. This is too big to read.

Related

User Input to determine the length of an array in Java

I am currently taking an intro to java class at my school due to my growing interest in programming.
I am to create a program that takes user input for a min and max integer. I am also to take user input for the size of the array as well as whether or not the user would like both the sorted and unsorted lists printed out.
After I collect this information, I need to generate random values within the given min/max range and sort those values(I had no problem completing these steps).
My code:
//Third Project by John Mitchell
package thirdProject;
//Imported library
import java.util.*;
//First class
public class thirdProject {
//Created scanner and random class as well as variables
public static Scanner scan = new Scanner(System.in);
public static Random rand = new Random();
public static int min, max, rand_num, sum, total, temp, i, j;
public static boolean sorted;
public static int[] values = new int[];
//Allowing for the average output to be of type double
public static double average;
//Main method
public static void main(String[] args) {
//Prompt user to enter minimum value to be sorted
System.out.println("Please enter a minimum value: ");
min = scan.nextInt();
//Prompt user to enter maximum value to be sorted
System.out.println("\nPlease enter a maximum value: ");
max = scan.nextInt();
//Prompt user to enter total number of values to be sorted
System.out.println("\nPlease enter the number of values that you would like sorted: ");
total = scan.nextInt();
//Prompt the user whether or not they would like both lists
System.out.println("\nWould you like to see both the sorted and unsorted lists? Please enter 'True' for yes or 'False' for no.");
sorted = scan.nextBoolean();
//Prints lists that were generated
if (sorted == true) {
gen_random_val();
System.out.println("\nThe unsorted list is: " + Arrays.toString(values) + ".");
sort_values();
System.out.println("\nThe sorted list is: " + Arrays.toString(values) + ".");
} else {
gen_random_val();
sort_values();
System.out.println("\nThe sorted list is: " + Arrays.toString(values) + ".");
}
}
//Second method
public static void gen_random_val() {
//For loop that generates values within the range of values given
for(int i = 0; i < values.length; i++) {
values[i] = rand_num = Math.abs(rand.nextInt(max) % (max - min + 1) + min);
sum = sum + values[i];
average = (sum*1.0) / values.length;
}
}
//Third method
public static void sort_values() {
//For loop that sorts values
for(i=0; i<(total-1); i++) {
for(j=0; j<(total-i-1); j++) {
if(values[j] > values[j+1]) {
temp = values[j];
values[j] = values[j+1];
values[j+1] = temp;
}
}
}
}
}
Currently, the hard codes length of 10 values in the array works fine as I have recycled part of my code from a previous project. I am looking for guidance on how to simply make the size determined by user input.
Thank you.
For example you can do this:
//Prompt user to enter total number of values to be sorted
System.out.println("\nPlease enter the number of values that you would like sorted: ");
total = scan.nextInt();
values = new int[total];
You don't have to give values to variables when you declare them.

How to change a 2D Array into an ArrayList in Java

I'm a beginner when it comes to ArrayLists, so i'm sort of confused how I would be able to turn a 2D array into a ArrayList. I'm currently writing a program that reserves theatre seats, but i'm using a 2D array for the Rows and the seats in the row, but I want to use an ArrayList instead of the 2D array. I can't find anything else on this whenever I try to search for it. I have 2 other classes which are the getters and setters for the selling and reserving of the tickets, and a main class for the menu and switch statement. Thanks!
import java.util.Scanner;
/**
*/
public class Theatre {
//Number of rows in the theatre
public static final int NUMBER_ROWS = 10;
//Number of seats that are in each row
public static final int NUMBER_OF_SEATS_IN_ROW = 15;
private Seat[][] seat = new Seat[NUMBER_ROWS][NUMBER_OF_SEATS_IN_ROW];
public Theatre(){
for(int x=0;x<seat.length;x++){
for(int y=0;y<seat[x].length;y++){
seat[x][y] = new Seat();
if(x<5){ // If row is less than 5, set price of seat to 100
seat[x][y].setPrice(100);
}else{ // If row is not less than 5, set price to 70
seat[x][y].setPrice(70);
}
}
}
}
/**
* This method prompts for row and seat number and reserves it under a name if it is not already reserved
*/
public void reserveSeat(){
Scanner input = new Scanner(System.in);
int row;
int seat;
//Gathering row number with validation
do{
System.out.print("Please select row: ");
row = input.nextInt();
row--;
}while(row<0||row>=NUMBER_ROWS);
//Gathering seat number with validation
do{
System.out.print("Please select seat: ");
seat = input.nextInt();
seat--;
}while(seat<0||seat>=NUMBER_OF_SEATS_IN_ROW);
if(row<5){
System.out.println("Price: $100");
}else{
System.out.println("Price: $70");
}
if(this.seat[row][seat].isSold()){ // If seat is reserved, display message
System.out.println("This seat is reserved");
}else{ // If seat is not reserved, prompt for name and reserve it
System.out.print("Please enter your name to reserve seat: ");
this.seat[row][seat].setReservedBy(input.next());
this.seat[row][seat].setSold(true);
}
}
/**
* This method displays all the seats and gives a visual representation of which seats are reserved
*/
public void showReservations(){
String output = "";
for(int x=0;x<seat.length;x++){
for(int y=0;y<seat[x].length;y++){
if(seat[x][y].isSold()){ // If seat is sold, append "x"
output += "x ";
}else{ // If seat is not sold, append "o"
output += "o ";
}
}
output += "Row "+(x+1)+"\n"; // Append newline character when row is complete
}
System.out.println(output);
}
/**
* This method calculates the total value of seats sold and displays it
*/
public void showTotalValue(){
double totalValue = 0;
for(int x=0;x<seat.length;x++){
for(int y=0;y<seat[x].length;y++){
if(seat[x][y].isSold()){ // If seat is sold, add price of seat to totalValue
totalValue += seat[x][y].getPrice();
}
}
}
System.out.println("The total value of seats sold is $"+totalValue);
}
}
You may want to build a list of lists, like so:
List<List<Seat>> seats = new ArrayList<List<Seat>>();
You could then add more rows like so:
seats.add(new ArrayList<Seat>);
And get the seat object like so:
seats.get(row).get(column);
You also might be able to find more information here: 2 dimensional array list
You create an ArrayList<ArrayList<Seat>> like so:
public class Theatre {
//Number of rows in the theatre
public static final int NUMBER_ROWS = 10;
//Number of seats that are in each row
public static final int NUMBER_OF_SEATS_IN_ROW = 15;
// Passing NUMBER_ROWS to the constructor sets aside that much space
// but the array is still empty.
private ArrayList<ArrayList<Seat>> seat = new ArrayList<ArrayList<Seat>>(NUMBER_ROWS);
public Theatre(){
for(int x=0; x NUMBER_ROWS; x++){
seat.add(new ArrayList<Seat>(NUM_OF_SEATS_IN_ROW);
for(int y=0; y < NUMBER_OF_SEATS_IN_ROW; y++){
seat.get(x).add(new Seat());
// etc.
}
}
}
}

for loop resets construct inputs

for the following code:
System.out.println("How many types of food do the gerbils eat?");
int F = keyboard.nextInt();
food = new food[F];
for
(int a = 0; a<F; a++){
System.out.println("Name of food number " + (a+1));
foodname = keyboard.next();
System.out.println("Max amount of food " + (a+1));
maximum = keyboard.nextInt();
food[a] = new food(foodname, maximum);
for (int n = 0; n<F; n++){
System.out.println(food[n]);
}
}
I get the following output:
How many types of food do the gerbils eat?
2
Name of food number 1
p
Max amount of food 1
5
p 5
null
Name of food number 2
r
Max amount of food 2
5
r 5
r 5
As you can see, every time the loop restarts, the new input values for food name and food maximum are reset. why is it doing that, and how do i fix it so that it stores my original input for food 1 name and maximum?
Class food:
public class food {
public static String foodname;
public static int maximum;
public food(String foodname, int maximum) {
this.foodname = foodname;
this.maximum = maximum;
}
public String getFood(){
return foodname;
}
public int getmaxamount(){
return maximum;
}
public String toString() {
return (this.getFood() + " " + this.getmaxamount());
}
}
In your Food class, you declared
foodname
maximum
as static.
It means, those values will be the same for every Food you create.
As you want different kind of Food, simply remove those modifiers
Although this question has already been answered, I thought I'd go ahead and add this:
Sometimes, you want to have variables that are common to all objects. This is accomplished with the static modifier. Fields that have the static modifier in their declaration are called static fields or class variables. They are associated with the class, rather than with any object. Every instance of the class shares a class variable, which is in one fixed location in memory.
Link: http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html

Novice at Java. Loop to enter height of people and find tallest

I am studying loops and am attempting a sample question here to use only a loop to ask the user to enter in the name of the person, height in feet first, then inches and then to find the tallest. I understand how to do the majority of it.
Could anyone point out where I am going wrong? I began writing the code and realised that I can't declare the persons names without knowing how many people the user will enter. I can't get my head around it.
I want to prompt the user with the questions but also update it to person [2], person [3], person [4] etc. depending on how many people they entered in initially.
Apologies for not wording this correctly. Any help is appreciated. I understand lines 10, 11 and 12 are probably wrong.
class HeightTest
{
public static void main(String[] args)
{
int noOfPeople;
int index;
int feet;
int inches;
String personOne;
String personTwo;
String personThree;
System.out.print("Enter a number of people ");
noOfPeople = EasyIn.getInt();
for (index = 1; index <=noOfPeople; index++)
{
System.out.println("Enter the name of person " + index);
personOne = EasyIn.getString();
System.out.println("Enter feet portion for " + personOne);
feet = EasyIn.getInt();
System.out.println("Enter inches portion for " + personOne);
inches = EasyIn.getInt();
}
}
}
You have a very good start. All you need to do now is keep track of the heights that are entered, and compare them to the largest one input so far. If the height for the current loop iteration is larger than the current largest, store it as the largest.
In pseudocode:
int largestHeightInches = 0;
for( i = 1; i <= noOfPeople; index++ ) {
currentHeightFeet = GetInt();
currentHeightInches = GetInt();
currentHeight = currentHeightInches + currrentHeightFeet * 12;
if( largestHeightInches < currentHeight ) {
largestHeightInches = currentHeight;
}
}
You would have to create an array of Persons to acheive what you want.
Here's a snippet.
Create a class called Person
public class Person
{
int index;
int feet;
int inches;
String name;
}
create a main Test class to contain your main method, and do something like this
public class Main{
public static void main (String[] args)
{
// get the number of people in noOfPeople as you do now.
Person[] pArray= new Person[nOfPeople]
for(Person p: pArray)
{
System.out.println("Enter the name of person " + index);
p.name = EasyIn.getString();
// ...etc
}
}
}

Beginner Java (getting class assignment to compile)

This is a lab I am working for for a CSE 201. The program is supposed to read information about students and their scores from a file, and output the name of each student with all his/her scores and the total score, plus the average score of the class, and the name and total score of the students with the highest and lowest total score.
The exact assignment can be seen here.
I'm having a little trouble getting it to compile, especially with the variable "students".
Any help would be great.
/*
* The program will read information about students and their
* scores from a file, and output the name of each student with
* all his/her scores and the total score, plus the average score
* of the class, and the name and total score of the students with
* the highest and lowest total score.
*/
import java.util.Scanner;
public class Lab7
{
public static void main(String[] args)
{
// Input file name
Scanner in = new Scanner(System.in);
String filename = getFileName(in);
// Input number of students
int Student[students] = getStudents(FileIOHelper.getNumberOfStudents(filename));
// Input all students records and create Student array and
// integer array for total scores
int[] totalScores = new int[students.length];
for(int i = 0; i < students.length; i++){
for(int j = 1; j < 4; j++){
totalScores[i] += students[i].getScore(j);
}
}
// Compute total scores and find students with lowest and
// highest total score
int maxIndex = 0, minIndex = 0;
for(int i = 0; i < students.length; i++){
if(totalScores[i] > totalScores[maxIndex]){
maxIndex = i;
}else if(totalScores[i] < totalScores[minIndex]){
minIndex = i;
}
}
// Compute average total score
int average = 0;
for(int i = 0; i < totalScores.length; i++){
average += totalScores[i];
}
average /= students.length;
// Output results
outputResults(students, totalScores, maxIndex, minIndex, average);
}
// Given a Scanner in, this method prompts the user to enter
// a file name, inputs it, and returns it.
private static String getFileName(Scanner in)
{
System.out.print("Enter input file name: ");
return in.nextLine();
}
// Given the number of students records n to input, this
// method creates an array of Student of the appropriate size,
// reads n student records using the FileIOHelper, and stores
// them in the array, and finally returns the Student array.
private static Student[] getStudents(int n)
{
Student[] student = new Student[n];
for(int i = 0; i < student.length; i++){
student[i] = FileIOHelper.getNextStudent();
}
return student;
}
// Given an array of Student records, an array with the total scores,
// the indices in the arrays of the students with the highest and
// lowest total scores, and the average total score for the class,
// this method outputs a table of all the students appropriately
// formatted, plus the total number of students, the average score
// of the class, and the name and total score of the students with
// the highest and lowest total score.
private static void outputResults(
Student[] students, int[] totalScores,
int maxIndex, int minIndex, int average
)
{
System.out.println("\nName \t\tScore1 \tScore2 \tScore3 \tTotal");
System.out.println("--------------------------------------------------------");
for(int i = 0; i < students.length; i++){
outputStudent(students[i], totalScores[i], average);
System.out.println();
}
System.out.println("--------------------------------------------------------");
outputNumberOfStudents(students.length);
outputAverage(average);
outputMaxStudent(students[maxIndex], totalScores[maxIndex]);
outputMinStudent(students[minIndex], totalScores[minIndex]);
System.out.println("--------------------------------------------------------");
}
// Given a Student record, the total score for the student,
// and the average total score for all the students, this method
// outputs one line in the result table appropriately formatted.
private static void outputStudent(Student s, int total, int avg)
{
System.out.print(s.getName() + "\t");
for(int i = 1; i < 4; i++){
System.out.print(s.getScore(i) + "\t");
}
System.out.print(total + "\t");
if(total < avg){
System.out.print("-");
}else if(total > avg){
System.out.print("+");
}else{
System.out.print("=");
}
}
// Given the number of students, this method outputs a message
// stating what the total number of students in the class is.
private static void outputNumberOfStudents(int n)
{
System.out.println("The total number of students in this class is: \t" + n);
}
// Given the average total score of all students, this method
// outputs a message stating what the average total score of
// the class is.
private static void outputAverage(int average)
{
System.out.println("The average total score of the class is: \t" + average);
}
// Given the Student with highest total score and the student's
// total score, this method outputs a message stating the name
// of the student and the highest score.
private static void outputMaxStudent(
Student student,
int score
)
{
System.out.println(student.getName() + " got the maximum total score of: \t" + score);
}
// Given the Student with lowest total score and the student's
// total score, this method outputs a message stating the name
// of the student and the lowest score.
private static void outputMinStudent(
Student student,
int score
)
{
System.out.println(student.getName() + " got the minimum total score of: \t" + score);
}
}
First of all: it's always useful to actually pay attention to the compiler error. Java's compier errors are very clear and useful most of the time, and tell you exactly what's wrong once you're learned to understand them. And generally, it's much easier for people here on SO to help you if you include the actual text of an error rather than saying "I have trouble getting it to compiler"
This is the first obviously wrong line:
int Student[students] = getStudents(FileIOHelper.getNumberOfStudents(filename));
A variable declaration in Java consists of (slightly simplified):
The type of the variable
its name
optionally an assignment of an initial value
In the above line, you start with type int, but the next part Student[students] makes no sense - it looks like an array instantiation, certainly not a name. What you probably meant is:
Student[] students = getStudents(FileIOHelper.getNumberOfStudents(filename));
i.e. the type is Student[] (an array of Student objects), the name is 'students', and it's assigned the return value of the getStudents() method. An int is not involved anywhere (you don't have to specify the size of the array here, since it is created inside the getStudents() method).
The size of your array cannot be specified on the lefthand side.
The student array declaration should look like this:
int noOfStudents = FileIOHelper.getNumberOfStudents(filename);
//create an array of students of the given length
Student[] students = new Student[noOfStudents];
This part looks to be an issue:
// Input number of students
int Student[students] = getStudents(FileIOHelper.getNumberOfStudents(filename));
You probably want to first get the number of students, then use that variable to call getStudents. Also, if you want the array to be called students it should not be in the brackets.
Student[] students = .....
The line where you're having trouble is the very first line at the top of main():
int Student[students] = getStudents(FileIOHelper.getNumberOfStudents(filename));
I always recommend reading through a problematic line with the same mindset as a compiler: it doesn't know anything except what you've told it, top to bottom, left to right.
So let's start at the beginning:
int
I know what an int is! You want to declare one! Awesome! Moving on...
Student
What the heck is a Student? I don't see anywhere in the code that would tell me what that is! As a human, I can infer that it's supposed to be the name of a class, since class names are always capitalized in Java, but it's not declared so the compiler cannot be sure. Is it perhaps supposed to be the name of this class (instead of Lab7)?
More importantly, if it is a class then you have just named two datatypes in a row: int and Student. Which type did you intend to use? Presumably if you want a list of Students, the int is not relevant at all. If you want the number of students, then just the int is relevant.
Moving on:
students
What the heck is a students? I again don't see anywhere in the code that would tell me what that is!
Let's back away for a moment. What are you really trying to do here? You're trying to obtain an array of all the students in the file. The getStudents() function presumably achieves that. (It may be buggy, but that's not our problem at the moment. We're just calling it here, so we will assume that it works.)
But how are you supposed to know how big to make the array if you haven't yet read it? Conveniently, you don't have to know! You can simply write:
Student[]
You are instantiating the array down in getStudents(), and there you've correctly given it a size. Here in main() you're simply declaring it, and no size is necessary.
Okay, so can you just write:
Student[] = getStudents(FileIOHelper.getNumberOfStudents(filename));
No, 'cause your variable doesn't have a name. How about something like this:
Student[] students = getStudents(FileIOHelper.getNumberOfStudents(filename));
I suspect that's what you intended, but since you got stuck somewhere along the way it's important to be able to get "unstuck," and mentally walking through what the compiler sees is a useful way to do that.

Categories

Resources