How to modify the code in else if so that whatever I input in if will be displayed in the condition 2?
import java.util.*;
public class REPORTS
{
public static void main(String[]args)
{
int Studentid,equipid,quantity,studentid,equipid1;
String Studentname,Studentcourse,Studentlevel,equipmentname,reservationdate,returndate;
STUDENT stud=new STUDENT(1234,"abc","abc","abc");
EQUIPMENT equip;
RESERVATION reserve;
Scanner in = new Scanner(System.in);
int x = choices();
if(x==1)
{
System.out.println("Enter Student ID:");
Studentid=in.nextInt();
in.nextLine();
System.out.println("Enter Student Name:");
Studentname=in.nextLine();
System.out.println("Enter Student Course:");
Studentcourse=in.nextLine();
System.out.println("Enter Student Level:");
Studentlevel=in.nextLine();
stud.setID(Studentid);
stud.setName(Studentname);
stud.setCourse(Studentcourse);
stud.setLevel(Studentlevel);
}
else if(x==2)
{
stud.display();
}
}
I'm thinking of using a looping but I dont know how to properly loop in order for me to fetch the data that is input by the user in the if statement.
I changed my if else to switch and tried a while loop. But the program runs endlessly and instead of displaying what I input it keeps asking for student name:
while(x!=7)
{
switch(x)
{
case 1:
{
stud.getData();
choices();
break;
}
case 2:
{
stud.display();
break;
}
}
}
A few starting points:
public static void main(String[]args)
{
int Studentid,equipid,quantity,studentid,equipid1;
String Studentname, Studentcourse, Studentlevel, equipmentname,
reservationdate, returndate;
STUDENT stud=new STUDENT(1234,"abc","abc","abc");
...
Rename your STUDENT class to Student. Also, you don't need all these local variables, they just make your code harder to read.
Provide a default constructor for Student
public static void main(String[]args)
{
Student stud=new Student(); // call the default constructor, don't enter bogus data
Scanner in = new Scanner(System.in);
int x = choices();
while (x != 7) {
switch(x) {
case 1:
System.out.println("Enter Student ID:");
stud.setID(in.nextInt());
in.nextLine();
System.out.println("Enter Student Name:");
stud.setName(in.nextLine());
System.out.println("Enter Student Course:");
stud.setCourse(in.nextLine());
System.out.println("Enter Student Level:");
stud.setLevel(in.nextLine());
break;
case 2: stud.display(); break;
}
// this must be inside the loop!!
x = choices();
}
}
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
For example, we have 5 courses available: comp2011, comp2012, comp2013, comp2014, comp2015.
When adding or dropping a course, you need to specify the student's name (you may assume it is unique) and the course that is going to be added/dropped.
For adding a course, if the student has already enrolled in at least one course, the system will append the newly added course to his/her course record. But if it is the first time the student is trying to add courses, the system will create a record for him/her and state that this is the first course of this student (see sample output below)...
The system should support listing the courses that the student has enrolled in.
The system should support some basic validation check: Students cannot add the same course two times nor drop a course that is not enrolled.
When dropping the last course, there will be nothing in the student course list, but the system should still keep the empty file for him/her so that when another course is added, it knows that this is not the first time.
How Can I Make the Array that is going to support all my methods at once knowing that I made a method for adding, dropping, listing and quitting.(Quiting is not having an array)
This is where I am at now:
import java.util.*;
public class codeTraining {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String AddDrop = "";
while (!AddDrop.equals("Q")) {
System.out.println("Add-Drop Course Menu");
System.out.println("A for Add, D for Drop, L for List, Q for Quit");
AddDrop = input.nextLine();
switch (AddDrop) {
case "A" -> A();
case "D" -> D();
case "L" -> L();
case "Q" -> Q();
default -> System.out.println("Please enter a valid Character!");
}
}
}
public static void A() {
Scanner input = new Scanner(System.in);
String name;
String course;
System.out.println("Please enter the student name:");
name = input.nextLine();
System.out.println("Please enter the course you want to add:");
course = input.nextLine();
System.out.println("Adding course : " + course);
System.out.println("Add course successfully");
}
public static void D() {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a student name");
String name = input.nextLine();
System.out.println("please enter the course you want to drop:");
String course = input.nextLine();
System.out.println("Dropping course: " + course);
System.out.println("Drop course successfully");
}
public static void L() {
Scanner input = new Scanner(System.in);
String name, course;
System.out.println("Please enter the student name");
name = input.nextLine();
}
public static void Q() {
System.out.println("Quit...");
}
}
You could use a hashmap for this problem, as it will allow you to quickly and easily look up the courses of students. It's declared as a global variable outside all of the methods, which means it can be accessed by any of them.
import java.util.*;
public class codeTraining {
//Hashmap contains names that are mapped to lists of courses
static HashMap<String, ArrayList<String>> map =
new HashMap<String, ArrayList<String>>();
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String AddDrop = "";
while (!AddDrop.equals("Q")) {
System.out.println("Add-Drop Course Menu");
System.out.println("A for Add, D for Drop, L for List, Q for Quit");
AddDrop = input.nextLine();
//added breaks to the switch statement
switch (AddDrop) {
case "A": A(); break;
case "D": D(); break;
case "L": L(); break;
case "Q": Q(); break;
default: System.out.println("Please enter a valid Character!");
}
}
}
public static void A() {
Scanner input = new Scanner(System.in);
String name;
String course;
System.out.println("Please enter the student name:");
name = input.nextLine();
System.out.println("Please enter the course you want to add:");
course = input.nextLine();
System.out.println("Adding course : " + course);
//if the map contains the name already
if (map.containsKey(name)) {
//if the student already had the course in its list
if (map.get(name).contains(course)) {
System.out.println("The student is already taking this course");
return;
} else {
//adding the course to the list that's mapped
//to the student's name in the hashmap
map.get(name).add(course);
}
}
//if student isn't in the system
else {
//create a new arraylist with the new course in it
ArrayList<String> courses = new ArrayList<String>();
courses.add(course);
//add a map between the student's name and his course list
map.put(name, courses);
}
System.out.println("Add course successfully");
}
public static void D() {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a student name");
String name = input.nextLine();
System.out.println("please enter the course you want to drop:");
String course = input.nextLine();
System.out.println("Dropping course: " + course);
//checks if name in system
if (map.containsKey(name)) {
if (map.get(name).contains(course)) {
//removing if list had the course in it
map.get(name).remove(course);
} else {
System.out.println("This student isn't taking that course");
return;
}
} else {
System.out.println("This student isn't in the system");
return;
}
System.out.println("Drop course successfully");
}
public static void L() {
Scanner input = new Scanner(System.in);
String name, course;
System.out.println("Please enter the student name");
name = input.nextLine();
if (map.containsKey(name)) {
//printing out courses for specified student
ArrayList<String> courses = map.get(name);
for (int i = 0; i < courses.size(); i++) {
System.out.print(courses.get(i) + " ");
}
} else {
System.out.println("This student isn't in the system");
}
}
public static void Q() {
System.out.println("Quit...");
}
}
I added some comments in case you were new to hashmaps. Basically, map.put(key, value) will add a mapped pair to the list so that when you call map.get(key), it will return whatever value you put it to. I hope this helps, and feel free to ask if you're confused.
I am new to programming and have spent last number of days trying to take user input, store it in an arraylist and then output the specific details. I would really appreciate someone shining some light on where I'm going wrong. I cant seem to be able to access the input from the employee class and store it in the arraylist in the main Method.
Thanks.
public class OctEmployeeArray{
public void menu(){
boolean breakOut= false;
while(breakOut == false){
System.out.println("=====================================");
System.out.println("=====================================");
System.out.println("EMPLOYEE HOLIDAY ENTITLEMENT PROGRAM");
System.out.println("Please chose the appropriate option: ");
System.out.println("=====================================");
System.out.println("=====================================");
System.out.println("1) Enter new employee details:");
System.out.println("2) Display the employee average age:");
System.out.println("3) Display information on specific employee:");
System.out.println("4) Display all database accounts:");
System.out.println("5) Exit the program:");
System.out.println("=====================================");
Scanner in = new Scanner(System.in); //scanner assigned to 'in'
String choice = in.nextLine(); //user input stored in choice
switch (choice){
case "1": System.out.println("You chose the 'add employee' input");
Employee e1= new Employee();
e1.addEmployee();
break;
case "2":
System.out.println("You chose the b input");
break;
case "3":
System.out.println("You chose the c input");
//searchspecficEmployee();
break;
case "4":
System.out.println("You chose the 'display all' input");
//displayAll();
break;
case "5":
System.out.println("You chose to Exit.");
breakOut= true;
break;
default:
System.out.println("The input is not accurate");
break;
}
}
}
public class Employee {
private String staffName;
private int staffNumber;
private int staffAge;
private int yearStarted;
private String role;
public Employee(String staffName, int staffAge, int yearStarted, int staffNumber, String role){
this.staffName= staffName;
this.staffNumber= staffNumber;
this.staffAge= staffAge;
this.yearStarted= yearStarted;
this.role= role;
}
public Employee(){
}
public int getAge(){
return staffAge;
}
public String getName(){
return staffName;
}
public int getStaffNum(){
return staffNumber;
}
public int getStartYear(){
return yearStarted;
}
public Employee addEmployee(){//this asks the new employee questions, saves them in a employee object called e
Scanner in= new Scanner(System.in);
//Employee d= new Employee();
System.out.println("Please enter your Full name:");
String name = in.nextLine();
System.out.println("Please enter your age:");
int age= Integer.parseInt(in.nextLine());
System.out.println("Please enter your staff number:");
int staffNum= Integer.parseInt (in.nextLine());
System.out.println("Please enter year of current employment:");
int startYear=Integer.parseInt(in.nextLine());
System.out.println("Please enter role employment:");
String role=in.nextLine();
Employee e= new Employee(name, age, startYear, staffNum, role);// puts all the varibles and puts them inside e and returns it
return e;
}
}
public static void main(String[] args) {
ArrayList<Employee> alist= new ArrayList();// arraylist created to save employee objects
OctEmployeeArray o= new OctEmployeeArray();// object created for access to main menu
o.menu();//display main menu
Employee em= new Employee();// create employee object to access add employee method
alist.add(em.addEmployee);
for(Employee count : alist){
System.out.println(count.getName());
System.out.println(count.getStaffNum());
}
}
}
You are creating a new Employee instance inside the addEmployee() method. That's not wrong. But the fact this method is inside the Employee class is semantically nonsense (sorry) - and i think it's also why it doesn't work (It's a coincidence. Unfortunately a lot of semantic nonsense does work.).
What you should do is to remove the addEmployee() method from the Employee class and move it to the class holding your Employee array. Don't create new Employee instances inside the Employee class.
import java.util.ArrayList;
import java.util.Scanner;
/*Create a program that keeps track of specific information for Students. The information stored should be the following:
First Name, Last Name, Major, GPA, UIN, NetID, Age, Gender,
For this simple program we will only need to store 10 students in an ArrayList.
Your students should be stored in an object called Student.
You should be able to add, display and remove Students in the ArrayList.
You will submit 2 files for grading: Lab4.java and Student.java*/
public class Lab4 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
ArrayList<Student> newStudents = new ArrayList<Student>();
// ArrayList<Student> newStudents = new ArrayList<Student>(10); tried this as well, but doesn't work.
System.out.println("Welcome to the Student Interface!.");
System.out.println("Please select a number from the options below \n");
while (true) {
// Give the user a list of their options
System.out.println("1: Add a student to the list.");
System.out.println("2: Remove a student from the list.");
System.out.println("3: Display all students in the list.");
System.out.println("0: Exit the student interface.");
// Get the user input
int userChoice = input.nextInt();
switch (userChoice) {
case 1:
addStudents(newStudents);
break;
case 2:
removeStudent(newStudents);
break;
case 3:
displayStudent(newStudents);
break;
case 0:
System.out.println("Thank you for using the student interface. See you again soon!");
System.exit(0);
}
}
}
public static void addStudents(ArrayList<Student> newStudents) {
Scanner input = new Scanner(System.in);
boolean student_added = false;
// TODO: Add a student that is specified by the user
System.out.println("Please enter first name: ");
String firstName = input.next();
System.out.println("Please enter last name: ");
String lastName = input.next();
System.out.println("Please enter major: ");
String Major = input.next();
System.out.println("Please enter GPA: ");
String GPA = input.next();
System.out.println("Please enter UIN: ");
String UIN = input.next();
System.out.println("Please enter NetID: ");
String NetID = input.next();
System.out.println("Please enter Age: ");
String Age = input.next();
System.out.println("Please enter Gender: ");
String Gender = input.next();
for (int i = 1; i < 5; i++) { // ( I have also tried i<newStudents.size(). Didn't work.Thank you in advance!)
newStudents.add(new Student(firstName, lastName, Major, GPA, UIN, NetID, Age, Gender));
student_added = true;
break;
}
if (student_added) {
System.out.println("Student Added");
System.out.println();
} else {
System.out.println("\n Student Interface is full!");
}
}
private static void displayStudent(ArrayList<Student> newStudents) {
// TODO Auto-generated method stub
for (Student e : newStudents) {
System.out.println(e);
}
}
private static void removeStudent(ArrayList<Student> newStudents) {
Scanner input = new Scanner(System.in);
System.out.println("Please, enter the UIN to remove the Student: ");
String uin = input.nextLine();
for (Student e : newStudents) {
if (e.getUIN().equals(uin)) {
newStudents.remove(e);
System.out.println("Student removed");
break;
}
else {
System.out.println("Sorry, no such student with this " + uin + " " + "number exist");
}
}
}
}
The Student instance is being added to the list, and there is no check for if the size of the array is larger or equal to 10. You are checking the value of the i variable, which is created when you enter the for loop.
The for loop isn't the right tool for this job in this case.
Instead, do a check for newStudents.size(), and if that does not exceed the maximum value, add the student to the list.
For example:
if (newStudents.size() <= 10) { // check the size of the array [see note 1]
newStudents.add(new Student(firstName, lastName, Major, GPA, UIN, NetId, Age, Gender));
System.out.println("Student added\n");
} else {
System.out.println("\n Student interface is full!");
}
Note 1: As an aside, it'd be best if 10 was a constant at the top of the program (defined like public static const MAX_STUDENTS = 10;) to make the code more maintainable. See this question about what a magic number is.
import java.util.Scanner;
public class EmpTest {
public static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
// there is a second class with my constructors and other stuff of that nature
Employee e1 = new Employee();
Employee e2 = new Employee();
Employee e3 = new Employee();
String no = "no";
String yes = "yes";
while (true) {
System.out.println("Please enter in the employee name");
e1.name = input.nextLine();
System.out.println("Please enter in the salary of that employee");
e1.salary = input.nextDouble();
while (true) {
System.out.println("Would you like to add a second employee?");
String userInput = input.next();
if (userInput.equalsIgnoreCase(yes)) {
System.out.println("Please enter in the employee name");
e2.name = input.next();
System.out.println("Please enter in the salary of that employee");
e2.salary = input.nextDouble();
}
//this is where my break wont terminate the loop
//the console output just asks for the second employee salary and name without waiting for a user input
if(userInput.equalsIgnoreCase(no)) {
System.out.println("Okay");
break;
}
System.out.println("Would you like to add a third employee?");
userInput = input.next();
if (userInput.equalsIgnoreCase(yes)) {
System.out.println("Please enter in the employee name");
e3.name = input.next();
System.out.println("Please enter in the salary of that employee");
e3.salary = input.nextDouble();
}
if(userInput.equalsIgnoreCase(no)) {
System.out.println("Okay");
break;
}
}
}
}
}
your break statement is breaking inner while loop but no break statement for outer while loop.
After my first wrong answer here's the correct thing. As by the JLS:
A break statement with no label attempts to transfer control to the innermost
enclosing switch, while, do, or for statement of the immediately enclosing
method
So in your case you are breaking the inner while(true)-loop.
If you want to break some "outer" block you have to use break with a label like this:
loop:
while(true) {
.....
while(true) {
...
break loop;
}
}
Here is my answer with some explanations on the code:
import java.util.Scanner;
public class EmpTest {
public static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
Employee e1 = new Employee();
Employee e2 = new Employee();
Employee e3 = new Employee();
String no = "no";
String yes = "yes";
//initialized userInput here so that we can use it on the outer loop
String userInput="";
while (true) {
System.out.println("Please enter in the employee name");
e1.name = input.nextLine();
System.out.println("Please enter in the salary of that employee");
e1.salary = input.nextDouble();
input.nextLine();
//nextDouble() reads only the double and doesn't finish the line, so we need to add nextLine() method after nextDouble()
while (true) {
System.out.println("Would you like to add a second employee?");
userInput = input.nextLine();
if (userInput.equalsIgnoreCase(yes)) {
System.out.println("Please enter in the employee name");
e2.name = input.nextLine();
System.out.println("Please enter in the salary of that employee");
e2.salary = input.nextDouble();
//again
input.nextLine();
}
if(userInput.equalsIgnoreCase(no)) {
System.out.println("Okay");
break;
}
System.out.println("Would you like to add a third employee?");
userInput = input.nextLine();
if (userInput.equalsIgnoreCase(yes)) {
System.out.println("Please enter in the employee name");
e3.name = input.nextLine();
System.out.println("Please enter in the salary of that employee");
e3.salary = input.nextDouble();
input.nextLine();
}
if(userInput.equalsIgnoreCase(no)) {
System.out.println("Okay");
break;
}
}
//do the remaining things
//add the condition for breaking the outer loop if there's any
break;
}
//never forget to close the scanner
input.close();
}
}
some notes:
nextDouble() reads only 1 double and doesn't finish the line, so I
added input.nextLine() to finish the line.
I just added a break on the outer loop, right after the inner loop.
I don't know if you have a condition for breaking the outer loop, or
if there's anything that you want to do after breaking the inner
loop
You can also convert that loop into method and just use "return"
statement to break out of the method. I don't know if it's allowed
though, so I just stick to how you created the program and modified
it a bit.
Never forget to close the scanner after using it
You have to provide 2 break statements, one for the inner while loop and another for the outer while loop.
I have made an array from class student
student [] stu=new student[100];
I'm in class student op and I want to insert name and code from method insert to array stu.
Until now everything worked, but when I want to get my name and code from another method like delete in class student op, it shows that my array stu is empty. Where is the problem? if I delet the line
stu[0]=new student();
in delet method Net beans show an error!!
public class studentop {
student [] stu=new student[100];
private int counter=0;
int con=0;
public int edd;
public void insert(int edame){
String ans;
Scanner input=new Scanner(System.in);
for(int i=edame;i<100;i++){
System.out.println("add more student? ");
ans=input.next();
if(ans.equals("y")){
String thename;
stu[i]=new student();
System.out.println("insert name "+(i+1)+" : ");
thename = input.next();
stu[i].setname(thename);
System.out.println("insert code "+(i+1)+" : ");
int thecode;
thecode = input.nextInt();
stu[i].setcode(thecode);
System.out.println(stu[i].getcode());
for(int m=0;m<=3;m++){
System.out.println("add mark "+(m+1)+" ? ");
String ans2;
ans2=input.next();
if(ans2.equals("y")){
switch (m){
case 0:
System.out.println("mark"+(m+1)+" : ");
int mark;
mark=input.nextInt();
stu[i].setmark(mark);
break;
case 1:
System.out.println("mark"+(m+1)+" : ");
// int mark;
mark=input.nextInt();
stu[i].setMark2(mark);
break;
case 2:
System.out.println("mark"+(m+1)+" : ");
// int mark;
mark=input.nextInt();
stu[i].setMark3(mark);
break;
case 3:
System.out.println("mark"+(m+1)+" : ");
// int mark;
mark=input.nextInt();
stu[i].setMark4(mark);
break;
}
}
else{
break;
}
}
System.out.println(stu[i].getname());//aztarighe get name az
}
else {
edame=i;
edd=edame;
break;
}
}//end for
}
public void delete(){
stu[0]=new student();//if I delet this line it shows an error!
System.out.println(stu[0].getcode());
}
}
and here is my class student
public class student {
public String name;
public int code;
public double mark;
private double mark2;
private double mark3;
private double mark4;
public void setname(String sourcename){
name=sourcename;
}
public String getname(){
return name;
}
It is not empty, however, when you try to get the student from the array you're creating a new student that's why it appears to be empty:
public void delete()
{
stu[0]=new student(); //here you're deleting your old student
System.out.println(stu[0].getcode());
}
Instead you could use:
public void delete()
{
System.out.println(stu[0].getcode());
}