Here is my code:
public static String currentStudent = "";
public void login() {
boolean studentLoggedOn = false;
Student student = new Student();
PC_Dialog dialog = new PC_Dialog("Enter Login Information", "Student ID, Password-", "OK");
dialog.choice();
String studentID = dialog.getField(1);
String password = dialog.getField(2);
student = (Student) projectSystem.studentFile.retrieve(studentID);
if (studentID != null) {
if (password.equals(student.password)) {
currentStudent = studentID;
studentLoggedOn = true;
studentRun();
}
}
if (!studentLoggedOn) {
JOptionPane.showMessageDialog(null, "Either the user name or the password were incorrect");
login();
}
}
After all of that, the "currentStudent = studentID;" doesn't seem to have any effect on the currentStudent String?
Your question is incomplete, but if I had to guess, I'd say you have a reference to currentStudent somewhere else in your code. Since strings are not mutable and the assignment operator also does not mutate objects, this reference would not change.
For example:
String one = "some string";
String two = one;
one = "another";
System.out.println(one);
System.out.println(two);
Will output
another
some string
Try reading up on Java references and string assignment.
Per the question author's request here's an example that accomplishes what I think he wants.
public class Session {
private String currentUserId = null;
public void setCurrentUserId( String id ) {
currentUserId = id;
}
public String getCurrentUserId() {
return currentUserId;
}
// Other session related information
//...
}
And use the Session class as follows.
public class MyApp {
private Session currentSession;
public MyApp() {
currentSession = new Session();
}
public void login() {
//...
if ( studentID != null ) {
if ( password.equals(student.password) ) {
currentSession.setCurrentUserId(studentID);
//...
}
}
//...
}
public void someOtherMethod() {
System.out.println(currentSession.getCurrentUserId());
}
}
Either currentStudent = studentID does not get executed, or StudentID is something you are not expecting (empty string?). Either fire up a debugger or just insert a print statement(s) to see what happens:
if (studentID != null) {
if (password.equals(student.password)) {
currentStudent = studentID;
System.out.println ("StudentID is " + studentID);
System.out.println ("CurrentID is " + currentStudent); // being paranoid here :-))
studentLoggedOn = true;
studentRun();
}
}
If you verify this shows as you'd expected, you can dig further
According to this site (question and answer on #20):
http://www.javacertifications.net/javacert/scjp1.5Mock.jsp
you cannot change the value of as static String variable within a local method because of its immutable property.
Java 1.5
Related
switch(menuChoice) {
case 1:
System.out.println("Enter your contact's first name:\n");
String fname = scnr.next();
System.out.println("Enter your contact's last name:\n");
String lname = scnr.next();
Necronomicon.addContact(new Person(fname, lname));
break;
// main truncated here for readability
import java.util.ArrayList;
public class AddressBook {
ArrayList<Person> ArrayOfContacts= new ArrayList<Person>();
public void addContact(Person p) {
ArrayOfContacts.add(p);
/*
for(int i = 0; i < ArrayOfContacts.size(); i++) {
if(ArrayOfContacts.get(i).getID() != p.getID())
ArrayOfContacts.add(p);
else
System.out.println("Sorry this contact already exists.");
}
*/
}
}
public class Person {
private String fName = null;
private String lName = null;
private static int ID = 1000;
public Person(String fName, String lName) { // Constructor I'm using to try and increment the ID each time a Person object is created starting at 1001.
this.fName = fName;
this.lName = lName;
ID = ID + 1;
}
}
I am trying to create an address book whereby each contact has a first name, last name and a unique ID.
My question is how to I prevent a user from entering in duplicate contacts with the same first and last name? Should I implement some kind of check in the addContact method or right in main? How?
You could simply use HashSet and avoid any kind of loops to test it. HashSet is in charge of this function.
import java.util.Set;
import java.util.HashSet;
public class AddressBook {
Set<Person> listOfContacts = new HashSet<>();
public void addContact(Person p) {
if (!listOfContacts.add(p))
System.out.println("Sorry this contact already exists.");
}
}
To increment ID property you should have 2 properties, 1 static and another one, and increment it in constructor. Look:
public class Person {
private final int ID;
private static int id = 1000;
private String fName;
private String lName;
public Person(String fName, String lName) { // Constructor I'm using to try and increment the ID each time a Person object is created starting at 1001.
this.ID= ++id;
this.fName = fName;
this.lName = lName;
}
To make the HashSet not accept duplicate objects you should set which properties should not be duplicated in the class (Person in your case). Follows an example:
#Override
public int hashCode() {
int hash = 7;
hash = 61 * hash + Objects.hashCode(this.fName);
hash = 61 * hash + Objects.hashCode(this.lName);
return hash;
}
#Override
public boolean equals(Object obj) {
if (obj == null || getClass() != obj.getClass())
return false;
final Person other = (Person) obj;
if (!Objects.equals(this.fName, other.fName))
return false;
return Objects.equals(this.lName, other.lName);
}
}
By the way, you can generate equals and hashCode methods using your IDE (Eclipse, NetBeans, etc.)
EDIT
Since you aren't able to use HashSet, I will show a version with ArrayList. By the way, you have to use HashCode and equals as I said to make it work well
import java.util.List;
import java.util.ArrayList;
public class AddressBook {
List<Person> arrayOfContacts = new ArrayList<>();
public void addContact(Person p) {
if (listOfContacts.contains(p))
System.out.println("Sorry this contact already exists.");
else
arrayOfContacts.add(p);
}
}
Here is the code for keeping out duplicate ID's.
public void addContact(Person p) {
for(int i = 0; i < ArrayOfContacts.size(); i++) {
Person contact = ArrayOfContacts.get(i);
if(contact.getID() == p.getID()) {
System.out.println("Sorry this contact already exists.");
return; // the id exists, so we exit the method.
}
}
// Otherwise... you've checked all the elements, and have not found a duplicate
ArrayOfContacts.add(p);
}
If you would like to change this code to keep out duplicate names, then do something like this
public void addContact(Person p) {
String pName = p.getFname() + p.getLname();
for(int i = 0; i < ArrayOfContacts.size(); i++) {
Person contact = ArrayOfContacts.get(i);
String contactName = contact.getFname() + contact.getLname();
if(contactName.equals(pName)) {
System.out.println("Sorry this contact already exists.");
return; // the name exists, so we exit the method.
}
}
// Otherwise... you've checked all the elements, and have not found a duplicate
ArrayOfContacts.add(p);
}
Use a HashSet. For every user's name, add it to the HashSet.
For example:
HashSet<String> namesUsed = new HashSet<String>();
if (namesUsed.contains(userName)) {
//do what you want here, if this is entered it means there is a duplicate
} else {
namesUsed.add(userName); //add it to the list of used names
}
You should Override equals inside your Person class
public boolean equals(Object obj) {
if(fName.equals(obj.getfName()) && lName.equals(obj.getlName)) {
return true;
}
return false;
}
Then just call:
if(!(person1.equals(person2))) {
//not a duplicate
}
And of course substitute the variables/objects with whatever objects you want.
You also should add getters and setters for last and first name.
Hope this helps!
Hi I'm working on an android studio project using global arrays,
I can read from the global arrays fine, and have no problem writing
to the global integers ,But i cannot figure out how to set the global
array from code, this is the important parts of the project:
added this under application tag in the android manifest xml:
android:name=".Globals"
java class Globals:
import android.app.Application;
public class Globals extends Application {
public int empnum=13;
public int getData3() {
return empnum;
}
public void setData3(int empnum) {
this.empnum = empnum;
}
public String[] passw = {"0123","0123","0123","0123","0123","0123","0123","0123","0123","0123","0123","0123","0123"};
public String[] getData4() {
return passw;
}
public void setData4(String[] passw) {
this.passw = passw;
}
public int login=0;
public int getData5() {
return login;
}
public void setData5(int login) {
this.login = login;
}
public String[] empname = {"Name1","Name2","Name3","Name4","Name5","Name6","Name7","Name8","Name9","Name10","Name11","Name12","Name13","Not logged in"};
public String[] getData6() {
return empname;
}
public void setData6(String[] empname) {
this.empname = empname;
}
Here is the block of code I'm having trouble with
inner class of java class TimeIn:
final Globals g = (Globals) getApplication();
final String[] empname = g.getData6();
final String[] passw = g.getData4();
public void onClick(View v) {
i = 0;
String empname = edit2.getText().toString();
int getemn = Integer.parseInt(edit.getText().toString());
if (i == 0 && h == 0) {
g.setData3(getemn);
g.setData6(String[getemn], empname); // This one line right here won't compile, I have tried different combinations but have had 0 luck
i = 1;
h = 1;
}
}
I have no problems getting and using a String array, this is how it works to get
an array value and compare it to a string:
public void onClick(View v) {
i = 0;
String getemp = edit2.getText().toString();
int getemn = Integer.parseInt(edit.getText().toString());
if (i == 0 && getemp.equals(passw[getemn])) { // All of this works perfectly
g.setData3(getemn);
g.setData5(0);
tfone.setText("Empoyee " + getemn);
tftwo.setText("Logged in");
i = 1;
}
if (i == 0 && getemp != (passw[getemn])) {
tfone.setText("No matches found");
edit2.setText("Not logged in");
i = 1;
}
}
So I know this line of code is wrong:
g.setData6(String[getemn], empname);
but for
the life of me I can't figure out how it should be written, the only error hint is I
get from hovering over the line-
array type expected; found 'java.lang.String'
Anyone know what I'm doing wrong?
In Global class, you declare the method with one parameter
public void setData6(String[] empname) {
this.empname = empname;
}
but when you call, you put 2 parameters g.setData6(String[getemn], empname);
You should remove one parameter
or add another method with 2 parameters in Globals class
Also
You are wrong in here
...
String empname = edit2.getText().toString();
int getemn = Integer.parseInt(edit.getText().toString());
...
g.setData6(String[getemn], empname); // This one line right here won't compile, I have tried different combinations but have had 0 luck
The setData6 function now require 2 parameters, one is String array and the other is String
but the way you put the String array to the function is wrong
Here is a simple example that show how to pass the String array to function
public class Test {
public static void setData6(String[] empnameList, String empname) { // with the `String array` you should declare the variable name like `empnameList` or `arrEmpname` NOT `empname` because `empname` make confusing when you read code
this.empnameList = empnameList;
this.empname = empname;
}
public static void main(String[] args) {
String[] strArray = new String[]{"Name1","Name2","Name2"};
String empName = "Na";
setData6(strArray,empName); // call method with 2 parameters here
}
}
Hope this help
Solved!! it turns out I had to modify my setter part of my Globals class, so this first part (the getter method) in the Globals class is correct:
public String[] compname = {"Manager's company", "Company2", "Company3", "Company4", "Company5", "Company6", "Company7", "Company8", "Company9", "Company10", "Company11", "Company12", "Company13", "Not punched in"};
public String[] getData7() {
return compname;
}
I had to change the getter part of my Globals class to this:
public int setcmpn = 0; // <-- Edited, this should equal some integer value
public void setData7(int setcmpn, String compname) { // removed [] from 2nd argument
this.setcmpn = setcmpn;
this.compname[setcmpn] = compname; // added in [] after array's name and fill it with the first argument from setData7 method
}
And to set the value of the desired index from any class just use:
Globals g = (Globals) getApplication();
g.setData7(getemn, getemp);
where getemn is an integer and getemp is a string.
This question already has answers here:
NullPointerException (Java) [duplicate]
(4 answers)
Closed 7 years ago.
I'm new to java and I'm creating generic social media site. My user class has the ability to create a "Post" class. When attempting to view these post I receive the aforementioned error. I'd like to make a method within the class so that the user class and view it's the string associated with it's post class.
import java.util.Scanner;
public class User {
private String password, address;
private Post myPost;
private int age;
public String userName;
public User (String u, String p, String l, int a) {
userName = u;
password = p;
address = l;
age = a;
}
public String viewLoginName ( ) {
return userName;
}
public String viewPassword ( ) {
return password;
}
public String viewAddress ( ) {
return address;
}
public int viewAge ( ) {
return age;
}
public Post createPost ( ) {
Scanner reader = new Scanner ( System.in );
String message;
System.out.println("What would you like to share? ");
message = reader.next ( );
myPost = new Post(userName + ": " + message);
return myPost;
}
public String viewMyPost()
{
return myPost.viewPost();
}
//the new method meant to allow users to view other users post
public String viewUserPost(String user)
{
return user.viewMyPost();
}
}
//Post Class
import java.util.Scanner;
public class Post {
private String message, acknowledged = "";
//Scanner reader = new Scanner ( System.in );
//message = reader.nextString ( );
public Post(String m) {
message = m;
}
public String viewPost() {
return message;
}
public String acknowledge() {
System.out.println("What is your username?");
Scanner reader = new Scanner(System. in );
String acknowledger;
acknowledger = reader.next();
acknowledged = acknowledged + acknowledger + ',';
return acknowledged;
}
}
You're shadowing the myPost variable by re-declaring it in the method. This leaves the class field null. Don't re-declare it.
public String createPost() {
Scanner reader = new Scanner(System. in );
String message;
System.out.println("What would you like to share? ");
message = reader.next();
// Post myPost = new Post(userName + ": " + message);
myPost = new Post(userName + ": " + message); // note the difference?
return "";
}
As a side recommendation, I would get all user interface code out of your User class as it doesn't belong there, and you risk running into resource problems by creating a Scanner object over and over. Instead the UI code belongs elsewhere in its own class, and you should consider giving the createPost method a String parameter called message.
Also I would also consider getting rid of the Post variable itself and its getter method, and simply have the createPost(String message) method return the Post object when called. Right now it returns a useless empty String, which is not going to be helpful to you or your user.
public Post createPost(String message) {
return new Post(userName + ": " + message);
}
Im try to insert data into Database using ArrayList.there is a Erro msg.
That is my Custmer.class method. this is what i got from when i going to pass ArrayList into another class.
incompatible types: ArrayList<String> cannot be converted to ArrayList<Inquiries>
I want to know how to do this using correct Using OOP concept
public void passingMsg(ArrayList<Inquiries> arrlist){
try {
System.out.println("Method "+arrlist);
String sq = "INSERT INTO Inquiries (name,mail,tp,msg)VALUES(?,?,?)";
PreparedStatement pr = con.prepareStatement(sq);
for(int i=0;i<arrlist.size();i++){
pr.setString(1,arrlist.get(i).getName());
pr.setString(2,arrlist.get(i).getMail());
pr.setString(3,arrlist.get(i).getTp());
pr.setString(4,arrlist.get(i).getMsg());
}
pr.executeQuery();//executeBatch();
} catch (SQLException ex) {
}
}
and this is how i get values from user
String name = txtName.getText();
String mail = txtEmail.getText();
String tp = txtTp.getText();
String msg = txtMsg.getText();
ArrayList<String> arrInq = new ArrayList<String>();
arrInq.add(name);
arrInq.add(mail);
arrInq.add(tp);
arrInq.add(msg);
Custmer c =new Custmer();
if( c.passingMsg(arrInq)){
try {
JOptionPane.showMessageDialog(this, "Successs!!");
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Unsuccesss!!");
e.printStackTrace();
}
}
and this is my Inquiries.class :
public class Inquiries {
private String name;
private String mail;
private String tp;
private String msg;
public Inquiries(String name,String mail,String tp,String msg){
this.name = name;
this.mail = mail;
this.tp = tp;
this.msg = msg;
}
//
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
public String getTp() {
return tp;
}
public void setTp(String tp) {
this.tp = tp;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
Can Some one please explain whats wrong with this. please ?
Reason For Error
This was simply telling you that your types were incompatible for the operation you were trying to perform. In your passingMsg() method, you have its header as: public void passingMsg(ArrayList<Inquiries> arrlist). However, inside your "how i get values from user" area, which I will now refer to as "2nd Snippet", you have your method call declared as: if( c.passingMsg(arrInq)). This means that you are implying that your parameter being passed, arrInq in this case, is of the type ArrayList<Inquiries>, but it's not. It's being initialized in your 2nd Snippet as: ArrayList<String> arrInq = new ArrayList<String>();
Simple Fix
I take no responsibility for this code; use at your own risk. To fix this, you would want to change that entire 2nd Snippet to something similar to the following:
String name = txtName.getText();
String mail = txtEmail.getText();
String tp = txtTp.getText();
String msg = txtMsg.getText();
ArrayList<Inquiries> arrInq = new ArrayList<Inquiries>();
arrInq.add(new Inquiries(name, mail, tp, msg));
Custmer c = new Custmer();
try {
c.passingMsg(arrInq);
JOptionPane.showMessageDialog(this, "Successs!!");
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Unsuccesss!!");
e.printStackTrace();
}
You would also want to change the method header to either return a boolean, or fix it up a little bit to actually throw the exception. Such as:
public void passingMsg(ArrayList<Inquiries> arrlist) {
System.out.println("Method " + arrlist);
String sq = "INSERT INTO Inquiries(name,mail,tp,msg) VALUES(?,?,?)";
PreparedStatement pr = con.prepareStatement(sq);
for (Inquiries inquiries : arrlist) {
pr.setString(1, inquiries.getName());
pr.setString(2, inquiries.getMail());
pr.setString(3, inquiries.getTp());
pr.setString(4, inquiries.getMsg());
}
pr.executeQuery();//executeBatch();
}
Let's talk in O-O-P way.
Here Inquiries is your model, model is nothing but simple class that has instance members and public methods to get and set value of model's instance variable.
Generally we put all database related operations code in their respective models.
e.g. I have model "Model" which typically maps to database table say it as "TableModel" ,I would do something like this:
public class Model{
private int id;
private String attr;
//other properties of the model
public int getId(){
return id;
}
public void setId(int id){
this.id=id;
}
//other getters and setters
//here we write methods to performs database operations
public void save(){
//use "this" to get properties of object
//logic to save to this object in database table TableModel as record
}
public void delete(int id){
//logic to delete this object i.e. from database table TableModel
}
public Model get(int id){
//retrieve record from table TableModel with this id
}
//other methods to get data from database.
}
Now question is how I can use this in some another class. Let's say I have list of Model objects and I wish to insert them in to database.I will do it something like this:
public class AnotherClass{
public void someMethod(){
//create list of models objects e.g. get them from user interface
ArrayList<Model> models=new ArrayList<>();
for(int i=0;i<3;i++){
Model model=new Model();
model.setId(i);
model.setAttr("attr"+i);
models.add(model);
}
SomeOtherClass obj=new SomeOtherClass();
obj.insert(models);
}
}
public class SomeOtherClass{
//other code above.....
//my method that inserts each Model object in database
//Note: this is sample method , you should do it in optimized way
// e.g. batch insert
public void insert(ArrayList<Model> models){
for(Model myModel:models){
myModel.save();
}
}
//other code below.....
}
You are using the wrong type parameter for the ArrayList. Instead of ArrayList<String> you need ArrayList<Inquiries>. To fix the problem, you should remove this code ...
ArrayList<String> arrInq = new ArrayList<String>();
arrInq.add(name);
arrInq.add(mail);
arrInq.add(tp);
arrInq.add(msg);
... and replace it with this code:
ArrayList<Inquiries> arrInq = new ArrayList<Inquiries>();
arrInq.add(new Inquiries(name, mail, tp, msg));
I got a message says error: cannot find symbol regarding on c1.certificateAwarded(grade); statement. I have no idea what is the problem. Really need all the help I can get.
Here's the code:
ExamDetails.java
package Exams;
import javax.swing.JOptionPane;
public class ExamDetails {
public static void main(String[] args) {
StudentResults sr = new StudentResults();
sr.inputStudentName();
sr.inputExamName();
sr.inputScore();
sr.inputGrade();
sr.DisplayDetails();
Certificates c1 = new Certificates();
c1.certificateAwarded(grade);
}
}
StudentResults.java
package Exams;
import javax.swing.JOptionPane;
public class StudentResults {
private String fullname;
private String examName;
private int examScore;
private int examGrade;
public String getStudentName()
{
return fullname;
}
public void setStudentName(String name)
{
fullname = name;
}
public String getExamName()
{
return examName;
}
public void setExamName(String exam)
{
examName = exam;
}
public int getExamScore()
{
return examScore;
}
public void setExamScore(int score)
{
examScore = score;
}
public int getExamGrade()
{
return examGrade;
}
public void setExamGrade(int grade)
{
examGrade = grade;
}
public void inputStudentName()
{
fullname = JOptionPane.showInputDialog("Enter the student's name");
}
public void inputExamName()
{
examName = JOptionPane.showInputDialog("Enter the subject's name");
}
public void inputScore()
{
String scoreString = new String();
JOptionPane.showInputDialog("Enter the student's score");
examScore = Integer.parseInt(scoreString);
}
public void inputGrade()
{
String gradeString = new String();
JOptionPane.showInputDialog("Enter the student's grade");
examGrade = Integer.parseInt(gradeString);
}
public String DisplayDetails()
{
String d;
d = "Student Name : " + fullname + "Exam Name : " + examName + "Score : " + examScore + "Grade : " + examGrade;
return d;
}
}
Certificates.java
package Exams;
public class Certificates extends StudentResults {
private String certificate;
public String Grade;
Certificates()
{
super();
certificate = "No Certificate Awarded";
}
String certificateAwarded(/*int grade*/) {
//StudentResults g = new StudentResults();
//Grade = g.inputGrade();
//Grade = inputGrade(examGrade);
if(Grade.equals("Grade : A"))
{
this.certificate = "Certificate of Excellence";
}
else
if(Grade.equals("Grade : B"))
{
this.certificate = "Certificate of Achievement";
}
else
if(Grade.equals("Grade : C"))
{
this.certificate = "Certificate of Achievement";
}
else
this.certificate = "No Certificate Awardedt";
return this.certificate;
}
}
In the ExamDetails.java class, you don't declare or instantiate the grade variable that you're passing to the certificateAwarded method.
Also, you have parameters commented out in your Certificates.java class. You should uncomment the parameter.
For your code to compile, grade would have to be either
a local variable declared within the main method
a field defined on the ExamDetails class
Neither of these declarations are present so the compiler is telling you that it can't find the grade "symbol".
Try adding int grade = sr.getExamGrade(); above the problem line, or something similar.
As the comment suggested, you need to have "grade" declared. Without it, the compiler can't complete determining what the signature is for Certficates.certificateAwarded, since what goes in the argument list is part of the signature. More importantly, you have this in your code:
String certificateAwarded(/* int grade */)
The parameter, "int grade" is commented out. So the compiler sees this:
String certificateAwarded( )
So, what the compiler might be telling you is that it is looking for a method of Certificates named certificateAwarded that takes 1 argument of type {whatever type "grade" is}. It doesn't find that.
I said "might be" because you are missing two symbols on the line in question: grade and a method with a matching signature.
I can think of two things you can try to fix it:
Change " c1.certificateAwarded(grade);" to "c1.certificateAwarded();"
Declare "grade" to be an int somewhere in main (or in a place that is visible within main) and change "String certificateAwarded(/int grade/)" to "String certificateAwarded(int grade)".
I would start by trying the first option. If it is necessary to try the second, you will need to add additional code in both main (or place where grade is visible to main) and in the certificateAwarded method.