how to position this java while loop? - java

So the while loop is not working, even though it compiles.  How do I position it correctly??
I tried a few things but they kinda worked. if someone on here can help me out that would be great
import java.util.Scanner;
//This is a Driver program to test the external Class named Student
public class StudentDriver //BEGIN Class Definition
{
//**************** Main Method*************************
public static void main (String[] args)
{Scanner scan = new Scanner(System.in);
//Data Definitions:
//Instance Data
String courseName;
int courseCredits;
String name;
String id;
String street;
String city;
String state;
String zip;
String major;
//Executable Statements:
//Initialize first Student
name = "Fred Fergel";
id = "0123";
street = "123 Main Street";
city = "Smalltown";
state = "NY";
zip = "12345";
major = "Computer Science";
//instantiate the Student object
Student student1 = new Student(name, id, street, city, state, zip, major);
//Test toString
System.out.println("Student 1\n\n" + student1.toString());
//Print a blank line
System.out.println();
//Add a course
student1.addCourse("CSC111", 4);//NOTE:  DO NOT PUT A SPACE BETWEEN CSC AND 111
//Print schedule
System.out.println("Student 1's Schedule:\n\n");
student1.displaySchedule();//call method
final String FLAG = "Y";
String prompt = "Y";
while (prompt.equals("y"))
{
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);
System.out.println("Do you wish to enter another course? y/n");
prompt = scan.next();
}
//end while
}//end main
}//end StudentDriver
Here is the student class:
import java.util.Scanner;
public class Student
{Scanner scan = new Scanner(System.in);
//Instance Data
String studentName;
String studentID;
String streetAddress;
String city;
String state;
String zipCode;
String major;
int totalCredits;
final int SIZE = 6;
final int MAX_CREDITS = 18;
String [ ] schedule = new String [SIZE];
int courseNumber = 0; //start out with no courses
//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;
}
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 10 courses
{
System.out.println("You have exceeded 10 courses.");
}//end courseNumber
}//addCourse
//Method to display the schedule
//-------------------------------------------------------
// Will only print out the courses added to the array.
//-------------------------------------------------------
public void displaySchedule( )
{
for (int index = 0; index < courseNumber; index++)
{
System.out.println("Course #" + (index + 1) + " " + schedule[index] + "\n");
}//end for
}//end display schedule
}

String prompt = "Y";
while (prompt.equals("y"))
Y and y are not the same thing. You need to use .equalsIgnoreCase() instead of .equals() if you want it to ignore case.

Related

Accepting User Input for Getter Class in Java

Java newbie here, I have one of those assignments where I need to write a class for creating student objects and then also write a driver.
I have all of the requirements done, except I am having trouble with this one - "Write method getTestScore that accepts test number and returns appropriate score."
I believe I've written the class correctly, but I am having trouble writing the code for the driver.
After the prompt for the user to enter the test number, it isn't returning anything and the program terminates insted of returning appropriate score .
Help is very appreciated!
Here is the class:
public class Student
{
private String firstName, lastName;
private String homeAddress, schoolAddress;
private int testScore1, testScore2, testScore3;
//Constructors
public Student()
{
firstName = "None";
lastName = "None";
homeAddress = "None";
schoolAddress = "None";
testScore1 = 0;
testScore2 = 0;
testScore3 = 0;
}
public Student(String first, String last, String home, String school, int score1, int score2, int score3)
{
firstName = first;
lastName = last;
homeAddress = home;
schoolAddress = school;
testScore1 = score1;
testScore2 = score2;
testScore3 = score3;
}
//Setter for test scores
public void setTestScore(int testNum, int score)
{
if (testNum == 1)
testScore1 = score;
else
if (testNum == 2)
testScore2 = score;
else
if (testNum == 3)
testScore3 = score;
else
throw new IllegalArgumentException(testNum + " is out of range");
}
//Getter for test scores
public int getTestScore(int testNum2)
{
if (testNum2 == 1)
return testScore1;
else
if (testNum2 == 2)
return testScore2;
else
if (testNum2 == 3)
return testScore3;
else
throw new IllegalArgumentException(testNum2 + " is out of range");
}
//Calculates average for each student
public int getAverage()
{
int average = (testScore1 + testScore2 + testScore3)/3;
return average;
}
//Returns a description of this Student object
public String toString()
{
String result;
result = firstName + " " + lastName + "\n";
result += "Home Address:\n" + homeAddress + "\n";
result += "School Address:\n" + schoolAddress + "\n";
result += "Test Score 1:\n" + testScore1 + "\n";
result += "Test Score 2:\n" + testScore2 + "\n";
result += "Test Score 3:\n" + testScore3 + "\n";
result += "Average Test Score:\n" + ((testScore1+testScore2+testScore3)/3);
return result;
}
}
And here is the driver:
package lab7;
import java.util.Scanner;
public class StudentBody {
public static void main(String[] args)
//Create student objects
{
Student snm24 = new Student("Sarah", "M", "18 79th Street", "5000 Forbes Ave.", 95, 80, 63);
Student adk28 = new Student("Andrew", "K", "16 Collins Ave.", "16401 NW 37th Ave.", 90, 82, 76);
//Get average for snm24
snm24.getAverage();
System.out.println("snm24 average initial: " + snm24.getAverage());
//Set new test score for test 3 for snm24 and see new average
snm24.setTestScore(3, 68);
System.out.println("snm24 average after adjustment: " +snm24.getAverage());
//Get test score for adk28
Scanner scan = new Scanner(System.in);
System.out.println("Which test score are you looking for?:");
int testNum2 = scan.nextInt();
adk28.getTestScore(testNum2);
}
}
it isn't returning anything and the program terminates. Help is very appreciated!
this here>
adk28.getTestScore(testNum2);
the returned value is getting lost.. do something with that, print it, assign it to a variable:
int result = adk28.getTestScore(testNum2);

stack overflow error when using constructor with 2D dynamic graphic [duplicate]

Please excuse what is probably a very basic question, but I am writing a program to store employee info and it works fine until it tries to set the info inside my employee class. It gives a stackoverflow error and I cannot figure out why. Thanks for any help.
Main class:
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner Input = new Scanner(System.in);
System.out.println("Enter the number of employees to enter.");
int employeeCount = Input.nextInt();
Input.nextLine();
Employee employee[] = new Employee[employeeCount];
String namesTemp;
String streetTemp;
String cityTemp;
String stateTemp;
String zipCodeTemp;
String address;
String dateOfHireTemp;
for(int x = 0; x < employeeCount; x++)
{
System.out.println("Please enter the name of Employee " + (x + 1));
namesTemp = Input.nextLine();
System.out.println("Please enter the street for Employee " + (x + 1));
streetTemp = Input.nextLine();
System.out.println("Please enter the city of Employee " + (x + 1));
cityTemp = Input.nextLine();
System.out.println("Please enter the state of Employee " + (x + 1));
stateTemp = Input.nextLine();
System.out.println("Please enter the zip code of Employee " + (x + 1));
zipCodeTemp = Input.nextLine();
address = streetTemp + ", " + cityTemp + ", " + stateTemp + ", " + zipCodeTemp;
System.out.println("Please enter the date of hire for Employee " + (x + 1));
dateOfHireTemp = Input.nextLine();
System.out.println("The employee ID for employee " + (x + 1) + " is " + (x + 1));
employee[x] = new Employee(x, namesTemp, address, dateOfHireTemp);
}
}
}
Employee class:
public class Employee
{
private int employeeID;
private Name name;
private Address address;
private DateOfHire hireDate;
public Employee()
{
}
public Employee(int employeeID, String name, String address, String hireDate)
{
String temp;
Name employeeName = new Name(name);
this.employeeID = employeeID;
}
}
Name class:
public class Name
{
public Name name;
public Name(String name)
{
Name employeeName = new Name(name);
this.name = employeeName;
}
}
The most common cause of StackoverflowExceptions is to unknowingly have recursion, and is that happening here? ...
public Name(String name)
{
Name employeeName = new Name(name); // **** YIKES!! ***
this.name = employeeName;
}
Bingo: recursion!
This constructor will create a new Name object whose constructor will create a new Name object whose constructor will... and thus you will keep creating new Name objects ad infinitum or until stack memory runs out. Solution: don't do this. Assign name to a String:
class Name {
String name; // ***** String field!
public Name(String name)
{
this.name = name; // this.name is a String field
}
Typically a class is used to group data together with functionality. It appears that the Name class is simply a wrapper for a String without adding any functionality. At this point in your Java career, it is probably better to declare String name; in the Employee class and remove the Name class all together. (Note that this would remove the error from your code that Hovercraft Full of Eels described.)

object array index value is being overided by the preceding index value

This is an odd situation for me, I just started learning Java OOP.
I made a class looks like this
public class Student {
public static String name;
public static int marks;
public Student(String n, int m){
name = n;
marks = m;
}
public static void printProperties(){
System.out.println("Name = " + name + " , marks = " + m);
}
}
As you can see the constructor accepts two data: name and marks.
in my main method
System.out.println("Please enter number of students:");
int n = scan.nextInt();
Student[] stu = new Student[n];
String name;
int marks = 0;
for(int i = 0; i < stu.length; i++){
System.out.println("Please enter name for student #" + (i+1));
name = scan.next();
System.out.println("Please enter marks for student #" + (i+1));
marks = scan.nextInt();
stu[i] = new Student(name,marks);
System.out.println();
}
//Display
for(int x = 0; x < stu.length; x++){
System.out.println("#" + (x+1) + " Name: " + stu[x].name + ", Marks: " + stu[x].marks);
}
So my output as follows:
Please enter number of students:
2
Please enter name for student #1
tom
Please enter age for student #1
20
Please enter name for student #2
billy
Please enter age for student #2
80
#1 Name: billy, Marks: 80
#2 Name: billy, Marks: 80
It should be:
#1 Name: tom, Marks: 20
#2 Name: billy, Marks: 80
Why is the preceding index value overidding its previous index value?
You code should work absolutely fine, if your Student class looks something like this :
public class Student{
String name;
int marks;
public Student(String name, int marks){
this.name = name;
this.marks = marks;
}
}
EDITED :
This is what Jon Skeet mentioned.
You are using static variables which are class level variables, so they are overridden every time you assign value to them and only the last value is retained.
You need instance variables here.
Do not make your fields static, and let's use private to control access -
public class Student {
private String name; // not static, and use private.
private int marks;
public Human(String n, int m){
name = n;
marks = m;
}
public void printProperties(){ // also should not be static.
System.out.println("Name = " + name + " , marks = " + m);
}
}
Don't use static , simple as that
A static variable belongs to the entire class. It is one variable that is shared among all of the objects. So when you change that variable, it changes it for all the objects.
Instead, define name and marks as instance variables. In other words, remove the static modifier from your variable declarations. An instance variable is unique to each object. Each object has its own copy of an instance variable.
Also, it's good practice to declare name and marks as private. Then create getters and setters for those variables. This hides the implementation.
import java.util.Scanner;
public class Student{
private String name;
private int marks;
public String getName() { //getter
return name;
}
public void setName(String name) { //setter
this.name = name;
}
public int getMarks() { //getter
return marks;
}
public void setMarks(int marks) { //setter
this.marks = marks;
}
public Student(String n, int m){
name = n;
marks = m;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter number of students:");
int n = scan.nextInt();
Student[] stu = new Student[n];
String name;
int marks = 0;
for(int i = 0; i < stu.length; i++){
System.out.println("Please enter name for student #" + (i+1));
name = scan.next();
System.out.println("Please enter marks for student #" + (i+1));
marks = scan.nextInt();
stu[i] = new Student(name,marks);
System.out.println();
}
//Display
for(int x = 0; x < stu.length; x++){
System.out.println("#" + (x+1) + " Name: " + stu[x].getName() + ", Marks: " + stu[x].getMarks());
}
scan.close();
}
}

How can I combine an extra variable to an array/method?

I have created a simple program which outputs student details. Ideally I would like to give the user an option to add both courses. Will this require a lot of messing about changing code? If not can someone help?
class Student
{
public static void main(String[]args)//The main method; starting point of the program.
{
Scanner input = new Scanner(System.in);
String surName, foreName, courseName;
int age,telephone;
System.out.println("\t\t\t***********************************************");
System.out.println("\t\t\tWelcome to the Mobile College's Student Records");
System.out.println("\t\t\t***********************************************");
System.out.println("\nHow many students would you like to add?");
int noStudents = input.nextInt();
Stu [] TheStu = new Stu [noStudents];
for (int x = 0; x < noStudents; x++)
{
System.out.println("Please enter Surname: ");
surName = input.next();
System.out.println("Please enter Forename: ");
foreName = input.next();
System.out.println("Please enter Age: ");
age = input.nextInt();
System.out.println("Please enter Telephone No. ");
telephone = input.nextInt();
System.out.println("Which course do you want to add the student to? .......Literacy or Numeracy ");
courseName = input.next();
TheStu [x] = new Stu (surName, foreName, age, telephone, courseName);
}
for (int y = 0; y < noStudents; y++)
{
System.out.println("\t\t\t***********************************************");
System.out.println ("\t\t\tName: " + TheStu[y].getfName() + " " + TheStu[y].getsName());
System.out.println ("\t\t\tAge: " + TheStu[y].getstuAge());
System.out.println ("\t\t\tTelephone No. 0" + TheStu[y].getphone());
System.out.println ("\t\t\tEnrolled on the " + TheStu[y].getcourseType() + " Course.");
System.out.println("\t\t\t***********************************************");
}
}// end of class
}
class Stu
{
private String sName;
private String fName;
private int stuAge;
private int phone;
private String courseType;
Stu (String s, String f, int a, int p, String c)
{
sName = s;
fName = f;
stuAge = a;
phone = p;
courseType = c;
}
String getsName()
{
return sName;
}
String getfName()
{
return fName;
}
int getstuAge()
{
return stuAge;
}
int getphone()
{
return phone;
}
String getcourseType()
{
return courseType;
}
}
If you want something pretty basic, you could change your courses into a String array so you could store both courses. Also when asking the user to input a course name, you could have an ALL option, so you automatically register the student for all courses. See below for a slightly modified version of your code :
import java.util.Scanner;
class Student
{
public static void main(String[] args)//The main method; starting point of the program.
{
Scanner input = new Scanner(System.in);
String surName, foreName, courseName;
String[] courses = new String[]{};
int age,telephone;
System.out.println("\t\t\t***********************************************");
System.out.println("\t\t\tWelcome to the Mobile College's Student Records");
System.out.println("\t\t\t***********************************************");
System.out.println("\nHow many students would you like to add?");
int noStudents = input.nextInt();
Stu [] TheStu = new Stu [noStudents];
for (int x = 0; x < noStudents; x++)
{
System.out.println("Please enter Surname: ");
surName = input.next();
System.out.println("Please enter Forename: ");
foreName = input.next();
System.out.println("Please enter Age: ");
age = input.nextInt();
System.out.println("Please enter Telephone No. ");
telephone = input.nextInt();
System.out.println("Which courses do you want to add the student to? .......Literacy or Numeracy or both ");
courseName = input.nextLine();
// change to either upper case or lower case for easy treatment
courseName = courseName.toUpperCase();
// Also verify that the user entered a valid course name
if(courseName.equals("LITERACY")){
courses = new String[]{"LITERACY"};
} else if(courseName.equals("NUMERACY")){
courses = new String[]{"NUMERACY"};
} else if(courseName.equals("BOTH")){
courses = new String[]{"LITERACY", "NUMERACY"};
} else{
System.out.println("Error : You entered an invalid option.... \n This student won't be registered for any courses");
}
TheStu [x] = new Stu (surName, foreName, age, telephone, courses);
}
for (int y = 0; y < noStudents; y++)
{
System.out.println("\t\t\t***********************************************");
System.out.println ("\t\t\tName: " + TheStu[y].getfName() + " " + TheStu[y].getsName());
System.out.println ("\t\t\tAge: " + TheStu[y].getstuAge());
System.out.println ("\t\t\tTelephone No. 0" + TheStu[y].getphone());
System.out.println ("\t\t\tEnrolled in the following courses : ");
courses = TheStu[y].getcourseTypes();
for(int i = 0; i < courses.length; i++){
System.out.println(courses[i]);
}
if(courses.length < 1){
System.out.println("No Courses");
}
System.out.println("\t\t\t***********************************************");
}
}// end of class
}
class Stu
{
private String sName;
private String fName;
private int stuAge;
private int phone;
private String[] courseTypes;
Stu (String s, String f, int a, int p, String[] c)
{
sName = s;
fName = f;
stuAge = a;
phone = p;
courseTypes = c;
}
String getsName()
{
return sName;
}
String getfName()
{
return fName;
}
int getstuAge()
{
return stuAge;
}
int getphone()
{
return phone;
}
String[] getcourseTypes()
{
return courseTypes;
}
}
I tried as much as possible not to make any serious changes to your code as i assume you're a beginner, but there are a lot of changes you could make to improve your code. Happy Coding :)
When you ask for the course name, keep asking until they have entered in a sentinal value. Inside Stu keep an List<String> courseTypes. Store the entered courses in courseTypes. Also, you may want to add a set value to some of the fields in Stu. What if their phone number changes?

Java: coding that uses a variable to specify array length?

I am working on a student scores application that accepts the last name, first name and score for one or more students and stores the results in an array. Then it prints the students and their scores in alphabetical order by last name. We do not know how many students there are, but there will be fewer than 100.
We have to display the class average at the end of the student information and display a message after each student whose grade is more than 10 points below the class average.
My first issue is that I have created a do/while loop to ask if the user would like to enter another but it will not work!?!?
Second, I can not figure out how to display the "10 points below" message on individual students.
public class Student implements Comparable
{
String firstName;
String lastName;
int score;
//stores last name, first name and score for each student
public Student(String lastName,String firstName,int score)
{
this.lastName = lastName;
this.firstName = firstName;
this.score = score;
}
//implement the comparable interface so students can be sorted by name
public int compareTo(Object o)
{
Student otherStudent = (Student)o;
if(otherStudent.lastName.equals(lastName))
{
return firstName.compareToIgnoreCase(otherStudent.firstName);
}
else
{
return lastName.compareToIgnoreCase(otherStudent.lastName);
}
}
public String toString()
{
return lastName + ", " + firstName + ": " + score;
}
}
import java.util.Scanner;
import java.util.Arrays;
public class StudentApp
{
static Scanner sc = new Scanner(System.in);
public static void main(String [] args)
{
Student [] studentArray;
String lastName;
String firstName;
int score = 0;
double average = 0;
System.out.println("Welcome to the Student Scores Application.");
System.out.println();
do{
//code that uses variable to specify the array length
int nStudent = 100; //array size not set unit run time
studentArray = new Student[nStudent];
for (int i=0; i<nStudent; i++)
{
System.out.println();
lastName = Validator.getRequiredString(sc,
"Student " + (i+1) + " last name: ");
firstName = Validator.getRequiredString(sc,
"Student " + " first name: ");
score = Validator.getInt(sc,
"Student " + " score: ",
-1, 101);
studentArray[i] = new Student(lastName, firstName, score);
double sum = 0.0;
sum += score;
average = sum/nStudent;
}
}while (getAnotherStudent());
Arrays.sort(studentArray);
System.out.println();
for (Student aStudent: studentArray)
{
System.out.println(aStudent);
if (score<= (average-10))
{
System.out.println ("Score 10 points under average");
}
}
System.out.println("Student Average:" +average);
}
public static boolean getAnotherStudent()
{
System.out.print("Another student? (y/n): " );
String choice = sc.next();
if (choice.equalsIgnoreCase("Y"))
return true;
else
return false;
}
}
There are a few problems here:
Every time through the do...while, you reinstantiate studentArray and sum. This means that all of your previously iterated over data is nuked when getAnotherStudent() is true - you want to instantiate the array and sum only once.
You don't stop if you have more than 100 students. You need an ending condition around nStudent as well in your loop.
You should make a few adjustments to getAnotherStudent() so that you can block on data, and wait when valid data is input - by using a loop:
public static boolean getAnotherStudent() {
Scanner sc = new Scanner(System.in);
System.out.print("Another student? (y/n): " );
if (sc.hasNext()) {
String choice = sc.next();
// blocks here - ignores all input that isn't "y" or "n"
while(!((choice.equalsIgnoreCase("Y") || choice.equalsIgnoreCase("N")))) {
if (choice.equalsIgnoreCase("Y")) {
return true;
}
System.out.print("Another student? (y/n): " );
choice = sc.next();
}
}
return false; // obligatory
Your code is close there are just a couple of problems. The reason why your do while loop is not working is that you have a for loop inside of it. This means that you will ask for 100 students before you ask if they want to add another one. Your sum is being created inside this loop so it will be reset each time.
Finally you do not know how many Students will be added but your code assumes there will be 100 Students. This means you cannot use the for each loop to go through the array as some could be null. Just use a regular for loop going up to the last index of a student you added. Here are the changes:
Student[] student = new Student[nStudent];
int studentCount = 0; //declear the counter outside the loop
double sum = 0.0; //declear the sum outside the loop
do {
System.out.println();
lastName = Validator.getRequiredString(sc,
"Student " + (i+1) + " last name: ");
firstName = Validator.getRequiredString(sc,
"Student " + " first name: ");
score = Validator.getInt(sc,
"Student " + " score: ",
-1, 101);
student[studentCount] = new Student(lastName, firstName, score);
sum += score; //increase the sum
studentCount++; //increment the counter
} while (studentCount < nStudent && getAnotherStudent()); //stop if the user says 'n' or we hit the maximum ammount
average = sum / studentCount; //work out the average outside the loop
System.out.println();
for (int i= 0; i< studentCount; i++ ) {
System.out.println(aStudent);
if (score <= (average - 10)) {
System.out.println("Score 10 points under average");
}
}
System.out.println("Student Average:" + average);
}
Your getAnotherStudent() method should read:
System.out.print("Another student? (y/n): " );
if (sc.hasNext()) { // blocks until user entered something
String choice = sc.next();
if (choice.equalsIgnoreCase("Y"))
return true;
else
return false;
} else {
// won't come here
return false;
}

Categories