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());
}
Related
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();
}
}
I'm very new to java and I can't figure out what it is I'm doing wrong, it's properly something really basic, I want to be able to add information about employees and then then display/list that data (id, first name, last name, salary, position etc ) using a menu() method.
Everything compiles and adding employee information with addEmployee() seems to work fine but when running listEmployees() I get the exception: java.util.IllegalFormatConversionException.
I have been playing around with it for a bit but I'm not getting anywhere, any help would be greatly appreciated.
import java.util.*;
public class Employee
{
final static int MAX=20;
static int [] idArray= new int[MAX];
static String [] firstnameArray= new String[MAX];
static String [] lastnameArray= new String[MAX];
static int count=0;
public static void add(int id, String fname, String lname)
{
idArray[count] = id;
firstnameArray[count] = fname;
lastnameArray[count] = lname;
++count;
}
public static void addEmployee()
{
Scanner sc=new Scanner(System.in);
for(int i=0; i<idArray.length; i++)
{
System.out.println("Enter your id as an integer");
System.out.print(" (0 to finish): ");
int id = sc.nextInt();
sc.nextLine();
if (id==0)E
return;
System.out.println("Enter your First name");
String fname = sc.nextLine();
System.out.println("Enter your Last name");
String lname = sc.nextLine();
add(id, fname, lname);
}
}
public static void listEmployees()
{
for(int i=0; i<count; ++i)
{
System.out.printf("%-15s %10d \n",idArray[i],firstnameArray[i],lastnameArray[i] );
}
}
public static void printMenu()
{
System.out.println
(
"\n ==Menu==\n" +
"1. Add Employee\n"+
"2. Display Employee\n"+
"3. Quit\n"
);
}
public static void menu()
{
Scanner input = new Scanner(System.in);
int option = 0;
while(option!=3)
{
printMenu();
System.out.println("Please enter your choice");
option = input.nextInt();
switch(option)
{
case 1:
addEmployee();
break;
case 2:
listEmployees();
break;
case 3:
break;
default:
System.out.println("Wrong option");
}
}
}
public static void main(String [] args)
{
menu();
}
}
You are passing a string (lastnameArray[i]) to a numeric format (%10d). You need to first convert the string lastnameArray[i] to an int/long and then pass that value to %10d.
System.out.println(idArray[i] + " " + firstnameArray[i] + " " + lastnameArray[i]);
use this one instaed of your printing statement
The printf function has the wrong arguments passed to it. You should match the format and parameters passed to print them in the same order. Assuming you are passing the correct parameter to be printed, the first parameter should have %d , %s , %s respectively.
This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 6 years ago.
I am working on a project in Java that requests user inputs information like name, id, score in array.I need to help about calculate a average grade that user input and how to find out who have highest score. Here is my code:
package finalproject;
import java.util.Scanner;
/**
*
* #author vincephng
*/
public class FinalProject {
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
Scanner input= new Scanner(System.in);
Cis84[] student= new Cis84[50];
int option;
for (int c = 0; c<50;c++)
student[c]=new Cis84();
do{
System.out.print("");
System.out.println("1) Add Information");
System.out.println("2) Show report");
System.out.println("3) Exit");
System.out.print("\nEnter option: ");
option = input.nextInt();
switch(option)
{
case 1:
String n;
double g;
int index, i;
System.out.println("Which position of the student?");
index=input.nextInt();
System.out.println("What is the student's name:");
n=input.nextLine();
n=input.nextLine();
System.out.println("What is student's Id");
i=input.nextInt();
System.out.println("What is student's score");
g=input.nextDouble();
student[index].setName(n);
student[index].setGrade(g);
student[index].setId(i);
break;
case 2:
for(int c=0; c<50;c++)
System.out.println(student[c]);
break;
case 3:
System.out.println("You are done");
break;
default:
System.out.println("Try again");
break;
}
}while (option != 3);
}
}
and class
package finalproject;
public class Cis84
{
private String name;
private int id;
private double grade;
public Cis84()
{
name="not input yet";
id= 00000;
grade= 0.0;
}
public Cis84(String n, int i, double g)
{
name= n;
id= i;
grade=g;
}
public void setName(String n)
{
name=n;
}
public void setId(int i)
{
id=i;
}
public void setGrade(double g)
{
grade=g;
}
public String getName()
{
return name;
}
public int getId()
{
return id;
}
public double getGrade()
{
return grade;
}
public String toString()
{
return String.format("%s\n%d\n%.2f\n", name, id, grade);
}
}
Your toString method isn't defined correctly - it should be toString, with a lower case t, not ToString as you currently have. This is, by the way, why it's recommended to use the #Override annotation when overriding a superclass' method. In case you made a trivial mistake (such as a typo, or mixing up cases like you did here), the compiler would have alerted you that you're doing something wrong, instead of just allowing you to declare another method, which has nothing wrong with it per se, except for not being the method you want to override.
To sum up, here's how the code should look:
#Override // override annotation
public String toString() { // correct method name
return String.format("%s\n%d\n%.2f\n", name, id, grade);
}
Your error is here:
You wrote this:
public String ToString() {
return String.format("%s\n%d\n%.2f\n", name, id, grade);
}
And that is not the method toString() of the class object.. (note the difference in the name, java defines methods camelCase but you did it PascalCase)
You mean instead
#Override
public String toString() {
return String.format("%s\n%d\n%.2f\n", name, id, grade);
}
After that you will be able to see the content of student[c]
You should override public String toString() method for Cis84 class. Then you can use one of the following ways:
for(Cis84 std: student){
System.out.println(std);
}
or
Arrays.deepToString(student);
In place of
case 2:
for(int c=0; c<50;c++)
System.out.println(student[c]);
break;
Try this:
case 2:
for(int c=0; c<50;c++)
System.out.println(student[c].getName()+" "+student[c].getId()+" "+student[c].getGrade());
break;
You are printing the object but actually you want the data which is inside that object.
I saw a student registration sample and wanted to write it using HashMap in my own way to learn more about HashMap.
About the program:
1)You can add student name and student id -class Student
import java.util.*;
public class Student {
Scanner userInput = new Scanner(System.in);
public String sName(){
System.out.print("Enter student name: ");
String sName = userInput.next();
return sName;
}
public char sID(){
System.out.print("Enter student ID: ");
char sID= userInput.next().charAt(0);
return sID;
}
}
2)A class where I have declared 2 HashMap variables, one for student name and id and the second one for GPA and id -class AddInfo
import java.util.*;
public class AddInfo {
public HashMap<String,Character> studentInfo= new HashMap<String,Character>();
public HashMap<Double,Character> studentGPAInfo= new HashMap<Double,Character>();
}
3)You can add student GPA and student id – class StudentGPA
import java.util.*;
public class StudentGPA {
Scanner userInput = new Scanner(System.in);
public double sGPA(){
System.out.print("Enter student GPA: ");
double sGPA = userInput.nextDouble();
return sGPA;
}
public char sID(){
System.out.print("Enter student ID: ");
char sID= userInput.next().charAt(0);
return sID;
}
}
4)The last one where all the information from the above classes are getting utilized using .put - class GetInfo
import java.util.*;
public class GetInfo {
public HashMap<String,Double> myStudent=new HashMap<String,Double>();
public void addName(){
Student s= new Student();
StudentGPA sG= new StudentGPA();
AddInfo ai= new AddInfo();
ai.studentInfo.put(s.sName(), s.sID());
ai.studentGPAInfo.put(sG.sGPA(),sG.sID());
if(s.sID()== sG.sID()){
myStudent.put(s.sName(), sG.sGPA());
System.out.println("For student id "+ s.sID()+ "you have " + myStudent);
}
}
}
5)Main class
public class Main {
public static void main (String []args){
GetInfo g= new GetInfo();
g.addName();
}
}
My Problem: I think my issue is in the 4th point (GetInfo class) where I am trying to evaluate if the 2 student IDs are same or not. If they are same then put them in a different HashMap variable.
if(s.sID()== sG.sID())
When I execute the program it keeps on asking for Enter Student ID.
Any direction/advice will be helpful. Thank You for your valuable time and input.
Each time you do
if(s.sID()== sG.sID())
You are calling the sID() method of the class StudentGPA, which reads:
public char sID(){
System.out.print("Enter student ID: ");
char sID= userInput.next().charAt(0);
return sID;
}
So of course you are being prompted for input.
You should write a setSid() that sets the value in a instance variable, and then a getSid() method that only returns the sID value without prompting for input.
Then you if statement will look like this:
if(s.getSid()== sG.getSid())
You have to one time init values and then use getter to get value
public class StudentGPA {
private double sGPA;
private char sID;
Scanner userInput = new Scanner(System.in);
public void initSGPA(){
System.out.print("Enter student GPA: ");
sGPA = userInput.nextDouble();
}
public void initsID(){
System.out.print("Enter student ID: ");
sID= userInput.next().charAt(0);
}
public double getSGPA()
{
return sGPA;
}
public char getSID()
{
return sID;
}
}
In my opinion, the better way is using bean
public class StudentGPA {
private double sGPA;
private char sID;
Scanner userInput = new Scanner(System.in);
public void setSGPA(double sGPA){
this.sGPA = sGPA;
}
public void setSID(char sID){
this.sID= sID;
}
public double getSGPA()
{
return sGPA;
}
public char getSID()
{
return sID;
}
}
..... move user intput into addName or separate procedure in GetInfo class
....
System.out.print("Enter student GPA: ");
sG.setSGPA(userInput.nextDouble());
System.out.print("Enter student ID: ");
sG.setSID(userInput.next().charAt(0));
.....
AddInfo ai= new AddInfo();
ai.studentInfo.put(s.getSName(), s.getSID());
ai.studentGPAInfo.put(sG.getSGPA(),sG.getSID());
Could anybody tell me how to list some data in an arrayList according to the integer value that each component of the ArrayList has? This is my main class
import java.util.Scanner;
import java.io.*;
import java.util.Collections;
import java.util.ArrayList;
public class StudentDriver {
public static void main(String[] args) throws IOException {
Scanner scan, urlScan, fileScan;
String url, file;
int count = 0;
scan = new Scanner(System.in);
System.out.println("Enter the name of the file");
fileScan = new Scanner(new File("Data.csv"));
ArrayList<Student> studentList = new ArrayList<Student>();
while(fileScan.hasNext()){
url = fileScan.nextLine();
urlScan = new Scanner(url);
urlScan.useDelimiter(",");
count++;
while(urlScan.hasNext()){
String name = urlScan.next();
String last = urlScan.next();
int score = urlScan.nextInt();
Student e = new Student(name,last, score);
studentList.add(e);
}
}
System.out.println("The file has data for" +count+ "instances");
int option;
do{
System.out.println("********");
System.out.println("Options:");
System.out.println("********\n1. List \n2. Add Student \n3.Delete Student \n4. Exit \n******** ");
System.out.print("Select option: ");
option = scan.nextInt();
if(option == 1){
int index = 0;
while(index<studentList.size()){
System.out.println(studentList.get(index));
index++;
}
}
else if(option == 2){
System.out.print("Enter the name of the student: ");
String newName = scan.next();
System.out.print("Enter the last name of the student: ");
String newLastName = scan.next();
System.out.print("Enter the exam score of the student: ");
int newScore = scan.nextInt();
Student b = new Student(newName, newLastName, newScore);
studentList.add(b);}
else if(option == 3){
System.out.print("Enter the name of the student to remove: ");
String remove = scan.next();
System.out.print("Enter the last name of the student: ");
String remove1 = scan.next();
int location = studentList.indexOf(remove);
location = studentList.indexOf(remove1);
studentList.remove(location);
}
}while(option!=4 && option <4);
}//main
}//class
And this is the other class
public class Student implements Comparable<Student>{
String firstName, lastName;
int score;
public Student(String firstName, String lastName, int score){
this.firstName = firstName;
this.lastName = lastName;
this.score = score;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public String toString(){
return firstName + " " + lastName + ", exam score is "+ score;
}
#Override
public int compareTo(Student c) {
return score-c.getScore();
}
}
As you can see, up to now I have created the class where my compare method is but I have difficulties on using it. Also I have had difficulties on deleting one of the Array List parts by just writing the name and last name of the student. If somebody would help me, I would be very thankful.
well you can change your compareTo method as
public int compareTo(Student another)
{
if (this.score > another.score)
return -1;
if (this.score < another.score)
return 1;
else
return 0;
}
this should show it as decreasing order you can change the operator
than use whereever you want to sort it
Collections.sort(studentList)
Also if you don't want to use Collections.sort() method I can show you how you can write it with for loop under add option
Student newStd = new Student(name, last, score);
for(int i=0;studentList.size()>i;i++)
{
int size = studentList.size();
if(newStd.compareToCustom(studentList.get(i))>0)
{
studentList.add(i, newStd);
break;
}
else if(newStd.compareToCustom(studentList.get(size-1))<0)
{
studentList.add(studentList.size(), newStd);
break;
}
else if(newStd.compareToCustom(studentList.get(i))==0)
{
studentList.add(i++, newStd);
break;
}
}
for the remove part you can use
else if ( option == 3)
{
System.out.print("Enter the first name of student will be deleted: ");
String removeName = scan.next();
System.out.print("Enter the last name of student will be deleted: ");
String removeLastName = scan.next();
for ( int i = 0; i < studentList.size(); i++)
{
Student deleted = studentList.get(i);
if ( deleted.getFirstName().toLowerCase().equals(removeName.toLowerCase()) && deleted.getLastName().toLowerCase().equals(removeLastName.toLowerCase()))
{
studentList.remove(i);
System.out.println("The student has been deleted.");
break;
}
else
{
System.out.println("This student is not found");
break;
}
}
}
Basically what you want is an ordered collection. As #duffymo has stated, think about a creating a custom Comparator using your score.
There is plenty of info here
In terms of deleting students from the list.
The studentList is a list containing Student objects.
This means that the follow code:
System.out.print("Enter the name of the student to remove: ");
String remove = scan.next();
System.out.print("Enter the last name of the student: ");
String remove1 = scan.next();
int location = studentList.indexOf(remove);
Tries to find the index of a Student given the first name. This will return -1 as you're searching for a String and not a Student object.
Instead you have to iterate through your studentList and compare the first and last name of each Student element with the values of remove and remove1.
for(Student student : studentList) {
if(student.getFirstName.equals(remove) && student.getLastName.equals(remove1)) {
// remove the student.
}
}
Also you could consider giving each Student an ID as an unique identifier.
try this to sort studentList
Collections.sort(studentList, new Comparator<Student>()
{
#Override
public int compare(Student x, Student y)
{
if(x.score >= y.score)
return 1;
else
return -1;
}
});