Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have ArrayList and protected getter function in first class and function in second class, which extends first class. I do getList().size() in function, but getting 0. If I do myList.size() in first class, I getting right answer.
Code:
protected List<WrappedGameProfile> getList(){
return Text;
}
public int getServerInfoSize(){
return super.getList().size(); //returns 0
}
All code:
package ServerInfo;
//imports
public class ServerInfo extends JavaPlugin {
Logger log;
private List<WrappedGameProfile> Text = new ArrayList<WrappedGameProfile>();
FileConfiguration config;
protected String ConvertFormat(String format){
return format.replace("#0", ""+ChatColor.BLACK).replace("#1", ""+ChatColor.DARK_BLUE).replace("#2", ""+ChatColor.DARK_GREEN).replace("#3", ""+ChatColor.DARK_AQUA).replace("#4", ""+ChatColor.DARK_RED).replace("#5", ""+ChatColor.DARK_PURPLE).replace("#6", ""+ChatColor.GOLD).replace("#7", ""+ChatColor.GRAY).replace("#8", ""+ChatColor.DARK_GRAY).replace("#9", ""+ChatColor.BLUE).replace("#a", ""+ChatColor.GREEN).replace("#b", ""+ChatColor.AQUA).replace("#c", ""+ChatColor.RED).replace("#d", ""+ChatColor.LIGHT_PURPLE).replace("#e", ""+ChatColor.YELLOW).replace("#f", ""+ChatColor.WHITE);
}
protected List<WrappedGameProfile> getList(){
return Text;
}
protected void setText(List<WrappedGameProfile> Text){
this.Text = Text;
}
public void onEnable(){
log = getLogger();
log.info("GuiServerInfo activating...");
this.saveDefaultConfig();
config = getConfig();
ProtocolLibrary.getProtocolManager().addPacketListener(
new PacketAdapter(this, ListenerPriority.NORMAL,
Arrays.asList(PacketType.Status.Server.OUT_SERVER_INFO), ListenerOptions.ASYNC) {
#Override
public void onPacketSending(PacketEvent event) {
handlePing(event.getPacket().getServerPings().read(0));
}
}
);
for (int i = 0; i < config.getStringList("Text").size();i++){
Text.add(
new WrappedGameProfile(
"id" + i + 1,
ConvertFormat(config.getStringList("Text").get(i)))
);
}
log.info("GuiServerInfo active!");
}
#Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (sender.isOp()){
if (args.length > 0){
if (args[0].equalsIgnoreCase("set")){
Text.clear();
List<String> newConf = new ArrayList<String>();
for (int i = 1; i < args.length; i++){
Text.add(new WrappedGameProfile("id" + Text.size() + 1, ConvertFormat(args[i])));
newConf.add(args[i]);
log.info("Add ServerInfo: " + args[i]);
}
config.set("Text", newConf);
sender.sendMessage("Successful!");
return true;
}
}
return false;
} else {
sender.sendMessage("You not op!");
return true;
}
}
private void handlePing(WrappedServerPing ping) {
ping.setPlayers(Text);
}
public void onDisable(){
saveConfig();
log.info("GuiServerInfo disabled!");
}}
And:
package ServerInfo;
import java.util.ArrayList;
import java.util.List;
import com.comphenix.protocol.wrappers.WrappedGameProfile;
public class ServerInfoAPI extends ServerInfo {
public void setServerInfo(List<WrappedGameProfile> Text){
super.setText(Text);
super.log.info("Set new ServerInfo");
}
public void setServerInfo(String[] Text){
List<WrappedGameProfile> tmp = new ArrayList<WrappedGameProfile>();
for (int i = 0; i < Text.length; i++) {
tmp.set(i, new WrappedGameProfile("id" + i + 1, ConvertFormat(Text[i])));
}
super.setText(tmp);
super.log.info("Set new ServerInfo");
}
public void insertServerInfoString(String str, int num){
getList().set(num, new WrappedGameProfile("id" + num, ConvertFormat(str)));
super.log.info("Add new ServerInfo - num:" + num + ", Text:" + str);
}
public void addServerInfoString(String str){
super.getList().add(new WrappedGameProfile("id" + super.getList().size() + 1, ConvertFormat(str)));
super.log.info("Add new ServerInfo: " + str);
}
public int getServerInfoSize(){
return super.getList().size();
}
public String getServerInfoString(int num){
return super.getList().get(num).getName();
}
public int getServerInfoStringNum(WrappedGameProfile pr){
return super.getList().indexOf(pr);
}
}
Just your terminology alone shows a serious lack of understanding of things like Objects, Classes, Packages, etc. you need to read up on some introductory tutorials.
To answer the question it sounds like you have created a new instance inheriting from a super class. Because it is a new instance the list is not shared, so changes you make in one class do not get seen.
To share one list between multiple objects you need to pass the list object from one to another.
Don't try to globalize variables. Instead call public methods of the class that holds the variable that will allow other objects to query its state or make controlled change to its state.
I agree also with the others: it sounds as if you're misusing inheritance, since this is not a problem that should be solved with inheritance, but only your code (which we haven't seen at the time of this writing) will tell us for sure.
Regarding:
No, i have just one List
No, if you're using inheritance, then you have more than one List. Again don't try to solve this with inheritance.
Why don't you have a
private List<WrappedGameProfile> text = new ArrayList<WrappedGameProfile>();
public List<WrappedGameProfile> getText() {
return text;
}
in your super class?
than your code will be :
public int getServerInfoSize(){
return getText().size();
}
and please do camelcasing correct, the variable Text has to be text.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I am trying to make a class to handle my user database for a programming school project. This will be using arrays and not arraylist which is a core parameter of the assignment.
public class UserDB {
User[] UserAry;
public UserDB(){
UserAry = new User[0];
}
//admin
public void addUser(String id, String pw, char type){
User[] NewUserAry = new User[UserAry.length+1];
for (int i=0; i<UserAry.length;i++){
NewUserAry[i] = UserAry[i];
}
NewUserAry[NewUserAry.length-1] = new User(id,pw,type);
UserAry = NewUserAry;
}
}
This is the code. I'm worried that if i were to call this in another class, then the array would always be at 0(when i call UserDB) or 1 (when i add a new user it would add one to previous zero) , before the arraysize becomes to zero again since it is initialized as 0.
I do not see any problem with your code. Just for the sake of making it cleaner, I have replaced your for loop with System.arraycopy. Apart from that, I have also replaced the variable names following the naming convention. Given below is the working code:
public class User {
String id,pw;
char type;
public User(String id, String pw, char type) {
super();
this.id = id;
this.pw = pw;
this.type = type;
}
#Override
public String toString() {
return "User [id=" + id + ", pw=" + pw + ", type=" + type + "]";
}
}
public class UserDB {
User[] userAry;
public UserDB() {
userAry = new User[0];
}
public void addUser(String id, String pw, char type) {
User[] newUserAry = new User[userAry.length + 1];
System.arraycopy(userAry, 0, newUserAry, 0, userAry.length);
newUserAry[newUserAry.length - 1] = new User(id, pw, type);
userAry = newUserAry;
}
public void printList() {
for (User user:userAry)
System.out.println(user);
}
}
public class TestUserDB {
public static void main(String[] args) {
UserDB db=new UserDB();
db.addUser("a1", "a", 'a');
db.addUser("a2", "b", 'b');
db.addUser("a3", "c", 'a');
db.addUser("a4", "d", 'b');
db.printList();
}
}
Output:
User [id=a1, pw=a, type=a]
User [id=a2, pw=b, type=b]
User [id=a3, pw=c, type=a]
User [id=a4, pw=d, type=b]
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
So, this is a class where I store data from another class called (Name)
the class (Name) got 3 informations. Name (String)/Number List /Adress List I used the last 2 as a List so I can allow multiple adresses/numbers
now the thing is, i can't get my getContact in this code to work, it doesn't return anything, so i thought that i messed up somewhere, checked everything and things were right, so i bypassed toString and printed an object of the type Namebook is my main method and it worked just fine.
public class Namebook {
private ArrayList<Name> contact;
private Name ctc;
public Namebook(){
contact = new ArrayList<Name>();
}
public void addContact(Name name){
this.contact.add(name);
}
public String getContact(){
return String.valueOf(this.contact);
}
#Override
public String toString() {
return String.valueOf(this.contact);
}
}
Class (Name)
public class Name {
private String name;
private List<String> number;
private List<String> Adress;
public Name(String name){
this.name = name;
}
public void addNumber(List<String> num){
this.number = num;
}
public void addAdress(List<String> adress){
this.Adress = adress;
}
public List<String> getNumber(){
return this.number;
}
public List<String> getAdress(){
return this.Adress;
}
public String toString() {
return this.name + " " + getNumber() + " " + getAdress() ;
}
}
Main
public class Main {
Scanner reader = new Scanner(System.in);
public static void main(String[] args) throws Exception {
Name person = new Name("sacha");
ArrayList<String> add = new ArrayList<String>();
ArrayList<String> num = new ArrayList<String>();
add.add("chicago");
num.add("13213223");
person.addNumber(num);
person.addAdress(add);
//System.out.println(person);
Namebook p1 = new Namebook();
p1.addContact(person);
p1.getContact();
}
}
Your toString and getContact methods are identical, and behave identically.
Case 1:
System.out.println(person);
This is short for
System.out.println(person.toString());
Case 2:
p1.getContact();
This is not short for anything. But notice that you do not have a System.out.println statement. That is what prints the output of the method. Without that, nothing is printed. To fix it
System.out.println(p1.getContact());
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Keep getting the error, I can't seem to figure out why, the abstract method is implemented. I tried adding the keyword public, but that didn't help at all. I've read examples on the internet about abstract method, but mostl of them are void.
The abstract class:
public abstract class Osoba {
private String ime_prezime;
private char pol;
public Osoba(String ime_prezime, char pol) {
this.ime_prezime=ime_prezime;
this.pol=pol;
}
public String getImePrezime() { return ime_prezime; }
public void setImePrezime(String ime_prezime) { this.ime_prezime=ime_prezime; }
public char getPol() { return pol; }
public void setPol(char pol) { this.pol=pol; }
abstract int brojGodinaOsobe(Datum danasnji_datum);
}
And the subclass:
public class OsobaDatum extends Osoba{
private Datum datum_rodjenja;
public OsobaDatum(String ime_prezime, char pol, final Datum datum_rodjenja) {
super(ime_prezime, pol);
this.datum_rodjenja=datum_rodjenja;
}
public String toString() {
return "OsobaDatum: \n" + "Ime i prezime: " + getImePrezime() +
"\n" + "Pol: " + getPol() + "\nDatum rodjenja: "
+ datum_rodjenja.toString();
}
int brojGodina(Datum danasnji_datum) {
if ( datum_rodjenja.getMesec() < danasnji_datum.getMesec() ) {
return danasnji_datum.getGodina() - datum_rodjenja.getGodina();
}
else if (datum_rodjenja.getDan() <= danasnji_datum.getDan() &&
datum_rodjenja.getMesec() == danasnji_datum.getMesec()) {
return danasnji_datum.getGodina() - datum_rodjenja.getGodina();
}
else
return danasnji_datum.getGodina() - datum_rodjenja.getGodina() -1 ;
}
}
The abstract method's name is brojGodinaOsobe() and it looks like you only implemented a method called brojGodina(). Add the Osobe and you should be OK.
It looks like you are not overriding the method brojGodinaOsobe(Datum danasnji_datum); from Super class.
Change brojGodina(Datum danasnji_datum) to brojGodinaOsobe(Datum danasnji_datum) in the OsobaDatum class.
Regards.
So I have a class named MainControl that is ran from another class (The main one) that I am certain only runs once. Inside of MainControl I have a few things that have to be loaded, one of which being a function that populates the HashMap with the key set to the keybind (int) and the values set to a class that holds the information of the specific keybinds function (KeyDetails).
So to populate the hashmap it goes through 2 loops, the first being to loop through the list of functions, the second to check if the key should be bound to the function. If the second loop finds that it should be bound it will run Keybinds.put(KeyCode, new Details(Function, KeyCode, KeyName, false); (Just ignore the false).
For some reason it ends up forcing MainControl(); to run again once it reached Keybinds.put... for no reason at all. There are no functions that should cause MainControl to run and it works when I remove the Keybinds.put line. Just by removing THAT single line it works.
public MainControl()
{
System.out.println("Starting System");
LoadSession("Default");
System.out.println("Ended System - Never Reached");
}
public static void LoadSession(String s)
{
Keybinds = new HashMap();
for (int i = 0; i < FunctionStringList.length; i++)
{
String Key = "";
int KeyVal = 0;
try
{
for (int a = 0; a < KeyBindingList.length; a++)
{
if (KeyBindingList[a].KeyName.equalsIgnoreCase(FunctionStringList[i]))
{
Key = KeyBindingList[a].KeyName
KeyVal = KeyBindingList[a].KeyCode
}
}
Keybinds.put(KeyVal, new Details(FunctionStringList[i], KeyVal, Key, false));
System.out.println("Key: " + Key + " Val: " + KeyVal + " Hack: " + FunctionStringList[i]);
}
catch (Exception E) { E.printStackTrace(); }
}
}
public static String FunctionStringList[] =
{
"Forward", "Backwards", "StrafeLeft", "StrafeRight", "Jump", "Sneak"
};
Details Class:
public class Details extends MainControl
{
public Details(String Name, int KeyCode, String KeyName2, boolean Bool)
{
FunctionName = Name;
Code = KeyCode;
KeyName = KeyName2 != null ? KeyName2 : "None";
State = Bool;
}
public boolean Toggle()
{
State = !State;
return State;
}
public void SendChat(String s)
{
Console.AddChat(s);
}
public String FunctionName;
public String KeyName;
public int Code;
public boolean State;
}
Your Details class is-a MainControl; it's a subclass.
When you extend a class, the child class' constructor is calling the parent object's no-arg constructor which is causing an infinite recursion.
Edit to add from the comment below: Your "offending line" is:
Keybinds.put(KeyVal, new Details(FunctionStringList[i], KeyVal, Key, false));
When the Details constructor executes, it then calls MainControl() ... which then calls LoadSession() ... which then creates a new Details ... which then calls MainControl() .. etc, etc. Infinite recursion until you get a Stack Overflow.
I am trying to create a class. Let's call it Questionnaire. In Questionnaire, I want to instantiate a number of classes called Question. The constructor for Questionnaire accepts a string array of words, and for each word, there should be a Question class to accept it as an argument for its constructor. In other words, for every string that is passed as an argument, I want to create a Question.
I need to be able to put Questionnaire within a bigger class and still call the methods of the Question classes. The size of the array passed to Questionnaire varies as well. I don't know how I can put multiple classes within another class when I don't know how many classes there will be, and how to reference them from an outer class. If the array was a fixed length I'd just create Questions as question1, question2, question3... but since this is not the case I am not sure anymore. I do know there is a maximum number of Question classes I want to create though.
edit: I'm using J2ME CDLC 1.1 MIDP 2.0 for this (it's part of a mobile phone app) so my solutions are constrained by what it offers.
You don't want to have a separate variable per question - use a List<Question> to have one variable which refers to a collection of questions:
public class Questionnaire
{
private final List<Question> questions;
public Questionnaire(String[] words)
{
questions = new ArrayList<Question>();
for (String word : words)
{
questions.add(new Question(word));
}
}
// Use questions here
}
EDIT: If you're in an environment without generics, you could use the non-generic form, like this:
private final List questions;
public Questionnaire(String[] words)
{
questions = new ArrayList();
for (String word : words)
{
questions.add(new Question(word));
}
}
or like this if you don't have List/ArrayList:
private final Vector questions;
public Questionnaire(String[] words)
{
questions = new Vector();
for (String word : words)
{
questions.add(new Question(word));
}
}
In either case you'll need to cast on every access. Alternatively, you could use an array:
private final Question[] questions;
public Questionnaire(String[] words)
{
questions = new Question[words.length];
for (int i = 0; i < words.length; i++)
{
questions[i] = new Question(word);
}
}
As J2ME API lacks the Collections API, your best bet is to grab a Vector.
Vector questions = new Vector();
for (int i = 0; i < words.length; i++) {
questions.addElement(new Question(words[i]));
}
You probably want to go with a Set of questions rather than List. Try :
private final Set<Question> questions;
This will prevent duplicate questions. Everything else will be the same as JonSkeet's answer.
Why don't you use a List on the questionaire and for each question you add you add one to the List, for example.
public class Questionnaire
{
public List<Question> myQuestions {get; private set;}
public Questionnaire(string[] questions)
{
myQuestions = new List<Questions>();
foreach(string q in questions)
{
myQuestions.Add(new Question {questionText = g});
}
}
}
public class Question
{
public string questionText {get; set;}
}
Then you will be able to check the questions from outside... this is what you want?
Hope this helps
EDIT: ohh is Java, but you got the idea right?
import java.util.*;
public class Questionnaire implements Iterable<Question> {
private final List<Question> questions;
public Questionnaire(String ...words) {
questions = new ArrayList<Question>(words.length);
for(String word : words) {
questions.add(new Question(word));
}
}
// allows you to use a Questionnaire object in a for-each loop
public Iterator<Question> iterator() { return questions.iterator(); }
#Override
public String toString() { return questions.toString(); }
}
You could add many more goodies to your class to make it more useful. An example of using the class above follows:
public class QuestionnaireTest {
public static void main(String[] words) {
Questionnaire questionnaire = new Questionnaire(words);
for(Question q : questionnaire) {
System.out.println("You asked: " + q);
}
}
}
You could also use it as follows:
public class QuestionnaireTest3 {
public static void main(String[] words) {
// because I declared the constructor to accept "String ...words", I can specify as many questions as I want using simple syntax
Questionnaire questionnaire = new Questionnaire("How deep the ocean?", "How high the moon?");
for(Question q : questionnaire) {
System.out.println("I asked: " + q);
}
}
}
Even though I did so in my first example above, you should really accept an array of String objects as questions. Here's a better design:
public class Questionnaire implements Iterable<Question> {
private List<Question> questions = new ArrayList<Question>();
public void add(Question q) {
if(q == null) throw new IllegalArgumentException("can't add null question!");
questions.add(q);
}
public Question get(int index) {
if(index < 0 || index >= questions.size()) throw new IndexOutOfBoundsException("invalid question index: " + index);
return questions.get(index);
}
// allows you to use a Questionnaire object in a for-each loop
public Iterator<Question> iterator() {
return Collections.unmodifiableList(questions).iterator();
}
#Override
public String toString() { return questions.toString(); }
}
public abstract class Question {
public String getText();
public String getAnswer();
public String getOptions();
// ...
}
public class YesNoQuestion extends Question {
private final String text;
private final String answer;
public YesNoQuestion(String text, boolean answer) {
if(!(text.startsWith("Is"))) throw new IllegalArgumentException("Must start with is: " + text);
this.text = text;
this.answer = answer ? "Yes" : "No"; // if answer == true, the "Yes",...
}
#Override
public String getText() { return text; }
public String getAnswer() { return answer; }
public String getOptions() { return "Yes or No ?"; }
}
And now you can use it as follows:
public class QuestionnaireTest4 {
public static void main(String[] words) {
Questionnaire test = new Questionnaire();
test.add(new YesNoQuestion("Is dogs animals?", false));
test.add(new YesNoQuestion("Is me has cheezburgers?", true));
for(Question q : questionnaire) {
System.out.println(q);
System.out.println(q.getOptions());
String input = null; // you need to code this part
if(q.getAnswer().equals(input))
System.out.println("CORRECT!");
else
System.out.println("YOU IS STUPID!!!!");
}
}
}