Trying to make it so if the user types "end", in the second input which is "Enter the first name of student", the loop automatically assigns each object in the array the attributes of "null" for id and name, and 0 for age and id, as well as breaking the outerloop. However, I get the error java.lang.NullPointerException.
Any help would be appreciated.
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
System.out.println("Enter number of students");
int numberof = myObj.nextInt();
System.out.println("Number of students is " + numberof);
Student Studentz[] = new Student[numberof];
outerloop:
for (int i = 0; i < numberof; ++i) {
Studentz[i] = new Student();
System.out.println("Enter first name of student " + (i + 1));
Scanner myObj1 = new Scanner(System.in);
String firstname = myObj1.nextLine();
System.out.println("Firstname is: " + firstname);
if (firstname.equals("end")) {
for (int g = i; g < numberof; ++g) {
Studentz[g].Setfirst("null");
Studentz[g].Setlast("null");
Studentz[g].Setage(0);
Studentz[g].Setid(0);
}
break outerloop;
} else {
Studentz[i].Setfirst(firstname);
System.out.println("Enter last name of student " + (i + 1));
Scanner myObj2 = new Scanner(System.in);
String lastname = myObj2.nextLine();
System.out.println("Last name is: " + lastname);
Studentz[i].Setlast(lastname);;
System.out.println("Enter age of student " + (i + 1));
Scanner myObj3 = new Scanner(System.in);
int nazca = myObj3.nextInt();
System.out.println("Age is: " + nazca);
Studentz[i].Setage(nazca);
System.out.println("Enter ID of student " + (i + 1));
Scanner myObj4 = new Scanner(System.in);
int nazca1 = myObj4.nextInt();
System.out.println("ID is: " + nazca1);
Studentz[i].Setid(nazca1);
}
for (int c = 0; c < numberof; ++c) {
System.out.println(Studentz[c].Snake());
}
}
}
}
public class Student {
private String first;
private String last;
private int age;
private int id;
public int getid() {
return
this.id;
}
public void Studentss(String f, String l, int a, int i) {
first = f;
last = l;
age = a;
id = i;
}
public void Setfirst(String z) {
this.first = z;
}
public void Setlast(String za) {
this.last = za;
}
public void Setage(int zb) {
this.age = zb;
}
public void Setid(int zc) {
this.id = zc;
}
public String Snake() {
String snek = "Name is " + this.first + " " + this.last + " , Age is " + this.age + " ,ID is " + this.id;
return snek;
}
}
you fail here because you try to print students data before you initialized all elements of Studentz array:
for (int c = 0; c < numberof; ++c) {
System.out.println(Studentz[c].Snake());
}
also your code fails here by the same reason:
for (int g = i; g < numberof; ++g) {
Studentz[g].Setfirst("null"); // NPE - no Student created yet in the array
Some Possibly Helpful Tips:
Follow Java naming rules for your variables and method names, Studentz should be studentz, even for your Arrays. I know...your tired of reading that but as you progress, you'll see how beneficial it really is.
If you can, don't use multiple Scanner objects, there is no need for that in your use-case. Declare one Scanner object and stick with it. You're probably doing this because you are using the nextLine() method after the nextInt() method and you're finding that it skips the first name prompt and provides a Null String (""). This happens because the nextInt() method does not consume the newline character when the Enter key is hit. To solve this problem you would either, place the code line myObj.nextLine(); directly under the int numberof = myObj.nextInt(); code line:
int numberof = myObj.nextInt();
myObj.nextLine(); // Consume ENTER key hit
or don't use the nextInt() method at all. Instead just stick with the nextLine() method and not worry about consumption:
Scanner myObj = new Scanner(System.in);
int numberof = 0;
String val = "";
while (val.equals("")) {
System.out.println("Enter number of students");
val = myObj.nextLine();
if (!val.matches("\\d+")) {
System.err.println("Invalid number supplied!");
val = "";
continue;
}
numberof = Integer.parseInt(val);
}
System.out.println("Number of students is " + numberof);
Student[] studentz = new Student[numberof];
It's always a good idea to validate any input from the User (as shown above), even if they're in a for loop. Give the User an opportunity to make a correct entry, after all, typo's do happen.
Get rid of the outerLoop: label. As a matter of fact, try avoid ever using them if you can....and you can. It would only be on a relatively rare occasion where you might ever need one.
Give your variables meaningful names, at least to some extent. This can benefit you later on down the road when you want to read your old code in the future.
In your Student class you made yourself a this real nice method named Studentss(). Well, I think it should be a constructor instead and save yourself a lot of code entry for calls to Setter methods. After all, that's mostly what the constructor is for. Your Student class constructor can look like this:
public Student(String firstName, String lastName, int age, int id) {
this.first = firstName;
this.last = lastName;
this.age = age;
this.id = id;
}
And be used like this. You will notice that upon each iteration of the outer for loop, all the prompt answers are placed within variables then at the end of all those prompts the constructor is used instantiate a student object, for example:
studentz[i] = new Student(firstname, lastname, age, id);
Doing it this way mean that there is no need to make calls to Setter methods. There is nothing wrong with making setter calls, it's just easier using the constructor. This is demonstrated below:
Scanner myObj = new Scanner(System.in);
int numberof = 0;
String val = "";
while (val.equals("")) {
System.out.println("Enter number of students");
val = myObj.nextLine();
if (!val.matches("\\d+")) {
System.err.println("Invalid number supplied!");
val = "";
continue;
}
numberof = Integer.parseInt(val);
}
System.out.println("Number of students is " + numberof);
Student[] studentz = new Student[numberof];
for (int i = 0; i < numberof; ++i) {
String firstname = "null";
String lastname = "null";
int age = 0;
int id = 0;
boolean exitOuterForLoop = false;
// Student First Name Prompt:
// (with option to End and default remaining to null's and 0's)
while (firstname.equals("null")) {
System.out.println("Enter first name of student " + (i + 1) + " (End to stop):");
firstname = myObj.nextLine();
if (firstname.equalsIgnoreCase("end")) {
firstname = "null";
//Make all remaining Student instances null and 0
for (int g = i; g < numberof; ++g) {
studentz[g] = new Student(firstname, lastname, age, id); // Use Student class constructor
}
exitOuterForLoop = true;
break; // Exit this 'while' loop
}
// Validate first name (no numbers or crazy characters)
if (!firstname.matches("(?i)[a-z']+")) {
System.err.println("Invalid First Name! (" + firstname + ") Try Again...");
firstname = "null";
}
}
if (exitOuterForLoop) {
break; // Exit this outer 'for' loop.
}
System.out.println("Firstname is: " + firstname);
// Student Last Name Prompt
while (lastname.equals("null")) {
System.out.println("Enter last name of student " + (i + 1));
lastname = myObj.nextLine();
// Validate last name (no numbers or crazy characters)
if (!lastname.matches("(?i)[a-z']+")) {
System.err.println("Invalid Last Name! (" + lastname + ") Try Again...");
lastname = "null";
}
}
System.out.println("Last name is: " + lastname);
// Student Age Prompt
val = "";
while (val.equals("")) {
System.out.println("Enter age of student " + (i + 1));
val = myObj.nextLine();
// Validate age (digits 0 to 9 only)
if (!val.matches("\\d+")) {
System.err.println("Invalid Age Supplied! (" + val + ") Try Again...");
val = "";
}
}
age = Integer.parseInt(val);
System.out.println("Student age is: " + age);
// Student ID Prompt
val = "";
while (val.equals("")) {
System.out.println("Enter ID of student " + (i + 1));
val = myObj.nextLine();
// Validate age (digits 0 to 9 only)
if (!val.matches("\\d+")) {
System.err.println("Invalid ID Supplied! (" + val + ") Try Again...");
val = "";
}
}
id = Integer.parseInt(val);
System.out.println("Student ID is: " + id);
studentz[i] = new Student(firstname, lastname, age, id); // Use Student class constructor
}
// Display the instances of Student contained within the 'studentz[]' array.
for (int c = 0; c < numberof; ++c) {
System.out.println(studentz[c].toString());
}
The snake() method is actually just another toString() method and there is nothing wrong with that however you might want to consider using StringBuilder class to create the returned string rather than doing concatenations, for example:
public String snake() {
return new StringBuilder("Name is ").append(this.first).append(" ").append(this.last)
.append(" , Age is ").append(this.age).append(" , ID is ")
.append(this.id).toString();
}
Not overly important here but it can save you memory if you do a lot concatenating with many large strings.
Related
public class billing{
private int id;
//File f=new File("C:/Users/Bingus/Documents/Projects/accounts.txt");
private String bc;
private String bd;
private String customerName;
private String customerAddress;
private String customerNumber;
private String periodT;
private String periodF;
private double presentR;
private double previousR;
private double previousB;
private double dueTotal;
private static ArrayList<Account> accountList = new ArrayList<>();
public billing(int id,String bc,String bd,String customerName,String customerAddress,String customerNumber,String periodT,String periodF,double presentR,double previousR,double previousB,double dueTotal){
this.id = id;
this.bc = bc;
this.bd = bd;
this.customerName = customerName;
this.customerAddress = customerAddress;
this.customerNumber = customerNumber;
this.periodT = periodT;
this.periodF = periodF;
this.presentR = presentR;
this.previousR = previousR;
this.previousB = previousB;
this.dueTotal = dueTotal;
}
public int getId(){
return id;
}
public String getBc(){
return bc;
}
public String getBd(){
return bd;
}
public String getCustomerName(){
return customerName;
}
public String getCustomerAddress(){
return customerAddress;
}
public String getCustomerNumber(){
return customerNumber;
}
public String getPeriodT(){
return periodT;
}
public String getPeriodF(){
return periodF;
}
public double getPresentR(){
return presentR;
}
public double getPreviousR(){
return previousR;
}
public double getPreviousB(){
return previousB;
}
public double getDue(){
return dueTotal;
}
public static void main(String[] args){
Scanner scanner = new Scanner (System.in);
Scanner kb = new Scanner (System.in);
int user_choice;
int x = 0;
do{
System.out.println();
System.out.println("1) New Billing");
System.out.println("2) Add Existing Billing");
System.out.println("3) View Billing Account ID");
System.out.println("4) View By Date");
System.out.println("5) Update Existing Billing");
System.out.println("6) Delete Billing Account");
System.out.println("7) Display All Account");
System.out.println("8) Exit");
System.out.println();
System.out.print("Enter choice [1-8]: ");
user_choice = scanner.nextInt();
switch (user_choice){
case 1:
int min = 1000;
int max = 9999;
int randomStr = (int)(Math.random() * (max - min + 1) + min);
int id = randomStr;
System.out.println("Your Account Number is : " + id);
System.out.print("Enter Billing Code: ");
String bc = scanner.next();
System.out.print("Enter Billing Date(dd/mm/yyyy): ");
String bd = scanner.next();
System.out.print("Enter Customer Name: ");
String customerName = kb.nextLine();
System.out.print("Enter Customer Address: ");
String customerAddress = kb.nextLine();
System.out.print("Enter Customer Number: ");
String customerNumber = scanner.next();
System.out.print("Enter Period To: ");
String periodT = scanner.next();
System.out.print("Enter Period From: ");
String periodF = scanner.next();
System.out.print("Enter Present Reading: ");
double presentR = scanner.nextDouble();
System.out.print("Enter Previous Reading: ");
double previousR = scanner.nextDouble();
System.out.print("Enter Previous Balance: ");
double previousB = scanner.nextDouble();
double dueTotal = getTotalDue(presentR,previousR,previousB);
Account user = new Account(id,bc,bd,customerName,customerAddress,customerNumber,periodT,periodF,presentR,previousR,previousB,dueTotal);
accountList.add(user);
break;
case 2:
case 3:
System.out.print("Enter Account Number: ");
int a = scanner.nextInt();
for(int i = 0; i<accountList.size();i++){
if(a == accountList.get(i).getId()){
System.out.println("Account ID: " + accountList.get(i).getId());
System.out.println("Customer Name: " +accountList.get(i).getCustomerName());
System.out.println("Customer Address: " + accountList.get(i).getCustomerAddress());
System.out.print("Customer Number: " + accountList.get(i).getCustomerNumber());
}
}
System.out.println("\nBilling Code\t\tBilling Date\t\tAmount Due");
for(int i = 0; i<accountList.size();i++){
if(a == accountList.get(i).getId())
{
System.out.println(accountList.get(i).getBc()+"\t\t\t"+accountList.get(i).getBd()+"\t\t\t"+accountList.get(i).getDue());
}
}
break;
case 4:
case 5:
System.out.print("Enter Account Number: ");
a = scanner.nextInt();
for(int i = 0; i<accountList.size();i++){
if(a == accountList.get(i).getId())
{
System.out.println("Your Account Number is : " + accountList.get(i).getId());
System.out.print("Enter Billing Code: ");
String bCode = scanner.next();
String c = accountList.get(i).getBc(); //this is the part in which i am having a hard time to fix, ive used the set but still i cannot change the element inside.
int index = accountList.indexOf(c);
accountList.set(index, bCode);
}
}
break;
case 6:
System.out.print("Enter Account Number: ");
a = scanner.nextInt();
System.out.print("Enter Billing Code: ");
String b = scanner.next();
for(int i = 0; i<accountList.size();i++){
if(a == accountList.get(i).getId()){
if(b.equals(accountList.get(i).getBc())){
accountList.remove(i);
System.out.print("\nAccount Removed\n");
}else{
System.out.print("Invalid Billing Code\n");
}
}else if(a != accountList.get(i).getId()){
System.out.print("Invalid Account Number or Number not in the database.\n");
}else{
System.out.print("Try Again\n");
}
}
break;
case 7:
System.out.println("Account ID\t\tBilling Code\t\tAccount Name\t\tTotal Due\t\tPresent R\t\tPrevious R");
Collections.sort(accountList,Collections.reverseOrder());
for(int i=0; i<accountList.size();i++){
System.out.println(accountList.get(i).getId() + "\t\t\t"+accountList.get(i).getBc()+ "\t\t\t"+accountList.get(i).getCustomerName()+ "\t\t\t"+accountList.get(i).getDue()+"\t\t\t"+accountList.get(i).getPresentR()+ "\t\t\t"+accountList.get(i).getPreviousR());
}
break;
}
}while(user_choice!=8);
}
I'm new to programming in Java and I'm still learning towards it. I'm making my billing system which calcualtes the payment. My problem for this is how can I change or update the value which is already in the arraylist, I've tried the set() but I cannot make it work. using arraylist is a big jump for me and I haven't yet got a hang of it. I've watched youtube vids but they seem to show non user input arry lists
Any help?
[1]: https://i.stack.imgur.com/HhF33.png
There are two ways to do it.
First Option is Loop the list and reach the object you want to change, update its attributes. Since the object is accessed by reference, whatever values you will change it will effect.
Second option is remove the object at that index, create a new object and insert at that position.
public void testArrayList ()
{
class MyData
{
String Id = "";
String Name = "";
public MyData () {}
public MyData (String id, String name) {
Id= id;
Name = name;
}
public String toString ()
{
return " Id=" + Id + " Name=" + Name;
}
}
ArrayList myDList = new ArrayList ();
myDList.add(new MyData("1", "John"));
myDList.add(new MyData("2", "Mike"));
myDList.add(new MyData("3", "Tom"));
System.err.println ("Org List " + myDList);
MyData tmp = (MyData) myDList.get(1);
tmp.Id = "22";
tmp.Name = tmp.Name + " Changed";
System.err.println ("Mod List (Observe second Object ) " + myDList);
}
You need to set the value in ArrayList to be an object of type Account.
1.You need to get an object of type Account and use settter method to update bcode
2. Set that Account object back to ArrayList
Code TL:DR. Do you have a set method in your Account class?
//set method example
public void setBc(String newBc){ //can also use other data types as parameters
this.bc = newBc;
}
If so you can just
accountList.get(i).setBc("This New BCODE"); //The parameter can also be a variable of string type
Your code:
System.out.println("Your Account Number is : " + accountList.get(i).getId());
System.out.print("Enter Billing Code: ");
String bCode = scanner.next();
String c = accountList.get(i).getBc(); //this is the part in which i am having a hard time to fix, ive used the set but still i cannot change the element inside.
int index = accountList.indexOf(c);
accountList.set(index, bCode);
If you want to update billing code in an account then get the account object and update the user entered bCode on the object. Also, you don't have to put the account back in the list:
System.out.println("Your Account Number is : " + accountList.get(i).getId());
System.out.print("Enter Billing Code: ");
String bCode = scanner.next();
Account existing = accountList.get(i);
//create new account with same data except bCode
Account updated = new Account(existing.getId(),bCode, existing.getBd(),/*do same for rest of the fields */);
int index = accountList.indexOf(existing);
accountList.set(index, updated);
You have to change this part in Your program
…
Billing billing = accountList.get(i);
//String c = billing.getBc(); // this is the part in which I am having a hard time to fix, I've used
// the set but still I cannot change the element inside.
billing.setBc( yourNewBc );
//int index = accountList.indexOf(c);
//accountList.set(index, billing);
…
class names are capitalized in Java
Here in this example we have iterated over the list and modified the values of the object.
Please make a setter to the values you want to modify and follow something like this.
public class Arr {
public static void main(String args[]){
ArrayList<Person> array = new ArrayList();
Scanner sc=new Scanner(System.in);
while (true){
System.out.println("1.add 2. modify 3.view list ; anything else to to quit");
int choice = sc.nextInt();
if (choice==1){
System.out.println("Enter ID then salary");
int id = sc.nextInt();
int salary = sc.nextInt();
Person p = new Person(id,salary);
array.add(p);
System.out.println("Done");
}
else if (choice==2){
System.out.println("Enter ID");
int id = sc.nextInt();
for (int i = 0; i < array.size(); i++){
Person p = array.get(i);
if (p.getId()==id){
System.out.println("value exits. Enter salary to be modified:");
int salary = sc.nextInt();
p.setSalary(salary);
}
}
System.out.println("Done");
}
else if (choice==3){
for (int i = 0; i < array.size(); i++)
System.out.print(" " + array.get(i).getId() + " " + array.get(i).getSalary());
}
else
break;
}
}
}
public class Person {
int id;
int salary;
public Person(int id, int salary) {
this.id = id;
this.salary = salary;
}
public int getId() {
return id;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
}
I am new to java and I am currently trying to make a program that uses an array of 10 inputted names and ages. What I want to do is add an option so that if the user types "done" when prompted to enter a name, the program will skip straight to listing the names and ages already entered.
Code:
import java.util.Arrays;
public class array2 {
public static void main(String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in);
input.useDelimiter(System.getProperty("line.separator"));
int numofpeople = 10;
Person[] persons = new Person[numofpeople];
for (int i = 0; i < numofpeople; i++) {
System.out.print("Enter the person's name: ");
String person = input.next();
System.out.print("Enter the persons's age: ");
int age = (Integer) input.nextInt();
persons[i] = new Person(person, age);
}
Arrays.sort(persons);
System.out.print("Name" + "\tAge");
System.out.print("\n----" + "\t----\n");
for (int i = 0; i < persons.length; i++) {
System.out.println(persons[i].person + "\t" + persons[i].age);
}
System.out.println("The oldest person is: " + persons[numofpeople-1].person);
System.out.println("The youngest person is: "+ persons[0].person);
}
}
class Person implements Comparable<Person> {
public String person;
public Integer age;
public Person(String s, Integer g) {
this.person = person;
this.age = g;
}
#Override
public int compareTo(Person o) {
return (this.age>o.age?1:-1);
}
}
What I'm thinking is that I need to use a boolean if statement that defines whether or not done has been entered, and if it has, then the program skips asking the user for the rest of the names and ages and instead jumps to printing the already entered ones. I am not sure on this so, any help would be appreciated!
Your thought is correct, the simplest way would be checking if person is equal to "done". If this is true, break the loop and code should continue, and it should produce the result you want.
You can do comething like this:
for (int i = 0; i < numofpeople; i++) {
System.out.print("Enter the person's name: ");
String person = input.next();
if (!person.equals("done")) {
System.out.print("Enter the persons's age: ");
int age = (Integer) input.nextInt();
persons[i] = new Person(person, age);
} else {
//print table or enter here a break; directive
}
}
If user enter done instead of any name, your program will straight to listing the names and ages already entered.
this also jumps out of the for loop and moves on to printing the list if the user types in "done":
for (int i = 0; i < numofpeople; i++) {
System.out.print("Enter the person's name: ");
String person = input.next();
if(person == "done"){break;}
System.out.print("Enter the persons's age: ");
int age = (Integer) input.nextInt();
persons[i] = new Person(person, age);
}
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
}
}
}
}
I am a student and looking for help with an assignment. Here is the task: Create a CollegeCourse class. The class contains fields for the course ID (for example, “CIS 210”), credit hours (for example, 3), and a letter grade (for example, ‘A’).
Include get() and set()methods for each field. Create a Student class containing an ID number and an array of five CollegeCourse objects. Create a get() and set() method for the Student ID number. Also create a get() method that returns one of the Student’s CollegeCourses; the method takes an integer argument and returns the CollegeCourse in that position (0 through 4). Next, create a set() method that sets the value of one of the Student’s CollegeCourses; the method takes two arguments—a CollegeCourse and an integer representing the CollegeCourse’s position (0 through 4).
I am getting runtime errors on the second for loop where I am trying to get the data into the course array. It is asking for both the CourseID and Hours in the same line and regardless of what I respond with it I am getting an error, it almost seems like it is trying to get all the arrays variables at the same time. Here is my code which includes three classes. Any help to send me in the right direction is appreciated as I have spent a ton of time already researching to resolve.
public class CollegeCourse {
private String courseId;
private int creditHours;
private char grade;
public CollegeCourse(String id, int hours, char grade)
{
courseId=id;
creditHours = hours;
this.grade = grade;
}
public void setCourseId(String id)
{
courseId = id;//Assign course id to local variable
}
public String getCourseId()
{
return courseId;//Provide access to course id
}
public void setHours(int hours)
{
creditHours = hours;//Assign course id to local variable
}
public int getHours()
{
return creditHours;//Provide access to course id
}
public void setGrade(char grade)
{
this.grade = grade;//Assign course id to local variable
}
public char getGrade()
{
return grade;//Provide access to course id
}
}
Student Class
public class Student {
final int NUM_COURSES = 5;
private int studentId;
private CollegeCourse courseAdd;//Declares a course object
private CollegeCourse[] courses = new CollegeCourse[NUM_COURSES];
//constructor using user input
public Student(int studentId)
{
this.studentId=studentId;
}
public void setStudentId(int id)
{
studentId = id;//Assign course id to local variable
}
public int getStudentId()
{
return studentId;//Provide access to course id
}
public void setCourse(int index, CollegeCourse course)
{
courses[index] = course;
}
public CollegeCourse getCourse(int index)
{
return courses[index];
//do I need code to return the courseId hours, grade
}
}
InputGrades Class
import java.util.Scanner;
public class InputGrades {
public static void main(String[] args) {
final int NUM_STUDENTS = 2;
final int NUM_COURSES = 3;
Student[] students = new Student[NUM_STUDENTS];
int s;//subscript to display the students
int c;//subscript to display courses
int stId;
int csIndex;
String courseId = "";
int hours = 0;
//String gradeInput;
char grade = 'z';
CollegeCourse course = new CollegeCourse(courseId,hours, grade);//not sure if I am handling this correctly
Scanner input = new Scanner(System.in);
for(s = 0; s<NUM_STUDENTS; ++s)
{
students[s] = new Student(s);
System.out.print("Enter ID for student #" + (s+1) + ":");
stId = input.nextInt();
input.nextLine();
students[s].setStudentId(stId);
for(c=0; c < NUM_COURSES; ++c)
{
csIndex=c;
System.out.print("Enter course ID #" + (c+1) + ":");
courseId = input.nextLine();
course.setCourseId(courseId);
System.out.print("Enter hours:");
hours = input.nextInt();
input.nextLine();
course.setHours(hours);
String enteredGrade = "";
while(enteredGrade.length()!=1) {
System.out.print("Enter grade:");
enteredGrade = input.nextLine();
if(enteredGrade.length()==1) {
grade = enteredGrade.charAt(0);
} else {
System.out.println("Type only one character!");
}
}
course.setGrade(grade);
students[s].setCourse(csIndex, course);
}
}
for(s = 0; s<NUM_STUDENTS; ++s)
{
System.out.print("\nStudent# " +
students[s].getStudentId());
System.out.println();
for(c=0;c<NUM_COURSES;++c)
System.out.print(students[s].getCourse(c) + " ");
System.out.println();
}
}
}
After input.nextInt() you need to add one more input.nextLine(); and than you can read grade.
System.out.print("Enter hours:");
hours = input.nextInt();
input.nextLine();
course.setHours(hours);
Why it is needed? See this question: Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods
You should add a very simple length validation when you input the grade:
String enteredGrade = "";
while(enteredGrade.length()!=1) {
System.out.print("Enter grade:");
enteredGrade = input.nextLine();
if(enteredGrade.length()==1) {
grade = enteredGrade.charAt(0);
} else {
System.out.println("Type only one character!");
}
}
so the full main class code:
import java.util.Scanner;
/**
* Created by dkis on 2016.10.22..
*/
public class App {
public static void main(String[] args) {
final int NUM_STUDENTS = 10;
final int NUM_COURSES = 5;
Student[] students = new Student[NUM_STUDENTS];
//String name;
int s;//subscript to display the students
int c;//subscript to display courses
int stId;
int csIndex;
String courseId = "";
int hours = 0;
char grade = 'z';
CollegeCourse course = new CollegeCourse(courseId,hours, grade);//not sure if I am handling this correctly
Scanner input = new Scanner(System.in);
for(s = 0; s<NUM_STUDENTS; ++s)
{
students[s] = new Student(s);
System.out.print("Enter ID for student #" + s+1 + ":");
stId = input.nextInt();
input.nextLine();
students[s].setStudentId(stId);
for(c=0; c < NUM_COURSES; ++c)
{
//CollegeCourse course = students[s].getCourse(c);
csIndex=c;
System.out.print("Enter course ID#" + c+1 + ":");
courseId = input.nextLine();
course.setCourseId(courseId);
System.out.print("Enter hours:");
hours = input.nextInt();
input.nextLine();
course.setHours(hours);
String enteredGrade = "";
while(enteredGrade.length()!=1) {
System.out.print("Enter grade:");
enteredGrade = input.nextLine();
if(enteredGrade.length()==1) {
grade = enteredGrade.charAt(0);
} else {
System.out.println("Type only one character!");
}
}
course.setGrade(grade);
students[s].setCourse(csIndex, course);
}
}
for(s = 0; s<NUM_STUDENTS; ++s)
{
System.out.print("\nStudent# " +
students[s].getStudentId());
for(c=0;c<NUM_COURSES;++c)
System.out.print(students[s].getCourse(c) + " ");
System.out.println();
}
}
}
I am currently trying to program a array based program. We have to make a employee class then a tester main class that holds a array of five user input employee names, salaries, and performance rating. The performance rating is used to determine a supplied raise amount. I have it basically done, but when i run the program, nothing happens even though java virtual machine is running. I have looked up and down for the error, anyone can point out what i am doing wrong?
Employee Class
public class Employee
{
private String employeeName;
private int salary;
private int performanceRating;
public Employee()
{
employeeName = "";
salary = 0;
performanceRating = 0;
}
public String getEmployeeName()
{
return employeeName;
}
public int getSalary()
{
return salary;
}
public int getPerformanceRating()
{
return performanceRating;
}
}
And this is the tester main class where the error comes in somewhere
import java.util.Scanner;
public class Tester
{
public static void main(String[] args)
{
Employee[] work = new Employee[5];
Scanner scanString = new Scanner(System.in);
Scanner scanInt = new Scanner(System.in);
String employeeName = "";
double salary = 0;
double performanceRating = 0;
String choice = scanString.nextLine();
while(choice.equals("yes"))
{
for(int i = 0; i < 5 ;i++)
{
System.out.println("What is the employee's name?");
employeeName = scanString.nextLine();
System.out.println("Enter Employee's salary");
salary = scanInt.nextInt();
System.out.println("Performance? 1 = excellent, 2 = good, 3 = poor");
performanceRating = scanInt.nextInt();
work[i] = new Employee();
}
for(int j = 0; j < 5; j ++)
if(work[j].getPerformanceRating() == 1)
{
salary = salary * 0.06;
System.out.println("Employee " + employeeName + " salary raised to " + salary);
}
else if(performanceRating == 2)
{
salary = salary * 0.04;
System.out.println("Employee " + employeeName + " salary raised to " + salary);
}
else if(performanceRating == 3)
{
salary = salary * 0.015;
System.out.println("Employee " + employeeName + " salary raised to " + salary);
}
else if(performanceRating < 5)
{
salary = salary;
System.out.println("Rating is off scale. No raise for emplyee " + employeeName);
}
System.out.println("Enter more employees? type 'yes' if you want to go again");
choice = scanString.nextLine();
}
System.out.println("Done");
}
}
The program reads from System.in. If you don't enter anything, nothing will happen.
Not sure why you have 2 Scanners instead of just one.
You have while(choice.equals("yes")) except you never prompt the user to make a choice. The program does do stuff (some of which may not all work properly), but you have to give the program input. What you can do is ask the user a question before the line String choice = scanString.nextLine();.
As a side note, you could use a switch in place of the if and else if's and it might be a little easier to read and understand.