This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 2 years ago.
I have an assignment where I have to have a class named Employee with two variables and a class called Salary that inherits those variables and declares new ones. Within the Salary class, I have to create a method that will take user input for the different variables. The first number inputted is the number of employees you are giving information for and tells the loop how many times to go around. After typing in the information for all the employees the information must be presented like this
123 John engineer 40000.0
124 Emma Testing 33000.0
The only other thing that is required in the program is a function that will check the salary variable and if it is under 20000, not display the employee information to the console.
I have the user input working but I can't seem to get the array to display properly. Whatever I try I either get gibberish or null. I have tried putting the array and the array printing function in the display method and the main method and it doesn't make a difference. How can I fix this?
Side note: I know having different scanners for each input is not the best way of doing things it's just temporary. I'm trying to get the program to work before cleaning it up. The reasoning for it is a type mismatch error using one scanner as a result of scanning an int, then two strings, then a double.
This is the code I have right now:
import java.util.Scanner;
class Employee {
int employee_id;
String employee_name;
Employee(int employee_id, String employee_name) {
}
Employee() {
}
}
class Salary extends Employee {
double monthly_salary;
String designation;
int num_of_employees;
int n = 0;
Salary(int employee_id, String employee_name, String designation, double monthly_salary) {
super(employee_id, employee_name);
}
Salary() {
}
void display() {
Scanner s = new Scanner(System.in);
Scanner c = new Scanner(System.in);
Scanner a = new Scanner(System.in);
Scanner e = new Scanner(System.in);
Scanner t = new Scanner(System.in);
num_of_employees = s.nextInt();
for (;n<num_of_employees;) {
employee_id = c.nextInt();
employee_name = a.nextLine();
designation = e.nextLine();
monthly_salary = t.nextDouble();
n++;
}
s.close();
c.close();
a.close();
e.close();
t.close();
}
}
public class Solution2 {
public static void main(String[] args) {
Salary sal = new Salary();
Salary salary[] = new Salary[10];
sal.display();
salary[sal.n] = new Salary(sal.employee_id, sal.employee_name, sal.designation,
sal.monthly_salary);
if (sal.monthly_salary >= 20000) {
System.out.println(salary[sal.n]);
}
else {
System.out.println("");
}
}
}
The result from the array with this code is
Salary#7b23ec81
Related
This question already has answers here:
How to find an object in an ArrayList by property
(8 answers)
Closed 5 years ago.
I've just started learning java and I'm trying to create an application to register students.
Based on this question how-would-i-create-a-new-object... I created a while loop to create an instance of a class.
public class RegStudent {
ArrayList<Student> studentList = new ArrayList<>();
Scanner input = new Scanner(System.in);
public void reggaStudent(int start) {
while (start != 0) {
String programNamn, studNamn;
int totalPoint, antalKurser;
System.out.println("Vad heter programmet?");
programNamn = input.nextLine();
System.out.println("Vad heter studenten");
studNamn = input.nextLine();
System.out.println("Hur många poäng har studenten?");
totalPoint = input.nextInt();
System.out.println("Hur många kurser är studenten registrerad på?");
antalKurser = input.nextInt();
// Add student to list of students
studentList.add(new Student(totalPoint, antalKurser,
programNamn, studNamn));
System.out.println("Vill du registrera in en fler studenter? "
+ "Skriv 1 för ja och 0 för nej");
start = input.nextInt();
input.nextLine();
} // End of whileloop
}
}
The class is:
public class Student {
private int totalPoint;
private int antalKurser;
private String programNamn;
private String studNamn;
private static int counter;
public Student(int totalPoint, int antalKurser, String program, String studNamn) {
this.totalPoint = totalPoint;
this.antalKurser = antalKurser;
this.programNamn = program;
this.studNamn = studNamn;
counter++;
}
public int getTotalPoint() {
return totalPoint;
}
public void setTotalPoint(int totalPoint) {
this.totalPoint = totalPoint;
}
public int getAntalKurser() {
return antalKurser;
}
public void setAntalKurser(int antalKurser) {
this.antalKurser = antalKurser;
}
public String getProgramNamn() {
return programNamn;
}
public void setProgramNamn(String programNamn) {
this.programNamn = programNamn;
}
public String getStudNamn() {
return studNamn;
}
public void setStudNamn(String studNamn) {
this.studNamn = studNamn;
}
public static int getCount(){
return counter;
}
#Override
public String toString() {
return String.format(" Namn: %s, Program: %s, Antal poäng: %d, "
+ "Antal kurser: %d\n ", studNamn, programNamn, totalPoint, antalKurser);
}
}
How do I go about to get and set the instance variables in specific instance? I.e find the instances.
I understand it might be bad design but in that case I would appreciate some input on how to solve a case where i wanna instantiate an unknown number of students.
I've added a counter just to see I actually created some instances of the class.
You simply query objects for certain properties, like:
for (Student student : studentList) {
if (student.getProgramName().equals("whatever")) {
some match, now you know that this is the student you are looking for
In other words: when you have objects within some collection, and you want to acquire one/more objects with certain properties ... then you iterate the collection and test each entry against your search criteria.
Alternatively, you could "externalize" a property, and start putting objects into maps for example.
studentList.add(new Student(totalPoint, antalKurser,
programNamn, studNamn));
You now have your Student objects in a list. I assume you have something like
List<Student> studentList = new ArrayList<>();
somewhere in your code. After you populate the list with Student objects, you can use it to find instances. You need to decide what criteria to use for a search. Do you want to find a student with a specific name? Do you want to find all students in a given program? Do you want to find students with more than a certain number of points?
Maybe you want to do each of these. Start by picking one and then get a piece of paper to write out some ideas of how you would do the search. For example, say you want to find a student with the name "Bill". Imagine that you were given a stack of cards with information about students. This stack of cards represents the list in your program. How would you search this stack of cards for the card with Bill's name on it? Describe the steps you need to take in words. Don't worry about how you will code this yet. The first step in writing a computer program is breaking the solution down into small steps. After you have a clear idea how you might do this by hand in the physical world, you can translate your description into Java code.
This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 5 years ago.
Class File:
public class Student {
public String stu_FName;
public String stu_LName;
public String stu_ID;
}
This is the code I wrote to get inputs from the user
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter value for X");
int x = sc.nextInt();
ArrayList<Student> stuIDArray = new ArrayList<Student>(4);
while (x != 0) {
Student st = new Student();
System.out.println("Enter First Name");
st.stu_FName = sc.next();
stuIDArray.add(st);
System.out.println("Enter value fo1r X");
x = sc.nextInt();
}
When I print the size of the array after storing values using the above code, size works fine,
System.out.println(stuIDArray.size());
but when i try to print out the results in any of the following methods, it prints some code type format
for (int i=0;i<stuIDArray.size();i++){
System.out.println(stuIDArray.get(i));
}
for (Student a : stuIDArray){
System.out.println(a);
}
output :
com.company.Student#45ee12a7
com.company.Student#330bedb4
com.company.Student#45ee12a7
com.company.Student#330bedb4
You need to specify name of the variable you need to get data for. Below code is working fine.
for (int i = 0; i < stuIDArray.size(); i++) {
System.out.println(stuIDArray.get(i).stu_FName);
}
for (Class1 a : stuIDArray) {
System.out.println(a.stu_FName);
}
This would happen because when you are trying to print the student "object", it would print the string representation of the student object.
What you need to do is to override the toString method in Student class with proper properties somewhat like,
#Override
public String toString() {
return "Student [stu_FName=" + stu_FName + ", stu_LName=" + stu_LName
+ ", stu_ID=" + stu_ID + "]";
}
You have to learn about toString() method. When you try to use System.out.println() on an object, its toString() method is invoked, and the signature you've been getting, e.g. com.company.Student#330bedb4 is the default return value of those methods, as explained here. If you'd like a proper detail of each field, override the toString method in your Student class. For more, check out this answer
This question already has answers here:
Ways to iterate over a list in Java
(13 answers)
Closed 7 years ago.
import java.util.*;
public class ChristmasParty
{
private Scanner input = new Scanner(System.in);
public static void main(String[] args)
{
ChristmasParty cp = new ChristmasParty();
cp.run();
}
public void run()
{
menu();
addName();
}
public void menu()
{
System.out.println("Welcome to the guests lists program");
System.out.println("Enter a name or enter X to quit");
}
public void addName()
{
String nameAdded = "";
ArrayList<String> guestsLists = new ArrayList<String>();
do
{
System.out.print("Enter a name: ");
nameAdded = input.nextLine();
guestsLists.add(nameAdded);
System.out.println("-----------------------------------------------");
System.out.println(nameAdded + " has been added to the guests list.");
}while(!nameAdded.equals("X"));
System.out.println("Guests lists:");
System.out.println("========================");
System.out.println(guestsLists.get(0));
System.out.println(guestsLists.get(1));
System.out.println(guestsLists.get(2));
System.out.println(guestsLists.get(3));
System.out.println(guestsLists.get(4));
System.out.println(guestsLists.get(5));
System.out.println(guestsLists.get(6));
System.out.println(guestsLists.get(7));
System.out.println(guestsLists.get(8));
System.out.println(guestsLists.get(9));
System.out.println(guestsLists.get(10));
System.out.println(guestsLists.get(11));
System.out.println(guestsLists.get(12));
System.out.println(guestsLists.get(13));
System.out.println(guestsLists.get(14));
System.out.println(guestsLists.get(15));
}
}
Hello, I am trying to make a code that will prompt the user to enter a name,and that name will be saved in the arraylists, and then once the user exits and quits by pressing "X", it will display all the names in the lists. However how do I make the System.out.println(guestsLists.get()); codes simpler rather than typing it all out?
Put this code:
}while(!nameAdded.equals("X"));
System.out.println("Guests lists:");
System.out.println("========================");
for(int i = 0; i < guestsLists.size(); i++)
{
System.out.println(guestsLists.get(i));
}
OR
for(String s : guestsLists)
{
System.out.println(s);
}
And remove all the sysouts after the
System.out.println("========================");
Simply iterate through the list using an enhanced for loop:
...
for (String name : guestsLists) {
System.err.println(name);
}
...
You can use that form of a for loop when you do not need an index inside the loop, but just want to iterate over the collection. In these cases, it is much easier to read (and less code) than using an explicit index (or using an explicit Iterator).
See also https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html
I'm having trouble with calling a method. The basis of the program is to read in data from data.txt, grab the name token given, then all of the grades that follow, then implement some operations on the grades to give details of the person's grades. I do all of the methods in a separate file named Grades.java, which has the Grades class. I'm just having trouble because I MUST have the testGrades method in my code (which I don't find necessary). I have done everything I need to do for the results to be perfect in a different program without having two different .java files. But it's necessary to do it this way. I think I have mostly everything pinned down, I'm just confused on how to implement and call the testGrades method. I commented it out and have the question on where it is in the program. Quite new to classes and objects, and java in general. Sorry for the lame question.
public class Lab2 {
public static void main(String[] args) {
Scanner in = null; //initialize scanner
ArrayList<Integer> gradeList = new ArrayList<Integer>(); //initialize gradeList
//grab data from data.txt
try {
in = new Scanner(new File("data.txt"));
} catch (FileNotFoundException exception) {
System.err.println("failed to open data.txt");
System.exit(1);
}
//while loop to grab tokens from data
while (in.hasNext()) {
String studentName = in.next(); //name is the first token
while (in.hasNextInt()) { //while loop to grab all integer tokens after name
int grade = in.nextInt(); //grade is next integer token
gradeList.add(grade); //adding every grade to gradeList
}
//grab all grades in gradeList and put them in an array to work with
int[] sgrades = new int[gradeList.size()];
for (int index = 0; index < gradeList.size(); index++) {
sgrades[index] = gradeList.get(index); //grade in gradeList put into grades array
}
//testGrades(sgrades); How would I implement this method call?
}
}
public static void testGrades(Grades grades) {
System.out.println(grades.toString());
System.out.printf("\tName: %s\n", grades.getName());
System.out.printf("\tLength: %d\n", grades.length());
System.out.printf("\tAverage: %.2f\n", grades.average());
System.out.printf("\tMedian: %.1f\n", grades.median());
System.out.printf("\tMaximum: %d\n", grades.maximum());
System.out.printf("\tMininum: %d\n", grades.minimum());
}
}
This is a little snippet of the beginning of the Grades.java file
public class Grades {
private String studentName; // name of student Grades represents
private int[] grades; // array of student grades
public Grades(String name, int[] sgrades) {
studentName = name; // initialize courseName
grades = sgrades; // store grades
}
public String getName() {
return studentName;
} // end method getName
public int length() {
return grades.length;
}
well your test grades take a Grades object so you need to construct a Grades object using your data and pass it to your test grades method
i.e.
Grades myGrade = new Grades(studentName,sgrades);
testGrades(myGrade);
It looks like what you need to do is have some type of local variable in your main method, that would hold your custom Grade type. So you need add a line like..
Grades myGrades = new Grades(studentName, sgrades);
Then you can call your testGrades method with a line like...
testGrades(myGrades);
Looks like you may also need a toString method in your Grades class.
Seems like homework, so I tried to leave a bit to for you to figure out :)
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
We had a programming exam last week and I wasn't able to do it.
We were asked to make a program that will ask the user to select either of these three options:
given name
middle name
last name.
After selecting, you are asked to enter a name using scanner.
Then it will ask you if you want to try again, if you input yes, the program will loop again and if you enter the same name, it will prompt an error saying you already set it that way.
I've done all of it except that part, comparing the values.
How do I compare the 1st and 2nd input using scanner?
Here is what I have done so far.
public class PXM {
private String givenname;
private String middlename;
private String lastname;
public void setGN(String gn) {
this.givenname = gn;
}
public void setMN(String mn) {
this.middlename = mn;
}
public void setLN(String ln) {
this.lastname = ln;
}
public boolean equals() {
}
}
import java.util.*;
public class TestPXM {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
String yes;
int t;
PXM p1 = new PXM(); {
System.out.println("1. given name ");
System.out.println("2. middle name");
System.out.println("3. last name");
System.out.print("select method: ");
int method = sc.nextInt();
if (method == 1) {
System.out.println("enter given name: ");
String gn = sc.next();
p1.setGN(gn);
}
}
}
}
You don't use the scanner to compare. You would save the values input and compare against those.
I would use a Set to hold the values, because Set values are guaranteed to be unique, and that suits the application. You would use Set.contains() to find if you've already got a name.
Assuming you have two Strings, s1 and s2 and you want to compare them, you should use the equals() method:
if (s1.equals(s2)) {
// strings are the same
} else {
// strings are different
}
If you don't know how to use Scanner, take a look here.
You can use this:
Since you've already set the variable in:
p1.setGN(gn);
you can read the input again after suitable prompt like:
String gn=sc.next();
and then compare the stored variable in the object p1 using a getter method:
public String getGN()
{
return this.givenname;
}
Now if you do
if(gn.equals(p1.getGN())
{
System.out. println("You have already set that");
}
You will get the desired result.