How to call a method in the same class [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am writing code for an e-mail system and I have one small problem, I can't figure out how to call a method.
what is the correct way to call the writeAllToFile method in the main method?
public class MailboxSystemSol{
public static void main (String args[]) throws IOException{
//code is too long to post here
}
public static void writeAllToFile(Userlist ul, User u, Message me){
//code is too long to post here
}
}
Here is the UserList class:
/**
* Created by Broomhead0 on 4/11/14.
*/
import java.util.ArrayList;
public class Userlist
{
ArrayList<User> users; //this is an arraylist that will store references to all users
public Userlist()
{
users = new ArrayList<User>();
}
// find a user in the list based on the username
public User findUser(String username)
{
// iterate through the array; only iterate according to how many users are currently in the array
for (int i = 0; i < users.size(); i++)
{
// access the particular user through users.(i), then get the name,
// and call the equals method on that name to compare it with the input username
if (users.get(i).userName.equals(username)){
return users.get(i);
}
}
// no user found
return null;
}
// add a user to the list; only do so if the user does not yet exist
public void addUser(User u)
{
if (findUser(u.userName) != null) //if there is a match,
System.out.println("User already exists");
else //if there is not match
{
users.add(u); //add the username
}
}
//check if this is correct
//accessors
public User getUser(int i){
return users.get(i);
}
public int getNumUsers(){
return users.size();
}
}
Here is the User class:
/**
* Created by Broomhead0 on 4/11/14.
*/
public class User
{
public String userName; // the name of the user
public Mailbox outbox; // reference to the mailbox of sent messages
public Mailbox inbox; // reference to the mailbox of received messages
// create mailboxes according to the size given as input
public User(String o, int boxsize) {
userName = o;
outbox = new Mailbox(boxsize);
inbox = new Mailbox(boxsize);
}
}
Here is the Message class:
/**
* Created by Broomhead0 on 4/11/14.
*/
public class Message {
// the properties of a message
private String sender;
private String receiver;
private String subject;
private String body;
// all property values are known at creation of the message; so initialize
public Message (String s, String r, String sub, String b)
{
sender = s;
receiver = r;
subject = sub;
body = b;
}
// any nice format of printing the names and the values of the properties will do
public void printMsg()
{
System.out.println("Sender: " + sender);
System.out.println("Receiver: " + receiver);
System.out.println("Subject: " + subject);
System.out.println("Message: " + body);
}
// what follows are basic getter methods
public String getSender()
{
return sender;
}
public String getReceiver()
{
return receiver;
}
public String getSubject()
{
return subject;
}
public String getBody()
{
return body;
}
}

public class MailboxSystemSol{
public static void main (String args[]) throws IOException{
//define userlist, user and message variables..
UserList userList = new UserList();
User user = new User("Matthew", 1024);
Message message = new Message("sender#gmail.com", "receiver#gmail.com", "Subject Content", "Body Content");
//do something with declared variables...
writeAllToFile(userList, user, message);
}
public static void writeAllToFile(Userlist ul, User u, Message me){
//code is too long to post here
}
}

Related

How do I call a variable from a void method in another class

How do I call the string variable user, from a void method in another class
I constantly get an error running this code because user in the getUser() function doesn't equal user in the action(ActionEvent j) function.
Class Alpha:
public class Alpha(){
private string user;
public Alpha(int temp){
temp = 0;
}
public void action(ActionEvent e){
String command = e.getActionCommand();
user = "hi";
}
public String getUser(){
return this.user;
}
Main:
public class Test {
public static void main(String[] args) {
Alpha n = new Alpha();
String username = n.getUser();
System.out.println(username);
}
}
Here a summarry of all the problems :
Class Alpha:
public class Alpha(){
private string user;
public Alpha(int temp){ why do you need a temp argument?
temp = 0; //why do you set temp at 0?
}
public void action(ActionEvent j){ // why do you need an ActionEvent j argument?
user = "hi";
}
public String getUser(){
return this.user;
}
Main:
public class Test {
public static void main(String[] args) {
Alpha n = new Alpha(); //you call a contructor but not the one you write -> Alpha(int temp)
String username = n.getUser();
/** you try to get the username here but it was never set (so it = null)
you set it in action(ActionEvent j), so you can try to insert
action(j);
**/
System.out.println(username);
}
}

Adding one Account Object to another Account Object

private HashMap<Integer, Account> accountMap;
There are account objects inside this map.
What i am trying to do is merging objects by their key lets say add Account 2 object to Account 1 and remove Account 2 from map.
This method is in bank class:
public void combineAccounts(int uid1, int uid2) {
Account x = new Account(uid1);
x.add(accountMap.get(uid1),accountMap.get(uid2));
}
Account.class:
a1.getValuables returns list obj : [Value: 16253.0 -> 100.0gr gold]
public class Account{
private final int uid;
private final List<Valuable> valuables;
public Account(int uid) {
this.uid = uid;
valuables = new ArrayList<>();
}
public void addValuable(Valuable valuable){
valuables.add(valuable);
}
/*implementation of getTotalValue method comes here*/
public double getTotalValue​(){
return 0;
//returns total amount of valuables present in that account
}
public Account add(Account a1,Account a2){
Account mergedaccount;
mergedaccount = a1.getValuables()+a2.getValuables() // something like this...
return mergedaccount;
}
public int getUid() {
return uid;
}
public List<Valuable> getValuables() {
return valuables;
}
public void sortValuables(){
Collections.sort(valuables);
}
#Override
public String toString() {
return "uid:" + uid + " " + valuables;
}
}
Bank.class:
public class Bank {
private HashMap<Integer, Account> accountMap;
private Account merged;
public Bank() {
accountMap = new HashMap<>();
}
/*implementation of createAccount method comes here*/
public void createAccount(int uid){
for (HashMap.Entry<Integer, Account> entry : accountMap.entrySet()) {
if(entry.getKey() == uid){
throw new IllegalArgumentException();
}
}
accountMap.put(uid,new Account(uid));
// creates an account of id uid, if that account already exists an exception is thrown
}
public Account getAccount(int uid){
return accountMap.get(uid);
}
#Override
public String toString() {
Collection<Account> accounts = accountMap.values();
return accounts.toString();
}
public void addValuable(int uid, Valuable valuable) {
if(accountMap.get(uid) ==null){
System.out.println("valuables could not be added, no such account");
return;
}else{
accountMap.get(uid).addValuable(valuable);
}
//Add valuable to an existing account, if the account does not exist, an error message should be printed.
}
public void combineAccounts(int uid1, int uid2) {
Account x = new Account(uid1);
x.add(accountMap.get(uid1),accountMap.get(uid2));
}
public void closeAccount(int uid) {
if(accountMap.get(uid) != null){
accountMap.remove(uid);
}else{
throw new IllegalArgumentException();
}
}
}

Java Unit Testing Help for loop

public void login(String username, String password) {
for(int i = 0; i < Users.size(); i++) {
user users = (user) Users.get(i);
if(users.getUsername().contains(username)
&& users.getPassword().contains(password)) {
userName = users.getUsername();
userLevel = users.getUserLevel();
isSuccess = true;
}
}
}
Hello everyone. I'm trying to do a java unit testing for this method using Java Junit. But i don't know how to do that? Because there's a for loop.
Let me explain the method.
for(int i=0;i<Users.size();i++){
This "Users" is a vector. This loop runs unit this vector ends.
user users = (user) Users.get(i);
Then im calling user class for user instance.
if((users.getUsername().contains(username)) &&
(users.getPassword().contains(password))) {
Then if any of the users that matches with the values in the vectors, this gives the output.
Can anyone tell me how to write a unit test for this?
Your code is hard to read. Learn Java coding standards.
Your method should not be printing anything. Determine if the user is valid. Print messages elsewhere.
I'll assume you've got a class User that encapsulates credentials:
package misc.user;
import org.apache.commons.lang3.StringUtils;
/**
* Created by Michael
* Creation date 8/5/2017.
* #link https://stackoverflow.com/questions/45524768/java-unit-testing-help-for-loop
*/
public class User {
private final String username;
private final String password;
public User(String username, String password) {
if (StringUtils.isBlank(username)) throw new IllegalArgumentException("username cannot be blank or null");
if (StringUtils.isBlank(password)) throw new IllegalArgumentException("password cannot be blank or null");
this.username = username;
this.password = password;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
#Override
public boolean equals(Object o) {
if (this == o) { return true; }
if (o == null || getClass() != o.getClass()) { return false; }
User user = (User) o;
if (!getUsername().equals(user.getUsername())) { return false; }
return getPassword().equals(user.getPassword());
}
#Override
public int hashCode() {
int result = getUsername().hashCode();
result = 31 * result + getPassword().hashCode();
return result;
}
#Override
public String toString() {
return "{\"User\":{"
+ "\"username\":\"" + username + "\""
+ ",\"password\":\"" + password + "\""
+ "}}";
}
}
I'd test it using JUnit:
package misc.user;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Michael
* Creation date 8/5/2017.
* #link https://stackoverflow.com/questions/45524768/java-unit-testing-help-for-loop
*/
public class UserTest {
private static List<User> users;
#BeforeClass
public static void setUp() {
users = new ArrayList<>();
users.add(new User("FooBar", "myPassword"));
users.add(new User("GeorgeBush", "exPrez"));
users.add(new User("weatherBoy", "cloudy"));
}
#Test
public void testLogin_Success() {
// setup
String username = "weatherBoy";
String password = "cloudy";
// exercise
boolean isValidUser = users.contains(new User(username, password));
// assert
Assert.assertTrue(isValidUser);
}
#Test
public void testLogin_Failure() {
// setup
String username = "noSuchUser";
String password = "does not matter";
// exercise
boolean isValidUser = users.contains(new User(username, password));
// assert
Assert.assertFalse(isValidUser);
}
}

How to create a test class for a java project [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have created a Browser class for my project. I now need to extend this project and therefore need to create a suitable test plan and test class.
How do I create this test class?
/**
* Write a description of class Browser here.
*
* #author (johnson)
* #version (10/12/13)
*/
import java.util.ArrayList;
import java.util.List;
public class Browser
{
// instance variables - replace the example below with your own
private int iD;
private String email;
private int yearOfBirth;
private boolean memberID;
private WineCase wineCase;
private boolean loggedIn;
private Website website;
private boolean discount;
private List<Boolean> baskets = new ArrayList<Boolean>();
/**
* Constructor for objects of class Browser
*/
public Browser()
{
// initialise instance variables
wineCase = null;
website = null;
iD = 00065;
yearOfBirth = 1992;
memberID = true;
discount = false;
}
/**
* Constructor for objects of class Browser
*/
public Browser(String newEmail,int newYearOfBirth)
{
// initialise instance variables
wineCase = null;
website = null;
iD = 0;
email = newEmail;
yearOfBirth = newYearOfBirth;
loggedIn = false;
memberID = true;
discount = false;
}
/**
* Constructor for objects of class Browser
*/
public Browser(int newID, String newEmail,int newYearOfBirth)
{
// initialise instance variables
wineCase = null;
website = null;
iD = newID;
email = newEmail;
yearOfBirth = newYearOfBirth;
memberID = true;
discount = false;
}
/**
* returns the ID
*/
public int getId()
{
return iD;
}
/**
* gets the email of the browser class
*/
public String getEmail()
{
return email;
}
public boolean getDiscount()
{
return discount;
}
/**
* gets the yearOfBirth for the browser class
*/
public int yearOfBirth()
{
return yearOfBirth;
}
public double getWineCost()
{
return wineCase.getWineCost();
}
public double getWineCase()
{
return wineCase.getWineCost();
}
/**
* returns
*/
public void setLoginStatus(boolean status)
{
loggedIn = status;
}
/**
* returns
*/
public void selectWineCase(WineCase winecase)
{
wineCase = winecase;
System.out.println ("Browser "+getId()+" has selcted wine case"+wineCase.getRefNo()+ "of "+winecase.getNoOfBottles()+ wineCase.getDescription()+ " at £"+wineCase.getWineCost());
}
/**
* returns
*/
public void payForWine()
{
website.checkout(this);
}
public void setId()
{
iD = 999;
}
public void setWebSite(Website website)
{
this.website = website;
}
public void setDiscount(boolean discount)
{
this.discount = discount;
}
public ArrayList<WineCase> getBasket(WineCase wineCase)
{
this.wineCase = wineCase;
System.out.println ("Browser "+getId()+" has selcted wine case"+wineCase.getRefNo()+ "of "+wineCase.getNoOfBottles()+ wineCase.getDescription()+ " at £"+wineCase.getWineCost());
}
}
Any answers/replies would be greatly appreciated.
You can use a unit testing framework as http://junit.org/. There are numerous examples on the internet.
An example unit test would be:
public class BrowserTest{
#Test
public void testNoArgsConstructor(){
Browser testedBrowser = new Browser();
assertNull(testedBrowser.getWineCase());
assertNull(testedBrowser.getWebsite());
assertEquals(00065, testedBrowser.getId());
assertEquals(1992, testedBrowser.getYearOfBirth());
assertTrue(testedBrowser.getMemberId());
assertFalse(testedBrowser.isDiscount());
}
//more tests
}
If You want to test your class, use JUnit framework - you will create unit tests (http://junit.org/). It is already included in IDE (Eclipse), just go File → New → JUnit → JUnit Test case.

How to in a class, use an attribute of a different class to find out the other attribute. (java)

Sorry if i'm being vague here, i'll post my code for you guys too. I'm a beginner so go easy on me.
I have a class called student, it has an int id, and another String name. I have created another Class for the GUI. It has a window that pops up and has a field for the id. I want to enter the ID and get the Name from that ID. I have no idea of going about this and i've been stuck for hours. I'm kind of slow to catch on, so could someone help me? I'm not very good at inheritance. (also, i have two other classes, but i don't think they would be of any help here.
STUDENT CLASS
public class Student {
private int id;
private String name;
private ArrayList<Course> regCourses;
public int getId() {
return id;
}
public String getName() {
return name;
}
public ArrayList<Course> getRegCourses() {
return regCourses;
}
public Student(int i, String n) {
id = i;
name = n;
regCourses = new ArrayList<Course>();
}
public String toString() {
String answer = id + " " + name + " - Registered Courses: ";
if (regCourses.size() == 0)
answer += "NONE";
else {
for (int i = 0; i < regCourses.size(); i++) {
answer += regCourses.get(i).getDepartment().getId()
+ regCourses.get(i).getCode();
if (i != regCourses.size() - 1)
answer += ", ";
}
}
return answer;
}
public void registerFor(Course c) {
if (!isRegisteredInCourse(c)) {
// Register
regCourses.add(c);
if (!c.getClassList().contains(this)) {
c.getClassList().add(this);
if (!c.getDepartment().getStudentList().contains(this))
c.getDepartment().getStudentList().add(this);
}
}
}
public boolean isRegisteredInCourse(Course c) {
return regCourses.contains(c);
}
}
And here's the search code in another class.
public class MainGUIWindow extends JFrame implements ActionListener {
JLabel studentID, studentName, currentRegCourses;
JButton search, regForCourse, withdraw;
JTextField idField, nameField;
JScrollPane courseScrollList;
public MainGUIWindow(String title) {
super(title);
//GUI STUFF
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == search) {
if (idField.getText() != null) {
int id = Integer.parseInt(idField.getText());
Student temp = null;
//CODE GOES HERE
}
}
}
public static void main(String[] args) {
new MainGUIWindow("Student Administration System").setVisible(true);
Also, if need be, these all my java files.
http://www.filehosting.org/file/details/426633/JavaCode-SO.zip
Edit: There are 2 more Classes that are my test programs that have data in them.
You could store the Students in a Hashmap or treemap and then look them up
i.e
HashMap<Integer,Student> studentMap = new HashMap<>();
studentMap.put(matt.getId(), matt);
.....
Student s = studentMap.get(lookupId); /* Retrieve based on Student id*/

Categories

Resources