I'm trying to reference the GPA in my StudentData class, however I'm getting an error that says it can't find the symbol on the line that says aStudent.gpa = studentGPA.
my main class:
public static void main (String [] args)
{
//local constants
final String QUIT = "Quit";
final String YES = "Y";
final int MODIFY_GPA = 1;
final int DISPLAY_USER = 2;
final int QUIT_MENU = 3;
//local variables
String name; //name of the user
String idPrompt; //asks the user if they want to input a gpa and id
String studentID; //student ID input by the user
float studentGPA; //student GPA input by the user
int choice; //prompts the user for a menu choice
Library myLib = new Library();
/****************** Start main method *******************/
//prompt for name of user or quit
System.out.print("Enter name of user(First and Last, Quit to end): ");
name = Keyboard.readString();
while(!QUIT.equals(name))
{
//ask the user if they want to enter ID and GPA
System.out.print("Do you want to enter an ID and GPA?(Y/N): ");
idPrompt = Keyboard.readString();
//if the user says yes
if(!YES.equals(idPrompt))
{
//instantiate a new Student with just the name
StudentData aStudent = new StudentData(name, "", 0);
}
else
{
//prompt the user for the ID
System.out.print("Enter the Student ID: ");
studentID = Keyboard.readString();
//prompt the user for the GPA
System.out.print("Enter the Student GPA: ");
studentGPA = Keyboard.readFloat();
//instantiate a new Student with all three data types
StudentData aStudent = new StudentData(name, studentID, studentGPA);
}
//clear the screen
myLib.clrscr();
//prompt user for a menu choice
choice = displayMenu();
//clear the screen
myLib.clrscr();
//begin while loop to modify the user or display
while(choice != QUIT_MENU)
{
//if the user wants to modify the GPA
if(choice == MODIFY_GPA)
{
studentGPA = StudentData.modifyGPA();
aStudent.gpa = studentGPA;
}
//if the user wants to display
else if(choice == DISPLAY_USER)
{
System.out.print("STUDENT OUTPUT");
//System.out.println(StudentData);
}
//if there was an invalid menu choice
else
{
System.out.print("INVALID DATA ENTERED");
}
//prompt for next choice
choice = displayMenu();
}
//prompt for name of user or quit
System.out.print("Enter name of user(First and Last, Quit to end): ");
name = Keyboard.readString();
}
}//end main method
and this is my StudentData class
public class StudentData
{
public String name;
public String id;
public float gpa;
//create a constructor that will receive the name of the student only
public StudentData(String inName)
{
//local variables
id = ""; //set the ID to null
gpa = 0.00F; //set the gpa to 0.00
name = inName; //gets the name of the student from the user
}
//create an overloaded constructor that will receive all three pieces of instance data
public StudentData(String inName, String inID, float inGPA)
{
name = inName; //name input by user through the constructor parameter
id = inID; //ID input by user through the constructor parameter
gpa = inGPA; //GPA input by user through constructor parameter
}
//create a method that will modify the students GPA
public static float modifyGPA()
{
//local constants
//local variables
float newGPA;
System.out.print("Enter new GPA: ");
newGPA = Keyboard.readFloat();
return newGPA;
}
//create a toString method that will format the instance data to look like:
public String toString()
{
String format;
format = ("Student" + name + "\n" +
"Student ID" + id + "\n" +
"Student GPA" + gpa + "\n");
return format;
}
It's the studentGPA variable. It's declared in a local block:
if(!YES.equals(idPrompt))
{
// variable *declared* here!
StudentData aStudent = new StudentData(name, "", 0);
// aStudent is visible here
}
// but it's not visible here out of the scope of this local block.
and thus only visible in that block. If you want it visible throughout the method, then declare it in method or class scope.
Scope, scope, scope!! Declarations in Java (and C/C++) are "scoped" to the "block", where a "block" is a set of statements between { and }.
This means that if you declare a variable { StudentData aStudent = new StudentData(...); } it goes "poof" when you pass that closing }. If you want it to be "visible" outside that scope you need to declare aStudent outside the block.
Note that you can still do the assignment inside that block, just don't mistakenly include StudentData or you will be declaring an entirely different version of the variable. And note that, in Java, a variable must be assigned a value along all possible paths from its declaration to its use, so you may have to assign null (eg) to the variable where it's declared.
for your posted problem,you can do like this in main class,
// your code
StudentData aStudent = null;
while(!QUIT.equals(name))
{
//your code
//if the user says yes
if(!YES.equals(idPrompt))
{
//instantiate a new Student with just the name
aStudent = new StudentData(name, "", 0);
}
else
{
//your code
//instantiate a new Student with all three data types
aStudent = new StudentData(name, studentID, studentGPA);
}
//your code
Related
I'm currently learning java and starting on methods, classes and objects. I'm attempting to code a simple program to have set values for 2 separate employee's at a company that would then allow for user input to alter certain variables of a specific object. The variables needing to be updated via user input will be the MonthlySalary and FirstName of the object employee2. I'm not really sure how to structure the user input part and I'm at a loss trying to find a solution.
import java.util.Scanner;
public class EmployeeTest
{
public static void main( String[] args ){
Scanner input = new Scanner(System.in);
// Create 2 Employee objects
Employee employee1 = new Employee( "Jane", "Doe", 5000 );
Employee employee2 = new Employee( "John", "Bloggs", 4500 );
// Do other steps (not requiring input)
// Ask for user input of Employee 2's new first name
System.out.println( "Please enter new first name for Employee 2: \n");
String input = employee2.newFirstName();
// repeat above to set Employee 2's new salary then display new information
}
}
With the Class file Employee.java
public class Employee
{
private String firstName; // Employee's First Name
private String lastName; // Employee's Last Name
private double monthlySalary; // Employee's Monthly Salary
// Employee constructor
public Employee( String initFirstName, String initLastName, double initMonthlySalary )
{
firstName = initFirstName;
lastName = initLastName;
if (initMonthlySalary > 0)
monthlySalary = initMonthlySalary;
else
monthlySalary = 0;
}
public Employee( )
{
firstName = "";
lastName = "";
monthlySalary = 0;
}
// Method to assign the employee's First Name
public void setFirstName( String newFirstName )
{
firstName = newFirstName;
}
// Method to assign the employee's Monthly Salary
public void setMonthlySalary( double newMonthlySalary )
{
if (newMonthlySalary > 0) monthlySalary = newMonthlySalary;
}
// Other required methods
}
You are struggling to take input from the console.
System.out.println("Please enter new first name for Employee 2: ");
String firstName = input.next();
employee2.setFirstName(firstName);
System.out.println("Please enter new Salary for Employee 2: ");
double salary = input.nextDouble();
employee2.setMonthlySalary(salary);
This will work for you. And please go through the basic syntaxes first. Because otherwise you are wasting your own time banging your head for this kind of syntactical doubts.
I am trying to clean my code up by creating a class specifically for an array of information. It is basically like a storage for variables in case I need them later. Here is what I have so far:
package com.input;
import java.util.Scanner;
public class Gender extends Welcome {
Scanner input = new Scanner(System.in);
private static String gender;
public static void setGender() {
Scanner input = new Scanner(System.in);
int[] storeInts = new int[25];
storeInts[0] = 0;
//The [0] index of array storeInformation is the gender value. 0 = female; 1 = male
gender = input.nextLine();
if(gender.equalsIgnoreCase("boy")) {
System.out.println("What is your name, sir?");
while (storeInts[0] < 1) {
storeInts[0]++;
}
}else if(gender.equalsIgnoreCase("girl")) {
System.out.println("What is your name, ma'am?");
}else{
System.out.println("You have failed to answer correctly. Try again:");
init();
}
Name nameObject = new Name();
nameObject.setName(storeInts[0]);
}
public static void nextName(int x) {
if(x == 1) {
System.out.println("What is your name, sir?");
}else{
System.out.println("What is your name, ma'am?");
}
Name nameObject = new Name();
nameObject.setName2();
}
}
What I'm trying to accomplish here, is if the user types "boy" my code will store 1 in the index [0] of array storeInts[]. If the user types "girl" the index [0] will remain the value of 0.
If I need to refer to the user's gender later on, I want to be able to go back and figure out if they are a "boy" or a "girl" using the array.
I want to be able to called this array from any method within my code. I have already used this array in a complicated way and I would like to find a solution to make it easier.
Here is when I used it:
nameObject.setName(storeInts[0]);
I transferred the index [0] to the setName() method.
Here is the setName() method:
public void setName(int x) {
String name;
name = input.nextLine();
String storedStrings[] = new String[25];
storedStrings[0] = name;
FirstTask firstTaskObject = new FirstTask();
if (name.length() == 0) {
System.out.println("You must be a unicorn. You want to play games?");
altInit(x);
}else{
System.out.println("Nice to meet you, " + name + "!");
firstTaskObject.beginning(name);
}
}
As you can see I created another array in the same manner as the previous one, but this one is to store Strings instead. Now back to what I was saying-- the parameter (int x) is the same value as storeInts[0]. This will tell me if the user is male or female. This value is sent to altInit() method when the user decides to try to continue without typing their name in first.
Here is the altInit() method:
public void altInit(int x) {
String yesOrNo;
AltStory altStoryObject = new AltStory();
Gender backToGender = new Gender();
yesOrNo = input.nextLine();
if(yesOrNo.equalsIgnoreCase("yes")) {
altStoryObject.AltInit();
}else if(yesOrNo.equalsIgnoreCase("no")) {
System.out.println("Consider this your last warning...");
backToGender.nextName(x);
}else{
System.out.println("You have failed to answer correctly. Try again:");
init();
}
}
When asked if they want to play games, they can type "yes" or "no." If the user types "no" as in they do not want to play games, then the program will print, "Consider this your last warning..." and then continue to the nextName() method in the previous class Gender. This also passes on that index[0] again in the array storedInts[].
Here is the nextName() method:
public static void nextName(int x) {
if(x == 1) {
System.out.println("What is your name, sir?");
}else{
System.out.println("What is your name, ma'am?");
}
Name nameObject = new Name();
nameObject.setName2();
}
As you can see, if the user is that value of a male (or 1) then the program will print, "What is your name, sir?." If the value is a female (or 0), then the program will print, "What is your name, ma'am?"
This whole time I felt like the stored value of storeInts[0], was just leap frogging around until it was used... I want to prevent this by just creating a class with methods giving me the ability to call any value stored in that array whenever I need it. How do I create an array, store it in a method, and call it when needed?
As someone has requested, here is the entire code:
//Gender class
package com.input;
import java.util.Scanner;
public class Gender extends Welcome {
Scanner input = new Scanner(System.in);
private static String gender;
public void setGender() {
Scanner input = new Scanner(System.in);
int [] storeInts = new int[25];
storeInts[0] = 0;
//The [0] index of array storeInformation is the gender value. 0 = female; 1 = male
gender = input.nextLine();
if (gender.equalsIgnoreCase("boy")) {
System.out.println("What is your name, sir?");
while(storeInts[0]<1){
storeInts[0]++;
}
} else if (gender.equalsIgnoreCase("girl")) {
System.out.println("What is your name, ma'am?");
} else {
System.out.println("You have failed to answer correctly. Try again:");
init();
}
Name nameObject = new Name();
nameObject.setName(storeInts[0]);
}
public void nextName(int x){
if (x == 1) {
System.out.println("What is your name, sir?");
}else {
System.out.println("What is your name, ma'am?");
}
Name nameObject = new Name();
nameObject.setName2();
}
}
//Name class
package com.input;
public class Name extends Gender{
public void setName(int x) {
String name;
name = input.nextLine();
String storedStrings[] = new String[25];
storedStrings[0] = name;
FirstTask firstTaskObject = new FirstTask();
if (name.length() == 0) {
System.out.println("You must be a unicorn. You want to play games?");
altInit(x);
} else {
System.out.println("Nice to meet you, " + name + "!");
firstTaskObject.beginning(name);
}
}
public void altInit(int x){
String yesOrNo;
AltStory altStoryObject = new AltStory();
Gender backToGender = new Gender();
yesOrNo = input.nextLine();
if(yesOrNo.equalsIgnoreCase("yes")) {
altStoryObject.AltInit();
}else if(yesOrNo.equalsIgnoreCase("no")){
System.out.println("Consider this your last warning...");
backToGender.nextName(x);
}else{
System.out.println("You have failed to answer correctly. Try again:");
init();
}
}
public void setName2() {
String name;
name = input.nextLine();
FirstTask firstTaskObject = new FirstTask();
if (name.length() == 0) {
System.out.println("You have failed to answer correctly. Try again:");
init();
} else {
System.out.println("Nice to meet you, " + name + "!");
firstTaskObject.beginning(name);
}
}
}
How do I create an array, store it in a method, and call it when needed?
my question is about creating a copy of a local variable created from within a static method and making it an instanced variable that can be used by other static methods in the class.
Here is the specific part of my code I am having issues with.
static void createBooks() {
Book [] inventory = new Book[maxBooks];
System.out.println("How many books would you like to add?");
int newBooks = keyboard.nextInt();
int createBooks;
if(newBooks>(maxBooks-findNumberOfCreatedBooks())) {
System.out.println("Sorry, your bookstore has a capacity of " + maxBooks + ", and you have " + findNumberOfCreatedBooks() + " books already created.");
System.out.println("Therefore we will add a maximum of " + (maxBooks-findNumberOfCreatedBooks()) + " to your collection.");
createBooks = (maxBooks-findNumberOfCreatedBooks());
}
else
createBooks=newBooks;
for(int x =findNumberOfCreatedBooks(); x<createBooks;x++) { //creates a new book where one doesn't exist
System.out.println("***Book"+x+"***");
System.out.println("Please enter the name this book:");
String name = keyboard.next();
System.out.println("Please enter the author of this book:");
String author = keyboard.next();
System.out.println("Please enter the ISBN of this book:");
keyboard.nextLine();
long isbn = keyboard.nextLong();
System.out.println("Please enter the price of this book:");
double price = keyboard.nextDouble();
inventory[x] = new Book(name,author,isbn,price);
}
I am trying to create an array of object Book which can then be accessed by other static methods such as a method called ChangeBooks() which will allow the user to modify books they have created with the setName(),setTitle() etc.
Is there a way to create a instance array of book objects that is changed from a static method, and doesn't point to a null reference when initialized outside the method?
Thanks
You could make inventory a static field on the class where this method is defined:
class BookStuff {
private static Book[] inventory;
private static final int MAX_BOOKS = 5;
static void createBooks() {
inventory = new Book[MAX_BOOKS];
// ...
}
static void readBook(int index) {
inventory[index].read();
}
}
Note that an instance property cannot be modified by a class method (static method).
I want to know how I can loop a new object within the same class, so that I can repeat the code to have several different objects with different details entered via the Scanner class.
It will probably make sense if I show what I am trying to do:
public class Students
{
private String studFirstName; // Student's first name
private String studSurname; // Student's surname
private String courseName; // Course name
public Students(String sFirstName, String sSurname, String cName)
{
studFirstName = sFirstName;
studSurname = sSurname;
courseName = cName;
}
public String getStudFirstName() // Getter for student's first name
{
System.out.println("Enter in student's first name: "); // Prompts end user for input
Scanner In = new Scanner(System.in); // Creating a new object
studFirstName = In.next(); // Accepts a one word input only
return studFirstName;
}
public String setStudFirstName(String sFirstName) // Setter for student's first name
{
return studFirstName;
}
public static void main (String [] args)
{
Students first[] = new Students[5];
for(Students a : first)
{
}
Students first[] = new Students("", "", "");
String studFirstName = first.getStudFirstName();
}
}
You need a regular for loop in order to assign values within the array.
int numStudents = 5;
Student students[] = new Student[numStudents]; // creates an array of 5 nulls
Scanner scan = new Scanner(System.in);
for(int i = 0; i < numStudents; i++) {
System.out.println("Enter your first name: "); // Prompt
String fname = scan.nextLine(); // Read
Student s = new Student(fname); // Assign
first[i] = s; // Store
}
You really don't need the get methods since you have access to set the values in the constuctor.
int numberOfStudents = 3;
// create an array that can hold up to 3 students
Student[] students = new Student[numberOfStudents];
// create the Scanner to read from console.
Scanner scanner = new Scanner(System.in);
// create the 3 students and store them in the array
for(int i = 0; i < numberOfStudents; i++) {
System.out.println("Enter name: ");
// read the next line from the console
String name = scanner.nextLine();
// ...
// if you have anything you need to create the student object (e.g. name, and so on).
Student s = new Student(studFirstName);
students[i] = s; // store the student object in the array.
}
// you should evt. close the scanner
// scanner.close();
// you can now do anything with your 3 stored students.
System.out.println("The Students first name is: " + students[0].getStudFirstName());
}
}
First, you should take a look at encapsulation. A getter is not meant to take user input. Getter should return the value of a private field. Setters should set the value of a private field.
// This is a field
private String myField;
// This will return the current value for the field 'myField'
public String getMyField() {
return this.myField;
}
// This will asign a new value to the field 'myField'
public void setMyField(String myField) {
this.myField = myField;
}
Answer
You will need a regular for loop to create as many students a you want. I renamed your class 'Students' to Student to fit javas naming conventions.
int numberOfStudents = 3;
// create an array that can hold up to 3 students
Student[] students = new Stundent[numberOfStudents];
// create the Scanner to read from console.
Scanner scanner = new Scanner(System.in);
// create the 3 students and store them in the array
for(int i = 0; i < numberOfStudents; i++) {
System.out.println("Enter name: ");
// read the next line from the console
String name = scanner.nextLine();
// ...
// if you have anything you need to create the student object (e.g. name, and so on).
Student s = new Student(name, .....);
students[i] = s; // store the student object in the array.
}
// you should evt. close the scanner
// scanner.close();
// you can now do anything with your 3 stored students.
System.out.println("The Students first name is: " + students[0].getStudFirstName());
I have tried various suggestions already given on the website.. But honestly i couldnt find something to fix it.
Basically when i try to use any variable created in Accept... it cant be used in other functions. Is there a simple solution to fix this? (Without changing the main code)
import java.util.Scanner;
class x4Salary
{
Scanner input = new Scanner(System.in);
public void accept()
{
System.out.println("Please input the name of the teacher");
String name = input.next();
System.out.println("Please input the address ");
String adress = input.next();
System.out.println("Please input the phone number");
long num = input.nextLong();
System.out.println("Please input the subject specialization");
String subjectSpecialization = input.next();
String subS = subjectSpecialization;
System.out.println("Please input the Monthly Salary");
long sal = input.nextLong();
if(sal>175000)
{
tax();
}
display();
double tax = 0.0;
}
public void tax()
{
System.out.println("Your current salary is : " + sal);
tax = sal + ((5/sal)*100);
System.out.println("The salary + Tax : " +tax);
display();
}
public void display()
{
System.out.println("The name of the teacher : " + name);
System.out.println("The Address of the teacher :" +adress);
System.out.println("The Phone number of the Teacher: "+num);
System.out.println("The Subject Specialization of the Teacher" + subS);
System.out.println("The Monthly salary of the teacher" +sal + tax);
}
}
You can make those variables as class members
class x4Salary
{
protected String name, address; //and so on
and then instead of String name = input.next();
name = input.next();
name would be visible in all methods of X4Salary
Those variables are scoped to the method alone. If you want to retain those values entered your options are:
create member variables in the containing class and populate those. Those values would be available for the lifetime of that class
return the values from the method. Since you have multiple values you would likely want an object containing these values to be returned
call another object from within that method, and pass the data that way.
For option 2 you could define a return object thus:
class Teacher {
private String name;
private String phone;
// add appropriate constructor
}
I suspect Teacher is a key object in your application and you would likely want to add the method display() to the Teacher class itself. Remember that OO is about creating objects and getting them to do things for you, not handling discrete related variables yourself.
you cant use the local variables(variables defined inside your method) outside of that method. they are only confined to that method. you either have to make it an instance variable or return that variable so that the other methods can use it.
in your case.
if you want to use sal outside method accept . make it an instance variable.
Class classname {
public long sal;
public void accept(){
//can access sal here
sal = input.nextLong();
}
public void display(){
//cvan access sal here
}
}
Define your variables as Member Variables in the Class then it can be accessible in all the member methods.
import java.util.Scanner;
class x4Salary
{
private double tax=0.0;
private string name, adress, subS;
private long num, sal;
Scanner input = new Scanner(System.in);
public void accept()
{
System.out.println("Please input the name of the teacher");
name = input.next();
System.out.println("Please input the address ");
adress = input.next();
System.out.println("Please input the phone number");
num = input.nextLong();
System.out.println("Please input the subject specialization");
subS = input.next();
System.out.println("Please input the Monthly Salary");
sal = input.nextLong();
if(sal>175000)
{
tax();
}
display();
}
public void tax()
{
System.out.println("Your current salary is : " + sal);
tax = sal + ((5/sal)*100);
System.out.println("The salary + Tax : " +tax);
display();
}
public void display()
{
System.out.println("The name of the teacher : " + name);
System.out.println("The Address of the teacher :" +adress);
System.out.println("The Phone number of the Teacher: "+num);
System.out.println("The Subject Specialization of the Teacher" + subS);
System.out.println("The Monthly salary of the teacher" +sal + tax);
}
}
You would need to make those variables as instance variables.
The variables created in a method, in confined to that method scope only. It is not visible outside that method. It will be created when the method is invoked, and then when the method is finished with execution, that variable becomes eligible for Garbage Collection.
This is true for any block scope you have. The variables created in one block, will not be visible outside that block.
For e.g: -
{ // A block
int num = 10;
}
System.out.println(num); // Error. num not visible here.
So, to access the variable in all methods, declare it as: -
public class Demo {
private int num; // Instance variable declaration. Outside every method.
public void setNum(int num) {
this.num = num;
}
public int getNum() {
return this.num;
}
}
So, as you can see, variable num is used in both the methods: - setNum and getNum.
Go to this tutorial to get started with classes, objects, and member declarations: -
http://docs.oracle.com/javase/tutorial/java/javaOO/variables.html