This program is created to store all student details and course details. The problem happens when trying to remove a student from this array it creates a error but only happens if you add a student to the array in option 2 in the program. You are able to remove a student when you haven't added a student it's only when you add a student that the error happens.
Main:
package javacoursework;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
/**
*
* #author zhunt
*/
public class JavaCoursework {
static student[] students;
static courses[] course;
public static void main( String[] args )
throws FileNotFoundException {
//creating File instance to reference text file in Java
File text = new File("students.txt");
Scanner scanner = new Scanner(text);
while(scanner.hasNextLine()){
String line = scanner.nextLine();
String[] split = line.split(",");
student.FName.add(split[0]);
student.SName.add(split[1]);
student.DOB.add(split[2]);
student.Address.add(split[3]);
student.Gender.add(split[4]);
}
File course = new File("course.txt");
Scanner scan = new Scanner(course);
while(scan.hasNextLine()){
String info = scan.nextLine();
String[] split2 = info.split(",");
courses.CName.add(split2[0]);
courses.Lecturer.add(split2[1]);
courses.Enrolled.add(split2[2]);
}
Scanner kb = new Scanner( System.in );
int x;
//students = new Student[0];
students = new student[2];
do
{
System.out.println();
System.out.println( "Do you want to:" );
System.out.println( "\t0) View Students" );
System.out.println( "\t1) View Students' Details" );
System.out.println( "\t2) Add a Student" );
System.out.println( "\t3) Remove a Student" );
System.out.println( "\t4) View Courses Details" );
System.out.println( "\t5) Exit Progarm" );
x = Integer.parseInt(kb.nextLine());
switch (x)
{
case 0:
student.ViewStudents();
break;
case 1:
student.ViewDetails();
break;
case 2:
student.addStudent();
break;
case 3:
student.removeStudent();
break;
case 4:
courses.Report();
break;
default:
}
}
while( x != 5);
}
}
Student:
package javacoursework;
import java.util.Scanner;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author zhunt
*/
public class student {
// Make 'static' so as to maintain the same
// collection throughout all instances of Student.
public static java.util.List<String> FName = new java.util.ArrayList<>();
public static java.util.List<String> SName = new java.util.ArrayList<>();
public static java.util.List<String> DOB = new java.util.ArrayList<>();
public static java.util.List<String> Address = new java.util.ArrayList<>();
public static java.util.List<String> Gender = new java.util.ArrayList<>();
public static void addStudent(){
if(FName.size()>19){
System.out.print("The maximum amount of 20 students are currently being stored in the system. If you wish to add a new student you need to remove an existing student from the program");
}
else{
Scanner kb = new Scanner( System.in );
String Fname;
String Sname;
String Dob;
String address;
String gender;
System.out.println( "\tInput Information" );
System.out.println( "\tFirst Name: ");
Fname = kb.nextLine();
System.out.println( "\tSurname: ");
Sname = kb.nextLine();
System.out.println( "\tDate of Birth(dd-mm-yyyy): ");
Dob = kb.nextLine();
System.out.println( "\tAddress: ");
address = kb.nextLine();
System.out.println( "\tGender(Male/Female): ");
gender = kb.nextLine();
if(Fname!=""&&Sname!=""&&Dob!=""&&address!=""&&gender!="")
{
if(gender.equalsIgnoreCase("Female")||gender.equalsIgnoreCase("Male")){
FName.add(Fname);
SName.add(Sname);
DOB.add(Dob);
Address.add(address);
Gender.add(gender);
System.out.print(Fname+" "+Sname+" has been added to the system");
}
else{
System.out.print("Gender must be entered as male/female. Please try again");
}
}
else{
System.out.print("You may not leave out any of the required information. Please try again");
}
}
}
public static void ViewDetails()
{
Scanner kb = new Scanner( System.in );
String i;
System.out.println( "Enter the full name of the student you wish to view: ");
i = kb.nextLine();
String[] name = i.split(" ");
boolean found=false;
for(int x=0; x <FName.size();x++){
if(FName.get(x).equalsIgnoreCase(name[0]))
{
if(SName.get(x).equalsIgnoreCase(name[1]))
{
found=true;
System.out.print("Student found here are the students full details: ");
System.out.print(FName.get(x)+", "+SName.get(x)+", "+DOB.get(x)+", "+Address.get(x)+", "+Gender.get(x));
}
}
}
if(found==false)
{
System.out.print("Student entered cannot be found.");
}
}
public static void removeStudent(){
Scanner kb = new Scanner( System.in );
String i;
System.out.println( "Enter the full name of the student you wish to remove: ");
i = kb.nextLine();
String[] name = i.split(" ");
boolean found=false;
for(int x=0; x <FName.size();x++){
if(FName.get(x).equalsIgnoreCase(name[0]))
{
if(SName.get(x).equalsIgnoreCase(name[1]))
{
found=true;
FName.remove(x);
SName.remove(x);
DOB.remove(x);
Address.remove(x);
Gender.remove(x);
System.out.print(FName.get(x)+" "+SName.get(x)+" has been removed from the course");
}
}
}
if(found==false)
{
System.out.print("Student entered cannot be found. Please try again");
}
}
public static void ViewStudents(){
for( int i = 0; i < FName.size(); i++)
{
System.out.println(SName.get(i)+", "+FName.get(i));
}
}
}
Course:
package javacoursework;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author zhunt
*/
import java.util.Collections;
public class courses {
// Make 'static' so as to maintain the same
// collection throughout all instances of Courses.
public static java.util.List<String> CName = new java.util.ArrayList<>();
public static java.util.List<String> Lecturer = new java.util.ArrayList<>();
public static java.util.List<String> Enrolled = new java.util.ArrayList<>();
public static void Report(){
int enrolled=student.FName.size();
double male=Collections.frequency(student.Gender, "Male");
male=male+Collections.frequency(student.Gender, "male");
male=(male / enrolled)*100;
double female=100-male;
System.out.print("Course: "+CName.get(0)+"\nLecturer: "+Lecturer.get(0)+"\nStudents Enrolled: "+enrolled+"\nPercentage Male: "+String.format("%.2f", male)+"%"+"\nPercentage Female: "+String.format("%.2f", female)+"%");
}
}
Error:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 19, Size: 19
at java.util.ArrayList.rangeCheck(ArrayList.java:659)
at java.util.ArrayList.get(ArrayList.java:435)
at javacoursework.student.removeStudent(student.java:124)
at javacoursework.JavaCoursework.main(JavaCoursework.java:84)
C:\Users\xxray\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
In code of Student#removeStudent, when the student was found, you're deleting it and then trying to access deleted student by its index.
Consider next case:
Students list has 20 elements (last student Bob has an index of x = 19)
We're deleting Bob from the list by calling FName.remove(x)
Students list now contains only 19 elements
We're trying to access the 20th element of the list by calling System.out.print(FName.get(x)+" "+SName.get(x)+" has been removed from the course"). And because the list has only 19 elements, we're getting IndexOutOfBoundsException. To fix this issue, save removed items into local variables and print them afterwards.
After this two improvement the code will be look like some think like that:
fname = FName.remove(x);
sname = SName.remove(x);
DOB.remove(x);
Address.remove(x);
Gender.remove(x);
System.out.print(fname + " " + sname + " has been removed from the course");
Related
i was told to make a program like that, after input i can see the data
This is my code, please help i had search how to do it but i mostly only if the data is already known not by user input.
is it using an array or using for?
i search many time but i still dont find like mine
ive tried using array but i dont know how to get the array like, there is 3 user input in one array. mostly i found just using one user input
and sometime i get the error where the string cannot meet the int type
import java.util.Scanner;
public class Case7{
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
int choose=0;
String name ="";
String pos = "";
int age = 0;
do{
System.out.println("JOB VACANCY");
System.out.println("===========");
System.out.println("1. Insert new data");
System.out.println("2. List of staff");
System.out.println("3. Search staff");
System.out.println("4. Exit");
System.out.print("Choose: ");
choose = input.nextInt();
if (choose == 1)
{
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
do{
System.out.print("Input staff name: ");
name = input.nextLine();
}while(name.length() < 3 || name.length() > 20);
do{
System.out.print("Input staff position [Manager | Analyst | Programmer]: ");
pos=input.nextLine();
}while(!pos.equalsIgnoreCase("Manager") && !pos.equalsIgnoreCase("Analyst") && !pos.equalsIgnoreCase("Programmer"));
do{
System.out.print("Input staff age: ");
age=input.nextInt();
}while(age <= 17);
System.out.println("Data has been added!");
input.nextLine();
input.nextLine();
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
}
else if (choose == 2)
{
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
for (int i = 1; i < 6 ; i++ )
{
System.out.println("Staff ID :" + i);
System.out.println("==============");
System.out.println("1. name : " +name );
System.out.println("2. position : " +pos );
System.out.println("3. age : " +age );
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
}
}
Can I suggest a radically different implementation?
You can use a switch to score the options and You can use a LinkedList to store all the new staff member dinamically.
Here's my commented code:
static LinkedList<Staffer> staff=new LinkedList<>(); //ours database
static Scanner input = new Scanner (System.in);
public static void main(String[] args) {
String s="";
int number=-1;
while(number!=4){ //if your choice is 4, we can exit!
//Chooser:
System.out.print("JOB VACANCY\n===========\n1. Input data\n2. Show Data\n3.Delete Data\n4.£xit\nYour choice: ");
s=input.nextLine();
if(s.matches("\\d+")){ //Check if s is a number
number=Integer.parseInt(s);
switch(number){
case 1: input(); break;
case 2: showData(); break;
case 3: deleteData(); break;
case 4: System.out.println("Goodbye!"); break;
default: System.out.println("Number not valid. Try again!");
}
}else
System.out.println("Number not valid. Try again!");
}
}
private static void showData() {
for(Staffer st:staff)
System.out.println(st);
}
private static void deleteData(/*parameters*/) {
// You can delete a staffer by passing the name, for example
}
private static void input() {
//Plese, implements your data control options...
String name, position;
int age;
System.out.print("Name: ");
name=input.nextLine();
System.out.print("Position: ");
position=input.nextLine();
System.out.print("Age: ");
age=(Integer.parseInt(input.nextLine()));
Staffer staffer=new Staffer(name,position, age);
staff.add(staffer);
}
public static class Staffer{ //a staff member has 3 parameter: name, position and age... You can add others
/*You should store the name using only upperCase or LowerCase, or
* John Williams != john williams != JOHN WILLIAMS and you can have three times
* the same people.
*
* The position can be converted in enum for the same reason.
*/
private String name, position;
private int age;
public Staffer(String name, String position, int age){
this.name=name;
this.position=position;
this.age=age;
}
#Override
public String toString(){
return "Mr. "+name+", "+position+" (age: "+age+")";
}
}
You can see the following example output:
.
Obviously, you have to improve the output and all the data check options.
I'm trying to create an array of math students, science students, and computer students based on the user input.
So basically the user should choose what student they want to add and then enter the student details.
Below I have added the code I have so far:
Main Java class:
public class Lab4 {
public static final int DEBUG = 0;
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Student s[] = new Student[10];
s[0] = new MathStudent(4,5);
s[1] = new MathStudent(5,7);
s[2] = new MathStudent(2,8);
s[3] = new MathStudent(3,6);
s[4] = new ScienceStudent(8,9);
s[5] = new ScienceStudent(3,6);
s[6] = new ScienceStudent(4,9);
s[7] = new ComputerStudent(6,12);
s[8] = new ComputerStudent(11,14);
s[9] = new ComputerStudent(13,17);
}
}
Student class:
public class Student {
private String name;
private int age;
public String gender = "na";
public static int instances = 0;
// Getters
public int getAge(){
return this.age;
}
public String getName(){
return this.name;
}
// Setters
public void setAge(int age){
this.age = age;
}
public void setName(String name){
if (Lab4.DEBUG > 3) System.out.println("In Student.setName. Name = "+ name);
this.name = name;
}
/**
* Default constructor. Populates name,age,gender,course and phone Number
* with defaults
*/
public Student(){
instances++;
this.age = 18;
this.name = "Not Set";
this.gender = "Not Set";
}
/**
* Constructor with parameters
* #param age integer
* #param name String with the name
*/
public Student(int age, String name){
this.age = age;
this.name = name;
}
/**
* Gender constructor
* #param gender
*/
public Student(String gender){
this(); // Must be the first line!
this.gender = gender;
}
/**
* Destructor
* #throws Throwable
*/
protected void finalize() throws Throwable{
//do finalization here
instances--;
super.finalize(); //not necessary if extending Object.
}
public String toString (){
return "Name: " + this.name + " Age: " + this.age + " Gender: "
+ this.gender;
}
public String getSubjects(){
return this.getSubjects();
}
}
MathStudent class:
public class MathStudent extends Student {
private float algebraGrade;
private float calculusGrade;
public MathStudent(float algebraGrade, float calculusGrade) {
this.algebraGrade = algebraGrade;
this.calculusGrade = calculusGrade;
}
public MathStudent() {
super();
algebraGrade = 6;
calculusGrade = 4;
}
// Getters
public void setAlgebraGrade(float algebraGrade){
this.algebraGrade = algebraGrade;
}
public void setCalculusGrade(float calculusGrade){
this.calculusGrade = calculusGrade;
}
// Setters
public float getAlgebraGrade() {
return this.algebraGrade;
}
public float getCalculusGrade() {
return this.calculusGrade;
}
/**
* Display information about the subject
* #return
*/
#Override
public String getSubjects(){
return("Algebra Grade: " + algebraGrade + " Calculus Grade: "
+ calculusGrade);
}
}
scienceStudent class:
public class ScienceStudent extends Student {
private float physicsGrade;
private float astronomyGrade;
/**
* Default constructor
*/
public ScienceStudent() {
super();
physicsGrade = 6;
astronomyGrade = 7;
}
public ScienceStudent(float physicsGrade, float astronomyGrade) {
this.physicsGrade = physicsGrade;
this.astronomyGrade = astronomyGrade;
}
// Getters
public void setPhysicsGrade(float physicsGrade){
this.physicsGrade = physicsGrade;
}
public void setAstronomyGrade(float astronomyGrade){
this.astronomyGrade = astronomyGrade;
}
// Setters
public float getPhysicsGrade() {
return this.physicsGrade;
}
public float getAstronomyGrade() {
return this.astronomyGrade;
}
/**
* Display information about the subject
* #return
*/
#Override
public String getSubjects(){
return("Physics Grade: " + physicsGrade + " Astronomy Grade: "
+ astronomyGrade);
}
}
computerStudent class:
public class ComputerStudent extends Student {
private float fortanGrade;
private float adaGrade;
/**
* Default constructor
*/
public ComputerStudent() {
super();
fortanGrade = 4;
adaGrade = 9;
}
public ComputerStudent(float fortanGrade, float adaGrade) {
this.fortanGrade = fortanGrade;
this.adaGrade = adaGrade;
}
// Getters
public void setFortanGrade(float fortanGrade){
this.fortanGrade = fortanGrade;
}
public void setAdaGrade(float adaGrade){
this.adaGrade = adaGrade;
}
// Setters
public float getFortanGrade() {
return this.fortanGrade;
}
public float getAdaGrade() {
return this.adaGrade;
}
/**
* Display information about the subject
* #return
*/
#Override
public String getSubjects(){
return("Fortan Grade: " + fortanGrade + " Ada Grade: " + adaGrade);
}
}
How Would I go about this?
You can ask for the number of students with type on each input and dynamically create the object.
Here is an example
System.out.println("Enter total number of students");
int n = scannerObject.nextInt();
Student students[] = new Students[n];
for(int i=0;i<n;i++){
int type = scannerObject.nextInt();
if(type == 1)
students[i] = new MathStudent();
}
Similarly, you can write for others.
For allowing user to enter his choice as input
You can do this(interpreted by your comments)
Pseudo code -
Print:
Enter 1 for math student
Enter 2 for Science student
Enter 3 for Comp student
Input choice
Now in your code use either multiple if else or better switch statement
switch(choice){
case 1: create object of math student
break;
case 2: create object of science student
break;
case 3:create object of comp student
break;
default: if not above by default do this
}
You could use an ArrayList and switch case to make your life easier. Your code should be like this:
import java.util.ArrayList;
import java.util.Scanner;
public class Students {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<Student> students = new ArrayList<>();
int age;
boolean addMore = true;
String name, gender;
Student st;
while (addMore) {
System.out.print("Give lesson (Computers, Math, Science): ");
String lesson = input.nextLine();
switch (lesson) {
case "Math":
// Read student's info
System.out.print("Give student's name: ");
name = input.nextLine();
System.out.print("Give student's gender: ");
gender = input.nextLine();
System.out.print("Give student's age: ");
age = input.nextInt();
System.out.print("Give student's Algebra grade: ");
int alg = input.nextInt();
System.out.print("Give student's Calculus grade: ");
int calc = input.nextInt();
input.nextLine(); // This is needed in order to make the next input.nextLine() call work (See here: https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo )
// Create the student object and pass info
st = new MathStudent(alg, calc);
st.setName(name);
st.setAge(age);
st.gender = gender;
students.add(st); // Adding the student in the list
System.out.println(st);
System.out.println(((MathStudent) st).getSubjects());
break;
case "Science":
// Read student's info
System.out.print("Give student's name: ");
name = input.nextLine();
System.out.print("Give student's gender: ");
gender = input.nextLine();
System.out.print("Give student's age: ");
age = input.nextInt();
System.out.print("Give student's Physics grade: ");
int physics = input.nextInt();
System.out.print("Give student's Astronomy grade: ");
int astronomy = input.nextInt();
input.nextLine();// This is needed in order to make the next input.nextLine() call work (See here: https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo )
// Create the student object and pass info
st = new ScienceStudent(physics, astronomy);
st.setName(name);
st.setAge(age);
st.gender = gender;
students.add(st); // Adding the student in the list
System.out.println(st);
System.out.println(((ScienceStudent) st).getSubjects());
break;
case "Computers":
// Read student's info
System.out.print("Give student's name: ");
name = input.nextLine();
System.out.print("Give student's gender: ");
gender = input.nextLine();
System.out.print("Give student's age: ");
age = input.nextInt();
System.out.print("Give student's Fortran grade: ");
int fortran = input.nextInt();
System.out.print("Give student's Ada grade: ");
int ada = input.nextInt();
input.nextLine();// This is needed in order to make the next input.nextLine() call work (See here: https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo )
// Create the student object and pass info
st = new ComputerStudent(fortran, ada);
st.setName(name);
st.setAge(age);
st.gender = gender;
students.add(st); // Adding the student in the list
System.out.println(st);
System.out.println(((ComputerStudent) st).getSubjects());
break;
default:
System.out.println("Wrong lesson");
addMore = false;
break;
}
if (addMore) {
System.out.println("Add another student? (y/n)");
String ans = input.nextLine();
addMore = ans.equals("y");
} else {
addMore = true;
}
}
System.out.println("Students");
for (Student student : students) {
System.out.println(student);
}
}
}
The code above asks for the lesson name (Computers, Math, Science) and if it is one of them it reads all the info about the student and the grades for the corresponding lesson. It creates the objects and adds them in the list students. When all info is added, it asks the user if he/she wants to add another student and if he writes the letter y, then all these are made again, until the user answers something different than the letter y (the letter n in most cases). After these it prints all the students' info by itterating the list.
Note: I think in your code for the ComputerStudent class, you meant to name the variable fortranGrade and not fortanGrade (change it also in the getSubjects function).
Links:
Java ArrayList
Switch Case in Java
Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods
I hope this helped you. If you have any questions or wanted something more you can do it.
UPDATE
The code below does the same things, but it uses for loop instead of switch case, as you asked in your comment.
package students;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Lab4 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<Student> students = new ArrayList<>();
int age;
boolean addMore = true;
String name, gender;
Student st;
ArrayList<Class<?>> studentClasses = new ArrayList<>();
studentClasses.add(MathStudent.class);
studentClasses.add(ComputerStudent.class);
studentClasses.add(ScienceStudent.class);
while (addMore) {
System.out.print("Give lesson (Computers, Math, Science): ");
String lesson = input.nextLine();
addMore = false;
for (Class studentClass : studentClasses) {
try {
st = (Student) studentClass.newInstance();
if (st.getLessonName().equals(lesson)) {
// Read student's info
System.out.print("Give student's name: ");
name = input.nextLine();
System.out.print("Give student's gender: ");
gender = input.nextLine();
System.out.print("Give student's age: ");
age = input.nextInt();
System.out.print("Give student's " + st.getSubjectsNames()[0] + " grade: ");
float firstSubj = input.nextFloat();
System.out.print("Give student's " + st.getSubjectsNames()[1] + " grade: ");
float secondSubj = input.nextFloat();
input.nextLine(); // This is needed in order to make the next input.nextLine() call work (See here: https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo )
// Create the student object and pass info
st = (Student) studentClass.getConstructor(float.class, float.class).newInstance(firstSubj, secondSubj);
st.setName(name);
st.setAge(age);
st.gender = gender;
students.add(st); // Adding the student in the list
System.out.println(st);
System.out.println(st.getSubjects());
addMore = true;
break;
}
} catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
Logger.getLogger(Lab4.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (addMore) {
System.out.println("Add another student? (y/n)");
String ans = input.nextLine();
addMore = ans.equals("y");
} else {
System.out.println("Wrong lesson. Try again.");
addMore = true;
}
}
System.out.println("Students");
for (Student student : students) {
System.out.println(student);
}
}
}
You also need to add the functions in the classes as mentioned bellow:
Student class:
public String getLessonName(){
return "";
}
public String[] getSubjectsNames(){
return new String[] {"", ""};
}
MathStudent class:
#Override
public String[] getSubjectsNames(){
return new String[] {"Algebra", "Calculus"};
}
#Override
public String getLessonName(){
return "Math";
}
ComputerStudent class:
#Override
public String[] getSubjectsNames(){
return new String[] {"Fortran", "Ada"};
}
#Override
public String getLessonName(){
return "Computers";
}
ScienceStudent class:
#Override
public String[] getSubjectsNames(){
return new String[] {"Physics", "Astronomy"};
}
#Override
public String getLessonName(){
return "Science";
}
Changes: The code firstly creates an arraylist with the student classes (studdentClasses) and adds all the classes for the students that are currently in the project (MathStudent, ComputerStudent, ScienceStudent). Then the user adds the lesson's name. Then (instead of the switch case) there is a for loop which itterates through the studdentClasses list and checks if the lesson's name that the user has written is the same with a student's class by using the getLessonName function. After that all the info for the student are asked and the grades for the subjects, and for the question (Give student's Physics grades) it uses the function getSubjectsNames. All the other things are like before.
You have a main class, that's what you need essentially, but you need to read from command line. Great, run from command line. Once you run, pay attention to what you did, you can pass parameters there as well. once you pass parameters, they go in line. This line is logically splitable, so split it within you code. for instance by pair of numbers after some key word like science and until next keyword and put again from java and ask a new question once you there.
I'm encountering an issue on a program I'm compiling. i got to display the actual calculation on function 2.The main program is called display11 and I'm calling the functions on the other class. can't figure it out whats wrong that is not displaying the loop. thanks a lot
import java.util.Scanner;
/**
*
* #author ec1302696
*/
public class Functions
{
private int n;
public void string_function(String name)
{
int optionChosen;
String fname;
String sname;
Scanner keyboard = new Scanner(System.in);
Scanner sc = new Scanner(System.in);
Functions fun = new Functions();
System.out.println("Please enter full name");
fname = sc.nextLine(); //accept first name entered by user
//****enter as a comment for now fun.first(fname);
fun.createname(fname);// this create name
//display this is option 1,administrator name admin
//ask for full name for generating username
//call createname passing the username
}
public void number_function(String admin)
{
{
int n, c, fact = 1;
System.out.println("Enter a number to calculate it's factorial");
Scanner in = new Scanner(System.in);
n = in.nextInt();
if ( n < 0 )
System.out.println("Number should be non-negative.");
else
{
for ( c = 1 ; c <= n ; c++ )
fact = fact*c;
System.out.println("Factorial of "+n+" is = "+fact);
}
// return fact;
//this is option 2 ,administrator name admin
//read the factorial
//calcualte the fatorial
// print it
}
}
public void createname(String username)
{
String fname = fname.substring(0,1);
System.out.println("The usernameis " + fname);
//string calcualte the string function to find the first letter ,and second name.
//concatenate and print it.
}
}
import java.util.Scanner;
/**
*
* #author ec1302696
*/
public class Display11 {
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
Functions fun = new Functions();// this create teh functions
int optionChosen;
String admin;
Scanner keyboard = new Scanner(System.in);
Scanner sc = new Scanner(System.in);
System.out.println("Please enter your name");
admin = keyboard.nextLine();
{
System.out.println("Welcome please select option from menu below");
}
System.out.println("OPTION 1 – USERNAME");
System.out.println("OPTION 2 - CALCULATE THE FACTORIAL");
System.out.println("OPTION 3 - EXIT");
optionChosen = keyboard.nextInt();
if (optionChosen == 1)
{
fun.string_function(admin);
}
else if (optionChosen == 2) {
{
fun.number_function(admin);
}
}
else if (optionChosen == 3)
{
}
}
}
If you need to show the calculation of the factorial, change the calculation loop to something like this:
StringBuilder result = new StringBuilder("Factorial of ").append(n).append(" is ");
for ( c = n ; c >0 ; c-- )
{
result.append(c);
if(c>1)
{
result.append(" * ");
}
fact = fact*c;
}
result.append(" = ").append(fact);
System.out.println(result);
Can't figure out this compiling error...
import java.util.*;
import java.util.Scanner;
import java.io.*;
/**
* Write a description of class Bookings here.
*
* #author (your name)
* #version (a version number or a date)
*/
public class Bookings
{
int day = 5;
int hour = 8;
boolean RunMeOnce = false;
Scanner input = new Scanner(System.in);
Scanner scan = new Scanner(System.in);
String fileName;
ConferenceRooms[] conRoom = new ConferenceRooms[3]; // 0 = room 1, 1 = room 2, 2 = room 3
MeetingRooms[] meetRoom = new MeetingRooms[3];
OfficeRooms[] offRoom = new OfficeRooms[3];
public Bookings(String [] args){
}
public void main(){
if (RunMeOnce = false)
{
for(int i=0; i<3; i++){
conRoom[i] = new ConferenceRooms(); //<<<<<<< ERROR OCCURS HERE
meetRoom[i] = new MeetingRooms();
offRoom[i] = new OfficeRooms();
}
RunMeOnce = true;
}
System.out.println("Hello and welcome to One Trinity Greens Room Booking, please choose an option from the list below.");
System.out.println("1. View availabile rooms");
System.out.println("2. Make a booking");
System.out.println("3. Amend a booking");
System.out.println("4. Delete a booking");
int selection = input.nextInt();
switch(selection){
case 1:
for(int i=0; i<3; i++){
System.out.println("Conference Rooms " + i+1);
conRoom[i].conferenceBookings();
System.out.println("Meeting Rooms " + i+1);
meetRoom[i].meetingBookings();
System.out.println("Office Rooms " + i+1);
offRoom[i].officeBookings();
}
break;
case 2:
break;
case 3:
break;
case 4:
break;
}
}
public void searchRooms(){
}
public void accessAvailability(){
}
public void viewBookings(){
}
public void searchBusiness(){
}
public void addBooking(){
}
public void deleteAllBookings(){
}
public void amendBooking(){
}
public void cancelBooking(){
}
}
public ConferenceRooms(String pbusinessName, String proomType, String pavailability, String proomInformation, String pmeetingBookings){
super(pbusinessName, proomType, pavailability);
roomInformation = proomInformation;
}
Oh My.. you have a lot of errors...
1. boolean RunMeOnce = false; // '=' is assigning, '==' is comparing
This is not declared as static . So, you will need an object of type Bookings to call it.
Change your code in main() to
Bookings bk = new Bookings();
if (bk.RunMeOnce)
2. You dont need 2 Scanners to the same Stream (InputStream)
Scanner input = new Scanner(System.in);
Scanner scan = new Scanner(System.in);
3. Show us your conferenceRoom and other classes for discovering more errors :)
You are not calling the constructor correctly. If the ConferenceRooms constructor you've provided is the only one you have, then it's clear why you're getting the error: provide the missing arguments!
package michael.week.pkg5;
class Employee {
String Fname ;
String Lname;
String PhoneNum;
String Address;
void setFirst(String First){
Fname = First ;
}
void setlast(String Last){
Lname = Last ;
}
void setAddress (String address){
Address = address ;
}
void setPhone (String Phone){
PhoneNum = Phone ;
}
void display (){
System.out.println ("the Fist name is :"+ Fname + " , the last name is : " + Lname + " ,the address is : "+ Address+ " ,the phone is : "+ PhoneNum);
}
}
package michael.week.pkg5;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class MichaelWeek5 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
class Stck {
Employee stck [] = new Employee[10];
int x ;
void stck (){
x= -1 ;
}
Employee push (Employee item){
if (x == 9){
System.out.println ("Stack is full");
}else stck[++x] = item ;
return stck[x];
}
Employee pop (){
if (x <0){
System.out.println (" Stack underflow");
return stck [x];
}else
return stck[x++];
}
}
InputStreamReader inp = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(inp);
String info2 = null ;
Stck obj = new Stck();
Employee obj2 = new Employee ();
int w = -1 ;
for (int r=1 ;r>0; ){
System.out.println("please enter add to add new employee");
System.out.println("please enter pop to pop the last added employee");
System.out.println("please enter exit to exit");
String choice = br.readLine();
if(choice.equals("add")){
System.out.println(w);
if (w >= 9){
System.out.println("you reached the maxmum number !");
continue ;
}
else {
w++;
obj.stck ();
String info ;
System.out.println ("please enter Employee first name :");
info = br.readLine();
System.out.println ("please enter Employee last name name :");
info = br.readLine();
System.out.println ("please enter Employee address :");
info = br.readLine();
System.out.println ("please enter Employee phone number :");
info = br.readLine();
}
} else if(choice.equals("pop")){
obj.pop();
w--;
}else if(choice.equals("exit"))
break ;
else {System.out.println (choice + " is wrong choice !") ;
}
}
}
}
Greetings,
i am new to java and i am working on this program....... i need to know how can i push the data to the stck ?
note : the push's parameter is type employee, and Employee contains First , Last, Phone , and address. how i can push each of them ?
here is what i did , and my instructor refused it
package week.pkg5;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Week5 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
class Employee {
String [] Fname = new String [10];
String[] Lname= new String [10];
String[] PhoneNum= new String [10];
String[] Address = new String [10];
int x= -1 ;
void increment(){
x++;
}
void PushFirst(String First){
Fname[x] = First ;
}
void Pushlast(String Last){
Lname [x] = Last ;
}
void PushPhone (String Phone){
PhoneNum [x] = Phone ;
System.out.println ("the Fist name is :"+ Fname [x]+ " , the last name is : " + Lname [x] + " ,the address is : "+ Address[x] + " ,the phone is : "+ PhoneNum[x]);
}
void PushAddress (String address){
Address [x] = address ;
}
void pop (){
if (x < 0){
System.out.println (" No Empolyee !");
}
else {
System.out.println ("the Fist name is :"+ Fname [x]+ " , the last name is : " + Lname [x] + " ,the address is : "+ Address[x] + " ,the phone is : "+ PhoneNum[x]);
x--;
}
}
void display (){
if (x < 0){
System.out.println (" No Empolyee !");
}
else {
for (int q = 0 ; q <=x ; q++){
System.out.println ((q+1)+"- "+"the First name is :"+ Fname [q]+ " , the last name is : " + Lname [q] + " ,the address is : "+ Address[q] + " ,the phone is : "+ PhoneNum[q]);
}
}
}
}
InputStreamReader inp = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(inp);
Employee obj = new Employee();
int w = -1 ;
for (int r=1 ;r>0; ){
System.out.println("please enter add to add new employee");
System.out.println("please enter display to display all employees list");
System.out.println("please enter pop to pop the last added employee");
System.out.println("please enter exit to exit");
String choice = br.readLine();
if(choice.equals("add")){
System.out.println(w);
if (w >= 9){
System.out.println("you reached the maxmum number !");
continue ;
}
else {
w++;
obj.increment();
String info ;
System.out.println ("please enter Employee first name :");
info = br.readLine();
obj.PushFirst(info);
System.out.println ("please enter Employee last name name :");
info = br.readLine();
obj.Pushlast(info);
System.out.println ("please enter Employee address :");
info = br.readLine();
obj.PushAddress(info);
System.out.println ("please enter Employee phone number :");
info = br.readLine();
obj.PushPhone(info);}
} else if(choice.equals("display")){
obj.display();
} else if(choice.equals("pop")){
obj.pop();
w--;
}else if(choice.equals("exit"))
break ;
else {System.out.println (choice + " is wrong choice !") ;
}
}
}
}
You would need to create a stack of employees and then you can push the whole employee object on to the stack.
import java.util.Stack;
...
Employee emp = new Employee();
Stack<Employee> stack = new Stack<Employee>();
stack.push(emp);
after creating an object to the class say (here stck) which will hold the data by calling method ex shown below
class std
{
int id;
string name;
public:
void set_id(int i)
{
id=i;
}
void set_name(string n)
{
name = n;
}
void disp()
{
system.out.println("name"+name+" and id = "+id);
}
};
main()
{
std s = new std();
s.set_id(1);
s.set_name("sunmoon");
s.disp();
}
so here you can observe that s is considered as stack and we pushed one person details as like you can create array of object and push n number of person details.
You have several issues in how you've modeled the data.
Issue #1 (The biggest issue of all):
An Employee should not have any internal representation of the stack. Think objects in the real world. In your example, each Employee should have:
a first name
last name
address
phone number
So the member fields :
String [] Fname = new String [10];
String[] Lname= new String [10];
String[] PhoneNum= new String [10];
String[] Address = new String [10];
int x= -1 ;
do not belong. This leads us to...
Issue #2 : The way you've modeled the Stack only allows for a fixed number of entries - 10 in your case). This is not how a stack should work. Read up on what a Stack is if you are uncertain. You can model a Stack in Java using a LinkedList - or use the built in Stack that Java provides. If you decide to create your own version, the important operations that need to be created are:
push
pop
isEmpty
My advice is to start by modelling the employee and pratice by pushing and popping them off of a built in Stack from the JDK until you really understand the operations before you try to create your own.