Trying to understand methods - calling methods within own class - help
I'm trying to write a simple program to search for letters in a string. I'm having a ton op problems; java seems so complicated with a lot of rules.
The main problem I'm having (for now) is calling a method within the same class as main.
import java.io.*;
class LookForLetters{
public static void main(String[] args)
int i = 0;
int j = 0;
int l = 0;
int m = 0;
String question1 = "Enter the line to be searched";
String question2 = "Enter the line to be searched";
returnResponse stringtosearch = new returnResponse(question1); // here's where my problem is
char[] chartosearch = stringtosearch.toCharArray();
returnResponse letterstofind = new returnResponse(question2);
char[] chartofind = letterstofind.toCharArray();
int findlength = chartosearch.length();
int searchlength = chartofind.length();
int[] k = new int[searchlength];
for(i = 0; i < findlength; i++)
for(j = 0; j < searchlength; j++)
if(chartosearch[i] == chartofind[j])
k[l] = i;
l++;
System.out.print("T");
System.out.print(i + " " + l);
if(l == 0)
System.out.print(chartofind[i] + " is the not in the sentence.");
System.out.println();
else
System.out.print(chartofind[i] + " is the ");
for(m = 0; m < l; m++)
System.out.print(k[l] + " ");
System.out.print("letter of your sentence");
System.out.println();
l = 0;
public String returnResponse(String question){
String response = " ";
System.out.print(question);
try
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReaderbr = new BufferedReader(isr);
response = br.readLine();
catch(IOException e)
System.out.print("error");
return response;
}The compiler says that it can't find the returnResponse method. when I try to instantiate the whole class, it says the package is not included. Please help.
JoachimSauer wrote:
DaneWKim wrote:
thank you very much for your response. I'm sure it's obvious that I'm really confused. I'm used to C and assembly programming, so the OO concepts are really foggy.That particular line doesn't even deal with any OO concept. But the fact that you already know C helps me give a (hopefully) more useful answer:
What is the return type of the method you're trying to call?
What is the type of the variable you want to assign the return value to?
Are those compatible? Or even more general: do they both exist?I changed it to:
String stringtosearch = returnResponse(question1);
char[] chartosearch = stringtosearch.toCharArray();
String letterstofind = returnResponse(question2);
char[] chartofind = letterstofind.toCharArray();I guess I'm getting confused with medthods, class and types. There's a whole host of new vocabulary and rules with OO and java that have me a bit confused. I appreciate your help.
Similar Messages
-
Calling a method within a class form another class(ViewController)
I am creating an SQL project in XCODE. I have one view. My main view controller is loading the database to a table/array. I want to add another class (with no NIB) just to handle the display of the table in a UITableView. So, I added a skeleton cocoa touch class file to my classes folder to handle this function when parameters change.
So, in my app delegate, the "applicationdidFinishLaunchingWithOptions" method loads my mainViewController and NIB. On the "viewDidLoad" method in my mainViewController, I read a URL into an SQLite database and close the database. Herein lies the problem: I want to call my new class (TableViewHandler) and pass it the array created in the mainViewController and use the array to populate the UITable.
How do I call a class from within another class (which has no NIB) to populate the table? Especially if my TableViewHandler has no "viewDidLoad", "viewDidAppear", etc.
Regads,
-KevinThis is what my exact problem.
i've created a bean (DataBean) to access the database. i'm having a servlet program (ShopBook). now to check some details over there in the database from the servlet i'm in need to use a method in the DataBean.
both ShopBook.java and DataBean.java lies in the package shoppack.
in ShopBook i tried to instantiate the object to DataBean as
DataBean db = new DataBean();
it shows the compiler error, unable to resolve symbol DataBean.
note:
first i compiled DataBean.java, it got compiled perfectly and the class file resides inside the shoppack.
when i'm trying to compile the ShopBook its telling this error.
hope i'm clear in explaining my problem. can u please help me?
thank u in advance.
regards,
Fazli -
Help with creating a method within a class
I need help creating another method within the same class.
Here is part of my progam, and could anyone help me convert the switch statement into a seperate
method within the same class?
import javax.swing.JOptionPane;
public class Yahtzee
public static void main (String[] args)
String numStr, playerStr, str, tobenamed;
int num, times = 13, roll, x, y, maxRoll = 3, z = 0, t;
int firstDie, secondDie, thirdDie, fourthDie, fifthDie, maxDie = 5, reroll;
int rerolling = 0, categoryChoice, score, nextDie1, nextDie2, nextDie3, nextDie4;
Die die1, die2, die3, die4, die5;
do
numStr = JOptionPane.showInputDialog ("Enter the number of player: ");
num = Integer.parseInt(numStr);
while (num < 1 || num > 6); //end of do loop
String [] player = new String[num];
// boolean //finsih later to make category choice only once.
for (x = 0; x < num; x++)
playerStr = JOptionPane.showInputDialog ("Name of Player" + (x + 1) + " :");
player[x] = playerStr;
} //end of for loop
die1 = new Die();
die2 = new Die();
die3 = new Die();
die4 = new Die();
die5 = new Die();
int scoring [][] = new int [num][13];//scoring aray
int[] numDie = new int[maxDie];
String[][] usedCategory = new String [num][times];
for (x=0; x < 13; x++)
for (y = 0; y < num; y++)
usedCategory[y][x] = " ";
for (int choices = 0; choices < times; choices++)
//player turns for loop.
for (x = 0; x < num; x++)
//rolls the die;
for (y = 0; y < maxDie; y++)
numDie[y] = die1.roll();
numStr = JOptionPane.showInputDialog (player[x] + "\n~~~~~~~~~~~~~~~~~~~~~~~"
+ "\nDie1: " + numDie[0]
+ "\nDie2: " + numDie[1]
+ "\nDie3: " + numDie[2]
+ "\nDie4: " + numDie[3]
+ "\nDie5: " + numDie[4]
+ "\nWhich dice do you want to reroll");
reroll = numStr.length();
if (reroll == 0)
t = maxRoll;
else{
//reroll
for(t = 0; t < maxRoll; t++ )
for (y = 0; y < reroll; y++)
rerolling = numStr.charAt(y);
//create another mwthod later.
switch (rerolling)
case '1':
numDie[0] = die1.roll();
break;
case '2':
numDie[1] = die1.roll();
break;
case '3':
numDie[2] = die1.roll();
break;
case '4':
numDie[3] = die1.roll();
break;
case '5':
numDie[4] = die1.roll();
break;
default:
t = maxRoll;//to be changed
} //end of switch class
}//end of reroll for loop
JOptionPane.showMessegeDialog (player[x] + "\n~~~~~~~~~~~~~~~~~~~~~~~"
+ "\nDie1: " + numDie[0]
+ "\nDie2: " + numDie[1]
+ "\nDie3: " + numDie[2]
+ "\nDie4: " + numDie[3]
+ "\nDie5: " + numDie[4]
+ "\nWhich dice do you want to reroll"
switch (rerolling)
case '1':
numDie[0] = die1.roll();
break;
case '2':
numDie[1] = die1.roll();
break;
case '3':
numDie[2] = die1.roll();
break;
case '4':
numDie[3] = die1.roll();
break;
case '5':
numDie[4] = die1.roll();
break;
default:
t = maxRoll; //not really anything yet, or is it?
} //end of rerolling switch class
//categorychoice = Integer.parseInt(category);
}//end of t for loop
}//end of player for loop.samuraiexe wrote:
well, i should have said it is a yahtzee program, and i ask the user what they want to reroll and whatever number they press, the switch will activate the case and the array that it will reroll.
HOw would i pass it as an argument?You put it in the argument list. Modifying your original code a bit:
public static void switchReroll (int[] dice, int position) {
switch (position) {
case '1':
dice[0] = die1.roll()
break;
case '2':
dice[1] = die1.roll();
break;
case '3':
dice[2] = die1.roll();
break;
case '4':
dice[3] = die1.roll();
break;
case '5':
dice[4] = die1.roll();
break;
default:
t = maxRoll;//to be changed
} //end of switch
}which you could then call as this:
switchReroll(numDie, reroll);Note that your code still isn't done; the above won't compile. This is just an example of how you could pass the stuff as an argument (and note how the values have different names in the main method than in the switchReroll method -- this works, but also note that it's the same array of ints in both).
By the way -- you really don't need a switch statement for this. You can do the same thing with a couple lines of code, which would lessen the advantage for a separate method. But I'd suggest continuing down this path, and then you could change the implementation of the method later. -
I have a code that asks for integer input and outputs the sum of the integer.
import java.util.Scanner;
public class Assignment3a {
public static void main (String[]args){
Scanner input = new Scanner (System.in);
//declaration
int i, n, mod=0, sum = 0;
//get user input for 'How many inputs'
System.out.print ("How many numbers in input? ");
i = input.nextInt();
//number of itterations
for (int entry=1; entry <= i; entry++){
System.out.print ("Enter a positive integer: ");
n = input.nextInt();
while (n < 0){//If number is negative
System.out.print ("ERROR! Should be positive. Enter a positive integer: ");
n=input.nextInt();
while(n>0){//sum of integers
mod= n % 10;
sum= mod + sum;
n = n / 10;}
System.out.println ("The sum of digits is " + sum + ".");
mod = 0;//reset integers
sum = 0;
}What I need is to use a method which does the sum of digit part. Here is a vague idea, of what I think it would be. Obviously, there are several error. Would someone show me the right way?
import java.util.Scanner;
public class test {
public static void main (String[]args){
Scanner input = new Scanner (System.in);
//declaration
int i, n, mod=0, sum = 0;
//get user input for 'How many inputs'
System.out.print ("How many numbers in input? ");
i = input.nextInt();
//number of itterations
for (int entry=1; entry <= i; entry++){
System.out.print ("Enter a positive integer: ");
n = input.nextInt();
if (n < 0){//If number is negative
System.out.print ("ERROR! Should be positive. Enter a positive integer: ");
n=input.nextInt();
else{//sum of integers
displaySum(n,mod,sum);
System.out.println (sum);
public static void displaySum(int n, int mod, int sum){
mod= n % 10;
sum= mod + sum;
n = n / 10;
}Edited by: acastelino2001 on Apr 22, 2010 2:27 PMacastelino2001 wrote:
I think you misunderstood me or may be I wasn't clear enough. the program should call a method (in this case displaySum) to solve the sum. The issue I'm having is, that I don't fully understand how methods work...Then it seems to me that you need to read the tutorials; otherwise anything we give you, while it might do the job, won't be your own work.
However, a method is essentially a named function which does a specific piece of work. It takes input in the form of parameters and hands back a result, in the form of a return value; however neither are absolute requirements (a method can have no parameters, and can define a return type of 'void', which indicates that it does not return a value).
The real craft of programming is to set up methods that break down the problem you've been assigned into single tasks, and for that reason I agree completely with flounder that calculateSum() is the first thing you should look at. Once you've got that working, you can then use its result to create a displaySum() method that prints it out.
Winston -
Trying to access methods from a .class file by creating instance of class
Hey all,
I'm hoping you can help. I've been given a file "Input.class" with methods such as readInt(), readString(), etc. I have tried creating instances of this class to make use of it, but I receive the error "cannot find symbol : class Input".
If you could help at all, I would greatly appreciate it.
Here's my code. The first is the base program, the second is the driver.
import java.util.*;
public class CarObject
private String makeType = "";
private String modelType = "";
private int yearOfRelease = 0;
private double numOfMiles = 0.0;
public void setFilmTitle(String make)
makeType = make;
public void setMediaType(String model)
modelType = model;
public void setYearOfRelease(int year)
yearOfRelease = year;
public void setNumOfMiles(double miles)
numOfMiles = miles;
public String getMakeType()
return makeType;
public String getModelType()
return modelType;
public int getYearOfRelease()
return yearOfRelease;
public double getNumOfMiles()
return numOfMiles;
The program is used by a rental car company and the object takes on desired attributes.
import java.util.*;
public class TestCarObject
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args)
System.out.println("Please answer the following questions regarding your rental car order.");
Input carinput = new Input();
String makeType = carinput.readString("Enter your desired make of car: ");
String modelType = carinput.readString("Enter your desired model of car: ");
int yearOfRelease = carinput.readInt("Enter the oldest acceptable year of release to rent: ");
double numOfMiles = carinput.readDouble("Enter the highest acceptable number of miles: ");
System.out.println("Make: " + makeType);
System.out.println("Model: " + makeType);
System.out.println("Year: " + makeType);
System.out.println("Mileage: " + makeType);
}No, I don't know the package name....Is there a way
to import the Input.class by itself without importing
the entire packge?
I tried extending the driver program too...It didn't
work either...
Message was edited by:
BoxMan56How do you know you have a class called Input.class ?
You got a jar file which contains it ? or just a simple .class file ?
You have to set the classpath in either case.
But for the former, you should also need to explicitly telling which package containing the class file you looking for (i.e. Input.class)
e.g. java.util.Vector which is a class called Vector inside java.util package.
You don't have to import the whole package, but you should tell which package this class belongs to. -
Cannot resolve symbol error while trying to define methods in a class
Well, I'm fairly new to java and I'm trying to write a simple program that will take user input for up to 100 die and how many sides they have and will then roll them and output the frequencies of numbers occuring. I have overloaded the constructor for the Die class to reflect different choices the user may have when initializing the Die.
Here is my code:import java.util.*;
import java.io.*;
public class Die
private final int MIN_FACES = 4;
private int numFaces;
private int i = 0;
private int faceValue;
private Die currentDie;
private BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
private String line = null;
public Die()
numFaces = 6;
faceValue = 1;
public Die (int faces)
if (faces < MIN_FACES) {
numFaces = 6;
System.out.println ("Minimum number of faces allowed is 6.");
System.out.println ("Setting faces to 6... . . . . . . . . .");
else
numFaces = faces;
faceValue = 1;
//Returns an array of Die Objects
public Die (int num_die, int faces)
numFaces = faces;
Die[] protoDie = new Die[num_die];
for (i = 0; i <= num_die-1; i++)
Die currentDie = new Die(numFaces);
protoDie = protoDie.initMultiDie(currentDie, i);
public Die (double num_die)
int numberOfDie = (int) num_die;
Die[] protoDie = new Die[numberOfDie];
System.out.print ("Enter the number of sides for die #" + i);
for (i=0; i <= protoDie.length; i++) {
do {
try {
line = br.readLine();
numFaces = Integer.parseInt(line);
catch (NumberFormatException nfe) {
System.out.println ("You must enter an integer.");
System.out.print ("Setting number of dice to 0, please reenter: ");
if (numFaces < 0) {
System.out.println ("The number of sides must be positive.");
numFaces *= -1;
System.out.println ("Number of sides is: " + numFaces);
else
if (numFaces = 0) {
System.out.println ("Zero dice is no fun. =[");
System.out.print ("Please reenter the number of sides: ");
numFaces = 0;
while (numFaces == 0);
Die currentDie = new Die(numFaces);
protoDie[i] = protoDie.initMultiDie(currentDie, i);
i = 0;
public Die[] initMultiDie (Die[] protoDie, Die currentDie, int i)
protoDie[i] = currentDie;
return protoDie;
public Die reInit (int sides)
currentDie.roll();
return currentDie;
public int roll()
faceValue = (int) (Math.random() * numFaces) + 1;
return faceValue;
}When I compile I get 2 errors at lines 42 and 73 saying:
Cannot resolve symbol | symbol: method initMultiDie(Die, int) | location: class Die[] | protoDie[i] = protoDie.initMultiDie(currentDie, i)
I've tried mixing things up with invoking the method, such as including protoDie in the parameter liist, instead of invoking the initMultiDie method thru the protoDie Die[] object. I'm a little confused as to what I can and cannot do with defining arrays of Objects like Die. Thank you for any input you may be able to provide.
~LijeI may as well just replace Die with Dice and allow
Dice to represent a collection of 1 die.. I just like
to cut on bloat and make my programs be as efficient
as possible.Efficiency and avoiding code bloat are good goals, but you don't necessarily achieve it by creating the smallest number of classes. If you have N algorithms in M lines, then you have that many, regardless of whether they're in one class or two. A really long source file can be a worse example of bloat than two source files of half the size -- it can be harder to read, less clear in the design, and thus with more bugs...
The important thing is clarity and a strong design.
The weird thing is, that initMultiDie is
what seems to be throwing up the error, but I don't
see why. Meh, I'm sure I'll figure it out.Refactoring a class to make the design more transparent often helps you figure out bugs. -
Calling arraylist from another class - help please!!
Hey, I need some help calling my arraylist from my GUI class, as the arraylist is in the 'AlbumList' class and not in the 'GUI' class i get the error 'cannot find symbol', which is pretty obvious but i cannot figure how to get around this problem. help would be greatly appreciated.
i have written ***PROBLEM*** next to the bad line of code!
Thanks!!
public class Album
String artist;
String title;
String genre;
public Album(String a, String t, String g)
artist = a;
title = t;
genre = g;
public String getArtist()
return artist;
public String getTitle()
return title;
public String getGenre()
return genre;
public class AlbumList
public ArrayList <Album> theAlbums;
int pointer = -1;
public AlbumList()
theAlbums = new ArrayList <Album>();
public void addAlbum(Album newAlbum)
theAlbums.add(newAlbum);
import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GUI extends JFrame
public int max = 5;
public int numAlbums = 4;
public int pointer = -1;
public GUI ()
super("Recording System");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel main = new JPanel();
JPanel panel1 = new JPanel();
panel1.setLayout(new GridLayout(3,2,0,0));
JPanel panel2 = new JPanel();
panel2.setLayout(new GridLayout(1,2,20,0));
final JLabel artistLBL = new JLabel("Artist: ");
final JLabel titleLBL = new JLabel("Title: ");
final JLabel genreLBL = new JLabel("Genre: ");
final JTextField artistFLD = new JTextField(20);
final JTextField titleFLD = new JTextField(20);
final JTextField genreFLD = new JTextField(20);
final JButton nextBTN = new JButton("Next");
nextBTN.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e)
pointer++;
artistFLD.setText(theAlbums.get(pointer).getArtist()); ***PROBLEM***
titleFLD.setText("NEXT");
genreFLD.setText("NEXT");
final JButton prevBTN = new JButton("Prev");
prevBTN.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e)
pointer--;
artistFLD.setText("PREVIOUS");
titleFLD.setText("PREVIOUS");
genreFLD.setText("PREVIOUS");
panel1.add(artistLBL);
panel1.add(artistFLD);
panel1.add(titleLBL);
panel1.add(titleFLD);
panel1.add(genreLBL);
panel1.add(genreFLD);
panel2.add(prevBTN);
panel2.add(nextBTN);
main.add(panel1);
main.add(panel2);
setVisible(true);
this.getContentPane().add(main);
setSize(500, 500);
-----------------------------------------------------------------------Thanks!!
Edited by: phreeck on Nov 3, 2007 8:55 PMthanks, it dosnt give me a complication error but when i press the button it says out of bounds error, and i think my arraylist may be empty possibly even though i put this data in.. this is my test file which runs it all.
any ideas? thanks!!
public class Test
public static void main(String []args)
AlbumList a = new AlbumList();
String aArtist = "IronMaiden";
String aTitle = "7thSon";
String aGenre = "HeavyMetal";
Album newA = new Album(aArtist, aTitle, aGenre);
a.addAlbum(newA);
aArtist = "LambOfGod";
aTitle = "Sacrament";
aGenre = "Metal";
Album newB = new Album(aArtist, aTitle, aGenre);
a.addAlbum(newB);
aArtist = "JohnMayer";
aTitle = "Continuum";
aGenre = "Guitar";
Album newC = new Album(aArtist, aTitle, aGenre);
a.addAlbum(newC);
aArtist = "StillRemains";
aTitle = "TheSerpent";
aGenre = "Metal";
Album newD = new Album(aArtist, aTitle, aGenre);
a.addAlbum(newD);
GUI tester = new GUI();
} -
Hi,
I'm trying to follow some Java code but I don't understand the syntax being used. If you define a class and then define a method within that class, is it automatically run? I'm attaching some sample code. I don't understand how public void map (line 18) is ever called or run, yet it is.
1. package org.myorg;
2.
3. import java.io.IOException;
4. import java.util.*;
5.
6. import org.apache.hadoop.fs.Path;
7. import org.apache.hadoop.conf.*;
8. import org.apache.hadoop.io.*;
9. import org.apache.hadoop.mapred.*;
10. import org.apache.hadoop.util.*;
11.
12. public class WordCount {
13.
14. public static class Map extends MapReduceBase implements Mapper<LongWritable, Text, Text, IntWritable> {
15. private final static IntWritable one = new IntWritable(1);
16. private Text word = new Text();
17.
18. public void map(LongWritable key, Text value, OutputCollector<Text, IntWritable> output, Reporter reporter) throws IOException {
19. String line = value.toString();
20. StringTokenizer tokenizer = new StringTokenizer(line);
21. while (tokenizer.hasMoreTokens()) {
22. word.set(tokenizer.nextToken());
23. output.collect(word, one);
24. }
25. }
26. }
27.
28. public static class Reduce extends MapReduceBase implements Reducer<Text, IntWritable, Text, IntWritable> {
29. public void reduce(Text key, Iterator<IntWritable> values, OutputCollector<Text, IntWritable> output, Reporter reporter) throws IOException {
30. int sum = 0;
31. while (values.hasNext()) {
32. sum += values.next().get();
33. }
34. output.collect(key, new IntWritable(sum));
35. }
36. }
37.
38. public static void main(String[] args) throws Exception {
39. JobConf conf = new JobConf(WordCount.class);
40. conf.setJobName("wordcount");
41.
42. conf.setOutputKeyClass(Text.class);
43. conf.setOutputValueClass(IntWritable.class);
44.
45. conf.setMapperClass(Map.class);
46. conf.setCombinerClass(Reduce.class);
47. conf.setReducerClass(Reduce.class);
48.
49. conf.setInputFormat(TextInputFormat.class);
50. conf.setOutputFormat(TextOutputFormat.class);
51.
52. FileInputFormat.setInputPaths(conf, new Path(args[0]));
53. FileOutputFormat.setOutputPath(conf, new Path(args[1]));
54.
55. JobClient.runJob(conf);
57. }
58. }If you define a class and then define a method within that class, is it automatically run?No.
However, if you start the JVM from the command line, the main() method is invoked. In the main() method of your class, you pass the WordCount class to the JobConf constructor then use something called JobClient to call runJob on that JobConf, so presumably map() is invoked indirectly that way. -
Print methods of a class at run-time
Suppose I have a class. At run-time I get an object of that class. I want to print methods defined in that object using System.out.println(). How can I do that?
ThanksTake a look at Object.getClass(). It returns a Class object. Then look at the methods within the Class class that you can invoke. Some of them return arrays of Method objects, for instance.
Learn to read the API and experiment with the available methods you already have (such as getClass(), available for every object).
http://java.sun.com/j2se/1.4.2/docs/api/index.html -
Trying to understand, being prompted the file compression rules on saving, or not
Hello,
I'm trying to understand something, could I ask for your help, please ?
After working on a jpg file, when I want to save it, still as jpg, with my Photoshop CS5,
- sometimes photoshop will just save the picture, and it's done
- sometimes photoshop will show me the compression dialog, "JPEG Options", in which I can choose the compression ratio, the format options (baseline, baseline optimized, progressive), and have an estimation of the total file size
While not being prompted any dialog is simpler, and I'll then simply assume Photoshop decides to retain the current image's compression and format rules, I must say I like to be in control, and I'd like to know under what form the file is being saved without having to resort to the much more complex "Save For Web" menu.
Please, would you know WHAT "triggers" the appearance of the JPEG Options when we close/save a jpeg file, in photoshop ? What makes this menu not to appear, what makes it appear ?
If there are trivial file operations/changes/filters that necessarily trigger its appearance when we want to save, something like that ? I've tried a variety of these, but I still can't figure it out, sometimes it shows in the end, and sometimes it doesn't.
Thank you very much if you can help me
Kind regards,
Oliver@ c.pfaffenbichler
These are images from various sources, not just one.
I'm deliberately excluding Save For Web, this completely re-processes everything.
My purpose, precisely, is to know when photoshop takes the decision to retain the image's "rules", and when photoshop decides to pose us the question, how do we want it saved.
Simply taking a jpeg image, doing stuff on it, and hitting control-w to close the window, and seeing if it will be an
- «OK, sure, do you want to save ? You clicked OK to confirm you wanted the changes saved ? Good, now it's closed» or a
- «please sir, how would you like your image saved, tell me the compression ratio and the format options, thank you» -
Trying to understand Objective C warning related to factory method
All,
I'm just beginning learning objective C (I am a C++ programmer by day), and I have a question about a warning I am seeing in my code. I found some really simple example code on the web that used the 'new' factory method to create an instance of an object. Here are the three files:
List.h
#import <objc/Object.h>
@interface List : Object // List is a subclass of the superclass Object
int list[100]; // These are instance variables.
int size;
/* Public methods */
- free;
- (int) addEntry: (int) num;
- print;
/* Private methods */
/* Other programs should not use these methods. */
- resetSize;
@end
List.m
#import "List.h"
@implementation List
+ new // factory method
self = [super new];
printf("inside new\n");
[self resetSize];
return self;
- free
return [super free];
- (int) addEntry: (int) num
list[size++] = num;
return size;
- print
int i;
printf("\n");
for (i = 0; i < size; ++i)
printf ("%i ", list);
return self; // Always return self
// if nothing else makes sense.
- resetSize
printf("Inside resetSize\n");
size = 0;
return self;
@end
main.m
#import <objc/Object.h>
#import "List.h" // Note the new commenting style.
main()
id list; // id is a new data type for objects.
list = [List new]; // create an instance of class List.
[list resetSize];
[list addEntry: 5]; // send a message to the object list
[list print];
[list addEntry: 6];
[list addEntry: 3];
[list print];
printf("\n");
[list free]; // get rid of object
Now, I know that the 'best' way to allocate and initialize an object is through [[List alloc] init], but I'm seeing a strange warning when I compile List.m, and I just want to understand why it's showing up. Here's the warning.
List.m: In function ‘+[List new]’:
List.m:9: warning: ‘List’ may not respond to ‘+resetSize’
List.m:9: warning: (Messages without a matching method signature
List.m:9: warning: will be assumed to return ‘id’ and accept
List.m:9: warning: ‘...’ as arguments.)
It looks like something is assuming that resetSize is a factory method rather than an instance method. The strange thing, though, is that the program works exactly like expected. resetSize is actually called from within the new method correctly.
Any ideas why I'm seeing the error, and how I should get rid of it?
Thanks,
EricThanks for clearing that up for me - it makes sense now. And sorry about the formatting problems - I guess forgetting the {code} tags make a pretty big difference
It's taking a little bit for my mind to switch from C++ syntax to Objective C, but I'm able to visualize the problem and the reason the code I found produced the error.
Thanks again,
Eric -
Trying to understand Static methods
Hi all,
I am trying to learn a little bit about static methods and hope that someone here can help me understand it better. My understanding of static methods is that they exist only once (More like global methods). This tells me that usage of static methods should be used with care as they are likely to cause problems in cases where multiple users try to access a static object at the same time.
I am looking at a piece of code that had me thinking for a bit. I cant post the code itself but here is an example of how the code is structured
The first class declares a couple of non static arrays and makes them available via the getters and setters. It also has one method that calls a static method in another class.
package com.tests.statictest;
import java.util.ArrayList;
public class ClassA{
ArrayList arrayList1 = new ArrayList();
ArrayList arrayList2 = new ArrayList();
public ClassA(){
arrayList1.add("TEST1");
arrayList1.add("TEST2");
arrayList2.add("Test3");
arrayList2.add("Test4");
ArrayList getArrayList1(){
return arrayList1;
ArrayList getArrayList2(){
return arrayList2;
ArrayList getJoinedArrayList(){
return ClassB.joinArrays(arrayList1,arrayList2);
}The second class contains the static method that is called by the above class to join the two arrays. This class is used by many other classes
package com.tests.statictest;
import java.util.ArrayList;
public class ClassB{
public static ArrayList joinArrays(ArrayList list1, ArrayList list2){
ArrayList list3 = new ArrayList();
list1.addAll(list2);
return list1;
}And here is my test class
package com.tests.statictest;
public class ClassC{
public static void main(String args[]){
ClassA classA = new ClassA();
System.out.println(classA.getArrayList1());
System.out.println(classA.getArrayList2());
System.out.println(classA.getJoinedArrayList());
}The output to the above program is shown below
[TEST1, TEST2]
[Test3, Test4]
[TEST1, TEST2, Test3, Test4]My question for the above is that i am wondering if the above is safe. Can you think of situations where the above is not recommended. What exactly would happen if ten instances of ClassA threads are executed at the same time? Woulnt the static method in ClassB corrupt the data?ziggy wrote:
Hi all,
I am trying to learn a little bit about static methods and hope that someone here can help me understand it better. My understanding of static methods is that they exist only once (More like global methods). This tells me that usage of static methods should be used with care as they are likely to cause problems in cases where multiple users try to access a static object at the same time. There is no such thing as a "static object" in Java. The word "static" simply means "belonging to a class as a whole, rather than an individual instance."
My question for the above is that i am wondering if the above is safe. Can you think of situations where the above is not recommended. What exactly would happen if ten instances of ClassA threads are executed at the same time?ClassA isn't a thread, so it can't be "executed", per se.
Woulnt the static method in ClassB corrupt the data?"Staticness" doesn't have anything to do with it; the issue at hand is operations on a shared data structure, which is a concern whether you're dealing with static or non-static members. There is nothing inherent in ClassB that will "corrupt" anything, however.
~ -
Strange error of CALL FUNCTION within Method
Hi all,
i'm facing a very strange problem. Some Function Modules can't be called from within a method and a dump appears with the following message CALL_FUNCTION_CONFLICT_LENG (CX_SY_DYN_CALL_ILLEGAL_TYPE).
Here's an example: I've created a normal class with only one static method.
Class: ZCL_TEST
Method: CHECK_EMPLOYEE
Importing Parameter: IV_PERNR TYPE PERNR_D
Coding:
DATA gt_return TYPE TABLE OF bapireturn1.
CALL FUNCTION 'BAPI_EMPLOYEET_ENQUEUE'
EXPORTING
number = iv_pernr
validitybegin = sy-datum
IMPORTING
return = gt_return.
CALL FUNCTION 'BAPI_EMPLOYEET_DEQUEUE'
EXPORTING
number = iv_pernr
validitybegin = sy-datum.
If i call this method a dump appears and if the same code of that method is implemented directly in a normal report everything works fine.
Why can't i call this function module from within a method?
Regards
Mark-AndréHi,
the dump even appears by testing the method from Class Builder with F8!
In my test report iv_pernr isn't declared as follows:
REPORT z_test.
PARAMETERS p_pernr TYPE pernr_d.
zcl_test=>check_employee( p_pernr ).
The reason of the dump is parameter RETURN. But i don't understand it why it only doesn't work from within a method.
Dump Message:
In the function module interface, you can specify only
fields of a specific type and length under "RETURN".
Although the currently specified field
"GT_RETURN" is the correct type, its length is incorrect.
Regards
Mark-André -
Class.this.method overriding inheritance trying to understand
Hi I saw a piece of code that calls MyClass.this.aFunctionOverriddenByMeThatIsInMySuperClass ()
Im just looking for some clarity on how this works what function this actually calls and why someone would write code in this manner.
I have created a simpler version below
2 class A and B and there basic functionality is described in each
class A {
public A (){};
public int func1 () { return 1; }
class B extends A {
public B (){};
public int func1() { return 0; } //note this returns 0 where A.func1 = 1
public int myFunc() { return B.this.func1(); }
//public int myOtherFunc() { return A.this.func1(); } //NOT LEGAL wont compile
B.java:5: not an enclosing class: A //pardon the stupidity but what is an enclosing class??
public int myOtherFunc() { return A.this.func1(); }
class D extends B {
public D (){};
public int func1(){ return 4; }
class C
public static void main (String [] args)
A a = new A();
B b = new B();
D d = new D();
System.out.println(a.func1()); //prints 1
System.out.println(b.func1()); //prints 0
System.out.println(b.myFunc()); //prints 0
System.out.println(d.myFunc()); //prints 4
I guess my assumption is that using MyClass.this.someOverriddenFunction allows the subclass to have more control ??
any thought or comment would be much appreciated.
thanksDo you know what inner classes are? Inner classes are classes that are defined within another class. If an inner class is not declared as static, it needs an instance of the class it is defined within to exist, this is the enclosing class. MyClass.this can be used so that the inner class can explicitly invoke methods on it's enclosing instance
-
Is it possible to call methods from another class from within an abstract c
Is it possible to call methods from another class from within an abstract class ?
I found an example in teh JDK 131 JFC that may help you. I t is using swing interface and JTable
If you can not use Swing, then you may want to do digging or try out with the idea presented here in example 3
Notice that one should refine the abstract table model and you may want to create a method for something like
public Object getValuesAtRow(int row) { return data[row;}
to give the desired row and leave the method for
getValuesAt alone for getting valued of particaular row and column.
So Once you got the seelcted row index, idxSelctd, from your table
you can get the row or set the row in your table model
public TableExample3() {
JFrame frame = new JFrame("Table");
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {System.exit(0);}});
// Take the dummy data from SwingSet.
final String[] names = {"First Name", "Last Name", "Favorite Color",
"Favorite Number", "Vegetarian"};
final Object[][] data = {
{"Mark", "Andrews", "Red", new Integer(2), new Boolean(true)},
{"Tom", "Ball", "Blue", new Integer(99), new Boolean(false)},
{"Alan", "Chung", "Green", new Integer(838), new Boolean(false)},
{"Jeff", "Dinkins", "Turquois", new Integer(8), new Boolean(true)},
{"Amy", "Fowler", "Yellow", new Integer(3), new Boolean(false)},
{"Brian", "Gerhold", "Green", new Integer(0), new Boolean(false)},
{"James", "Gosling", "Pink", new Integer(21), new Boolean(false)},
{"David", "Karlton", "Red", new Integer(1), new Boolean(false)},
{"Dave", "Kloba", "Yellow", new Integer(14), new Boolean(false)},
{"Peter", "Korn", "Purple", new Integer(12), new Boolean(false)},
{"Phil", "Milne", "Purple", new Integer(3), new Boolean(false)},
{"Dave", "Moore", "Green", new Integer(88), new Boolean(false)},
{"Hans", "Muller", "Maroon", new Integer(5), new Boolean(false)},
{"Rick", "Levenson", "Blue", new Integer(2), new Boolean(false)},
{"Tim", "Prinzing", "Blue", new Integer(22), new Boolean(false)},
{"Chester", "Rose", "Black", new Integer(0), new Boolean(false)},
{"Ray", "Ryan", "Gray", new Integer(77), new Boolean(false)},
{"Georges", "Saab", "Red", new Integer(4), new Boolean(false)},
{"Willie", "Walker", "Phthalo Blue", new Integer(4), new Boolean(false)},
{"Kathy", "Walrath", "Blue", new Integer(8), new Boolean(false)},
{"Arnaud", "Weber", "Green", new Integer(44), new Boolean(false)}
// Create a model of the data.
TableModel dataModel = new AbstractTableModel() {
// These methods always need to be implemented.
public int getColumnCount() { return names.length; }
public int getRowCount() { return data.length;}
public Object getValueAt(int row, int col) {return data[row][col];}
// The default implementations of these methods in
// AbstractTableModel would work, but we can refine them.
public String getColumnName(int column) {return names[column];}
public Class getColumnClass(int col) {return getValueAt(0,col).getClass();}
public boolean isCellEditable(int row, int col) {return (col==4);}
public void setValueAt(Object aValue, int row, int column) {
data[row][column] = aValue;
};
Maybe you are looking for
-
Unable to launch Itunes STORE post upgrade to 10.4.1.10
Since the upgrade I can not load the STORE. Itunes automated! customer service advisers do not seem to know either. I have been told to REMOVE Itunes/Quicktime and reload - done - Store worked First time, then the next time it failed! just a slow lo
-
I have a TMDS file but every time I try to open it it gives me the error 2500. I tried to solve it with TDMS Defragment.vi, but I don't know if I'm using it correctly or if it doesn't work.
-
Use of Edge Composition in iBooks Author, a question
Hi folks! I'm using with great pleasure Adobe Edge Animate 1.0 to make Html Widgets for Apple iBooks Author! In a composition, I've defined this variable: var track1 = new Audio(); track1.src = "media/track1.m4a"; track1.volume = 0.5
-
The new tab button is now surrounded by a large gray box after downloading the new version
Rather than seeing just the small rounded light gray button around the "+" sign for a new tab, there is now a larger, dark grey rectangle (larger than the new button itself) over the "+" sign. When I hover, the rounded part of the button appears, but
-
Outer Join with IN comparison condition
Dear all, according to the manual: "a WHERE condition cannot use the IN comparison condition to compare a column marked with the (+) operator with an expression" Suppose I'm running a queries on hr sample schema: SQL> select c.country_name,l.city fro