I am getting null output along when i am getting to string method in my program output.
//Main Method
package studentDatabaseApp;
import java.util.Scanner;
public class StudentDatabaseApp {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter number of Students: ");
int numOfStudents = scan.nextInt();
Student[] students = new Student[numOfStudents];
for(int n =0; n < numOfStudents; n++) {
students[n] = new Student();
students[n].enroll();
students[n].payTution();
}
for(int n =0; n < numOfStudents; n++) {
System.out.println(students[n].toString());
}
}
}
//Student Class Code
package studentDatabaseApp;
import java.util.Scanner;
public class Student {
private String firstName;
private String lastName;
private int gradeYear = 0;
private String studentID;
private String courses;
private static int courseCost = 600;
private int tutionBalance = 0;
private static int id = 1000;
//Constructor to enter student name and year for each student
public Student() {
Scanner scan = new Scanner(System.in);
System.out.print("Enter Student First Name: ");
this.firstName = scan.nextLine();
System.out.print("Enter Student Last Name: ");
this.lastName = scan.nextLine();
System.out.print("1 - Freshmen\n2 - Sophmore\n3 - Junior\n4 - Senior\nEnter Student Grade Year: ");
this.gradeYear = scan.nextInt();
//Setting student id
setStudentID();
}
//Unique id and student grade level
private void setStudentID() {
id++;
this.studentID = gradeYear + "" + id;
}
//Create courses so student can enroll
public void enroll() {
do {
System.out.print("Enter course to enroll (Q to Quit): ");
Scanner in = new Scanner(System.in);
String course = in.nextLine();
if(!course.equals("Q")) {
courses = courses + ", " + course;
tutionBalance = tutionBalance + courseCost;
}
else {
break;
}
}while(1 != 0);
}
//Student should able to view their balance and pay the tution
public void viewBalance() {
System.out.println("BALANCE TOTAL: " + tutionBalance);
}
//Total balance
public void payTution() {
viewBalance();
Scanner scan = new Scanner(System.in);
System.out.print("\nEnter your payment: ");
int tutionPaid = scan.nextInt();
tutionBalance = tutionBalance - tutionPaid;
viewBalance();
}
//Student status with their name, ID, course enrolled and balance
#Override
public String toString() {
return "\nSTUDENT NAME: " + firstName + " " + lastName +
"\nGRADE LEVEL: " + gradeYear + " " + "\nSTUDENT ID: " + studentID +
"\nCOURSES ENROLLED: " + courses +
"\nTUTION BALANCE: " + tutionBalance;
}
}
//Console Output
Enter number of Students: 1
Enter Student First Name: bilal
Enter Student Last Name: mujahid
1 - Freshmen
2 - Sophmore
3 - Junior
4 - Senior
Enter Student Grade Year: 4
Enter course to enroll (Q to Quit): Eng 101
Enter course to enroll (Q to Quit): Math 101
Enter course to enroll (Q to Quit): Q
BALANCE TOTAL: 1200
Enter your payment: 1000
BALANCE TOTAL: 200
STUDENT NAME: bilal mujahid
GRADE LEVEL: 4
STUDENT ID: 41001
COURSES ENROLLED: null, Eng 101, Math 101
TUTION BALANCE: 200
The problem is with
private String courses;
You use
courses = courses + course;
Courses is null since it is never initialized. Try changing it to
private String courses = “”;
(This will cause it to have a extra comma in the beginning which you can easily just substring off)
Initialise it with course the first time
if(!course.equals("Q")) {
courses = coursers == null ? course : courses + ", " + course;
...
Related
I got two classes, this one and other called DailyExpenses that's full of getters and setters + constructors etc..
My problem is that I want to get the sum value of all daily expenses user inputs inside the while loop and print the sum after the program is closed, and I don't know how to do it.
Here is my code:
import java.util.Scanner;
import java.util.ArrayList;
public class DailyExpensesMain {
public static void main(String[] args) {
ArrayList<DailyExpenses> expenses = new ArrayList<DailyExpenses>();
Scanner sc = new Scanner(System.in);
boolean isRunning = true;
System.out.println("Enter the date for which you want to record the expenses : ");
String date = sc.nextLine();
while(isRunning) {
System.out.println("Enter category: (quit to exit)");
String category = sc.nextLine();
if(category.equalsIgnoreCase("quit")) {
break;
}
System.out.println("Enter price: ");
double price = sc.nextDouble();
sc.nextLine();
System.out.println("Enter details: ");
String detail = sc.nextLine();
DailyExpenses newExpense = new DailyExpenses(date, category, price, detail);
expenses.add(newExpense);
}
sc.close();
for(DailyExpenses u: newExpense) {
System.out.println("Date: " + u.getDate() + " Category: " + u.getExpenseCategory() + " Price: " + u.getExpensePrice() +
" Detail: " + u.getExpenseDetail());
}
}
}
I still clueless on the situation
I'm doing an assignment that asks a user to input a student name, and then quiz scores until the user chooses to stop. It then calculates the total score and the average of all those scores and outputs them to the screen.
We are moving on to the subject of inheritance and now we are requested to make a class called MonitoredStudent which extends Student. The point of the MonitoredStudent class is to check if the average is above a user inputted average and display whether the student is off academic probation.
I have got most of the program written and when I input just one score (such as 71, when the average I set is 70) it is still displaying that I am on academic probation, even though the one quiz score is above the average I set of 70.
The main issue is that no matter what integer is set for the minimum passing average, I always get a return of false.
I added the "return false" statement in the isOffProbation method as when I add an if-else statement to check if the averageScore (from the Student class) is less than or equal to minPassingAvg eclipse tells me that the method needs a return type of boolean.
public class MonitoredStudent extends Student {
int minPassingAvg;
public MonitoredStudent(){
super();
minPassingAvg = 0;
}
public MonitoredStudent(String name, int minPassingAvg) {
super(name);
this.minPassingAvg = minPassingAvg;
}
public int getMinPassingAvg() {
return minPassingAvg;
}
public void setMinPassingAvg(int minPassingAvg) {
this.minPassingAvg = minPassingAvg;
}
boolean isOffProbation() {
if(getAverageScore() >= minPassingAvg)
return true;
return false;
}
}
This is the Student super class:
public class Student{
private String name;
private double totalScore;
private int quizCount;
public Student(){
name = "";
totalScore = 0;
quizCount = 0;
}
public Student(String n){
name = n;
totalScore = 0;
quizCount = 0;
}
public void setName(String aName){
name = aName;
}
public String getName(){
return name;
}
public void addQuiz(int score){
if(score >= 0 && score <= 100){
totalScore = totalScore + score;
quizCount = quizCount + 1;
}else{
System.out.println("Score must be between 0 and 100, inclusive");
}
}
public double getTotalScore(){
return totalScore;
}
public double getAverageScore(){
return totalScore / quizCount;
}
}
This is the main method:
import java.util.Scanner;
public class MonitoredStudentTester{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
MonitoredStudent monStu = new MonitoredStudent();
String repeat = "n";
int currentScore = 0;
int minPassAv;
System.out.println("Enter the student's name:");
String stuName = scan.next();
Student sName = new Student(stuName);
System.out.println("What is the minimum passing average score: ");
minPassAv = scan.nextInt();
Student stu = new Student();
do {
System.out.println("Enter a quiz score: ");
currentScore = scan.nextInt();
stu.addQuiz(currentScore);
monStu.setMinPassingAvg(currentScore);
System.out.println("Would you like to enter any more scores?: (Y for yes, N for no)");
scan.nextLine();
repeat = scan.nextLine();
}while(repeat.equalsIgnoreCase("y"));
String studName = stu.getName();
double totalScore = stu.getTotalScore();
double avgScore = stu.getAverageScore();
boolean offProb = monStu.isOffProbation();
System.out.println(studName + "'s Total Score is: " + totalScore);
System.out.println(studName + "'s Average Score is: " + avgScore);
System.out.println("Is " + studName + "off academic probation?: " + offProb);
}
}
You main class should be something like this.
public class MonitoredStudentTester {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
MonitoredStudent monStu = new MonitoredStudent();
String repeat = "n";
int currentScore = 0;
int minPassAv;
System.out.println("Enter the student's name:");
monStu.setName(scan.next());
System.out.println("What is the minimum passing average score: ");
minPassAv = scan.nextInt();
do {
System.out.println("Enter a quiz score: ");
currentScore = scan.nextInt();
monStu.addQuiz(currentScore);
monStu.setMinPassingAvg(minPassAv);
System.out.println("Would you like to enter any more scores?: (Y for yes, N for no)");
scan.nextLine();
repeat = scan.nextLine();
} while (repeat.equalsIgnoreCase("y"));
String studName = monStu.getName();
double totalScore = monStu.getTotalScore();
double avgScore = monStu.getAverageScore();
boolean offProb = monStu.isOffProbation();
System.out.println(studName + "'s Total Score is: " + totalScore);
System.out.println(studName + "'s Average Score is: " + avgScore);
System.out.println("Is " + studName + "off academic probation?: " + offProb);
}
}
When using inheritance you just need to create an object of child class.
This is my code for printing a shopping list. It works fine when I put the data manually at runtime through keyboard. But when I direct an input.txt file as an argument in command line it throws NoSuchElementException after 1st iteration.
I think it might have to do with the sequence of using Scanner.next() and Scanner.nextInt() but not sure.
How do I fix this?
import java.io.*;
import java.util.*;
class Product
{
Scanner sc = new Scanner(System.in);
int productID;
String productName;
String productType;
float productPrice;
Product()
{
// Do Nothing.
}
void createProduct()
{
System.out.println("Enter the Product ID: ");
productID = sc.nextInt();
System.out.println("Enter the Product Name: ");
productName = sc.next();
System.out.println("Enter the Product Type: ");
productType = sc.next();
System.out.println("Enter the Product Price: ");
productPrice = sc.nextFloat();
}
Product(int pID, String pName, String pType, float pPrice)
{
productID = pID;
productName = pName;
productType = pType;
productPrice = pPrice;
}
void showIdentification()
{
System.out.println(productID + " " + productName);
}
void showDetail()
{
System.out.println(productID + " " + productName + " " + productType + " " + productPrice);
}
}
class Shop
{
int n = 10;
Product list[] = new Product[n];
void createList()
{
for(int i=0; i<n; i++)
{
System.out.println("Product No. " + (i+1));
Product o = new Product();
o.createProduct();
o.showDetail();
list[i] = o;
}
}
void viewAllProducts()
{
for(int i=0; i<n; i++)
{
list[i].showIdentification();
}
}
}
class ShopList
{
public static void main(String[] args)
{
Shop sList = new Shop();
sList.createList();
sList.viewAllProducts();
}
}
Here is the input file :-
1001 CadburyA ChocolateA 15.00
1002 CadburyB ChocolateB 16.00
1003 CadburyC ChocolateC 17.00
1004 CadburyD ChocolateD 18.00
1005 CadburyE ChocolateE 19.00
1006 CadburyF ChocolateF 20.00
1007 CadburyG ChocolateG 21.00
1008 CadburyH ChocolateH 22.00
1009 CadburyI ChocolateI 23.00
1010 CadburyJ ChocolateJ 24.00
and here is the exception I got:-
java ShopList < input.txt
Product No. 1
Enter the Product ID:
Enter the Product Name:
Enter the Product Type:
Enter the Product Price:
1001 CadburyA Chocolate 15.0
Product No. 2
Enter the Product ID:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at Product.createProduct(ShopList.java:19)
at Shop.createList(ShopList.java:59)
at ShopList.main(ShopList.java:95)
You have to make Scanner static:
class Product
{
// There is only one System.in - the Scanner can be shared between
// all instances
static Scanner sc = new Scanner(System.in);
int productID;
String productName;
String productType;
float productPrice;
Product ()
{
// Do Nothing.
}
void createProduct()
{
System.out.println(" Enter the Product ID: ");
productID = sc.nextInt ();
// for debugging, I inserted the last value in the printlns:
System.out.println (productID + " Enter the Product Name: ");
productName = sc.next ();
System.out.println (productName + " Enter the Product Type: ");
productType = sc.next ();
System.out.println (productType + " Enter the Product Price: ");
productPrice = sc.nextFloat ();
System.out.println (productPrice + " ");
/* Helpless attemps to find out, if we need to consume the line break :)
String s = "dummy";
while (s != "\n") {
s = sc.next ();
System.out.println ("<" + s + ">");
}
*/
}
No other modifications were made.
Well, not exactly. As continental European, I had to tell the system, that my numbers are dot delimited or better, pass in comma delimited ones.
cat choco.lst | sed 's/\./,/' | java ShopList
That might not be the case on your system.
Well, and the Scanner in ShopList, which is not used, shall vanish too.
I need to be able to verify an age in the main class so for example if the name and age is added to the queue and when the person tries to leave if the age is less than 18 then a message appears saying "left because too young" or if the person is over 18 then a message appears saying "person left"
This is my main Class
public static void main(String[] args)
{
Queue q = new Queue();
Scanner k = new Scanner(System.in);
System.out.print("Join (j), leave (l) or end (e)? ");
String action = k.nextLine();
while (!action.equalsIgnoreCase("e"))
{
if (action.equalsIgnoreCase("j"))
{
System.out.print("Enter Name ");
String Name = k.nextLine();
System.out.print("Enter Age : ");
int Age = k.nextInt();
Person p1 = new Person(Name,Age);
q.add(p1);
System.out.println(Name + " Age " + Age + " Joined");
}
else if (action.equalsIgnoreCase("l"))
{
if (!q.isEmpty())
{
System.out.println(q.remove() + " Person Left");
}
else
{
System.out.println("Queue Empty");
}
}
else
{
System.out.println("Invalid operation");
}
System.out.print("Join (j), leave (l) or end (e)? ");
action = k.nextLine();
I also have a person class with the name and age and also a Queue Class.
Why can't you just add an if statement?
int Age = k.nextInt();
Person p1 = new Person(Name, Age);
q.add(p1);
if (Age < 18) {
q.remove(p1);
System.out.println("left because too young");
}
In my code I am to input multiple students and have a method check to see if any of the students are repeated (by checking ID number) but I cant seem to be able to set multiple students with my current code and save them. From my current code is there any way to be able to set multiple students or will I have to change my code completely
import java.util.Scanner;
public class Registrar
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String string1 = " ";
while(string1 != "1")
{
System.out.println("Please input full name name of student: ");
string1 = input.next(); // user input of name
if (string1 != "0"){
break;
}
System.out.println("Please input Student ID (if done enter 0): ");
String string2 = input.next(); // user input of ID
System.out.println("Please input Students Credits: ");
int inputCredits = input.nextInt(); // User input of Credits
System.out.println("Please input Student's Total Grade Points Earned: ");
double getPoints = input.nextDouble();
double GPA = getPoints/inputCredits; //User input of Grade Points Earned and Divide by Credits to get GPA
Student first = new Student(string1, string2, inputCredits, GPA);
System.out.println( "Name: " + first.getName() + "\nUser ID: " + first.getId() + "\nCredits: " + first.getCredits() + "\nGrade Point Average: " + first.getGradePoints() );
}
}
}
This is my Student Class
public class Student {
private String name;
private String idnum;
private int credits;
private double gradePoints;
public Student(String n, String id, int c, double gp){
name = n;
idnum = id;
credits = c;
gradePoints = gp;
}
public String getName(){
return name;
}
public String getId(){
return idnum;
}
public int getCredits(){
return credits;
}
public double getGradePoints(){
return gradePoints;
}
}
Try this code. better implementation with collection.
Scanner input = new Scanner(System.in);
String string1 = " ";
System.out.println("Number of students to be entered");
int s = input.nextInt();
List<Student> studentList = new ArrayList<Student>();
for(int i = 0; i<s; i++) {
System.out.println("Please input full name of student: ");
string1 = input.next(); // user input of name
System.out.println("Please input Student ID (if done enter 0): ");
String string2 = input.next(); // user input of ID
System.out.println("Please input Students Credits: ");
int inputCredits = input.nextInt(); // User input of Credits
System.out.println("Please input Student's Total Grade Points Earned: ");
double getPoints = input.nextDouble();
double GPA = getPoints/inputCredits; //User input of Grade Points Earned and Divide by Credits to get GPA
Student student = new Student(string1, string2, inputCredits, GPA);
System.out.println( "Name: " + first.getName() + "\nUser ID: " + first.getId() + "\nCredits: " + first.getCredits() + "\nGrade Point Average: " + first.getGradePoints() );
studentList.add(student);
}
You can take a user input(How many student you want to save and run a loope to take details of input. The rough code will be like this:
System.out.println("Enter how many student you want to enter");
int s = input.nextInt();
for(int i = 0; i<s; i++) {
//Code for take details of user
}
//Then you can print the details of student in similar way.