Abap-OOPS Help with standard class Cl_RSPLFC_COPY
Please help me out in expanding the functionality of an existing class cl_rsplfc_copy .As i want 2 copy some data from one cube 2 an another cube taking some characters common in both the cubes.
Is there any specific reason you want to use exit, when there is a standard copy planning function which does the copy without any customization? Why not use a multiplanning area and copy its simple to implement and maintain.
Similar Messages
-
I need abap oops help docu?
i need abap oops help docu?
Hi Karthikeyan,
Chk this standard Programs.
ABAP_OBJECTS_ENJOY_0 Template for Solutions of ABAP Object Enjoy Course
ABAP_OBJECTS_ENJOY_1 Model Solution 1: ABAP Objects Enjoy Course
ABAP_OBJECTS_ENJOY_2 Model Solution 2: ABAP Objects Enjoy Course
ABAP_OBJECTS_ENJOY_3 Model Solution 3: ABAP Objects Enjoy Course
ABAP_OBJECTS_ENJOY_4 Model Solution 4: ABAP Objects Enjoy Course
ABAP_OBJECTS_ENJOY_5 Model Solution 5: ABAP Objects Enjoy Course
DEMO_ABAP_OBJECTS Complete Demonstration for ABAP Objects
DEMO_ABAP_OBJECTS_CONTROLS GUI Controls on Screen
DEMO_ABAP_OBJECTS_EVENTS Demonstration of Events in ABAP Objects
DEMO_ABAP_OBJECTS_GENERAL ABAP Objects Demonstration
DEMO_ABAP_OBJECTS_INTERFACES Demonstration of Interfaces in ABAP Objects
DEMO_ABAP_OBJECTS_METHODS Demonstration of Methods in ABAP Objects
DEMO_ABAP_OBJECTS_SPLIT_SCREEN Splitter Control on Screen
links for OO ABAP.
http://www.sapgenie.com/abap/OO/
http://www.sapgenie.com/abap/OO/index.htm
http://help.sap.com/saphelp_nw04/helpdata/en/c3/225b5654f411d194a60000e8353423/content.htm
http://www.esnips.com/doc/375fff1b-5a62-444d-8ec1-55508c308b17/prefinalppt.ppt
http://www.esnips.com/doc/2c76dc57-e74a-4539-a20e-29383317e804/OO-abap.pdf
http://www.esnips.com/doc/5c65b0dd-eddf-4512-8e32-ecd26735f0f2/prefinalppt.ppt
http://www.allsaplinks.com/
http://www.sap-img.com/
http://www.sapgenie.com/
http://help.sap.com
http://www.sapgenie.com/abap/OO/
http://www.sapgenie.com.
http://www.sapgenie.com/abap/OO/index.htm
http://www.sapgenie.com/abap/controls/index.htm
http://www.esnips.com/doc/2c76dc57-e74a-4539-a20e-29383317e804/OO-abap.pdf
http://www.esnips.com/doc/0ef39d4b-586a-4637-abbb-e4f69d2d9307/SAP-CONTROLS-WORKSHOP.pdf
http://www.sapgenie.com/abap/OO/index.htm
http://help.sap.com/saphelp_erp2005/helpdata/en/ce/b518b6513611d194a50000e8353423/frameset.htm
http://www.sapgenie.com/abap/OO/
some more materials.
Go through the following Documents Links & Materials for ABAP Objects
check the below links lot of info and examples r there
http://www.sapgenie.com/abap/OO/index.htm
http://www.geocities.com/victorav15/sapr3/abap_ood.html
http://www.brabandt.de/html/abap_oo.html
Check this cool weblog:
/people/thomas.jung3/blog/2004/12/08/abap-persistent-classes-coding-without-sql
/people/thomas.jung3/blog/2004/12/08/abap-persistent-classes-coding-without-sql
/people/sap.user72/blog/2005/05/10/a-small-tip-for-the-beginners-in-oo-abap
/people/ravikumar.allampallam/blog/2005/02/11/abap-oo-in-action
/people/thomas.jung3/blog/2005/09/08/oo-abap-dynpro-programming
http://help.sap.com/saphelp_nw04/helpdata/en/c3/225b6254f411d194a60000e8353423/frameset.htm
http://www.sapgenie.com/abap/OO/
http://www.sapgenie.com/abap/OO/index.htm
http://help.sap.com/saphelp_nw04/helpdata/en/c3/225b5654f411d194a60000e8353423/content.htm
http://www.esnips.com/doc/375fff1b-5a62-444d-8ec1-55508c308b17/prefinalppt.ppt
http://www.esnips.com/doc/2c76dc57-e74a-4539-a20e-29383317e804/OO-abap.pdf
http://www.esnips.com/doc/5c65b0dd-eddf-4512-8e32-ecd26735f0f2/prefinalppt.ppt
http://www.allsaplinks.com/
http://www.sap-img.com/
http://www.sapgenie.com/
http://help.sap.com
http://www.sapgenie.com/abap/OO/
http://www.sapgenie.com/abap/OO/index.htm
http://www.sapgenie.com/abap/controls/index.htm
http://www.esnips.com/doc/2c76dc57-e74a-4539-a20e-29383317e804/OO-abap.pdf
http://www.esnips.com/doc/0ef39d4b-586a-4637-abbb-e4f69d2d9307/SAP-CONTROLS-WORKSHOP.pdf
http://www.sapgenie.com/abap/OO/index.htm
http://help.sap.com/saphelp_erp2005/helpdata/en/ce/b518b6513611d194a50000e8353423/frameset.htm
http://www.sapgenie.com/abap/OO/
these links
http://help.sap.com/saphelp_47x200/helpdata/en/ce/b518b6513611d194a50000e8353423/content.htm
For funtion module to class
http://help.sap.com/saphelp_47x200/helpdata/en/c3/225b5954f411d194a60000e8353423/content.htm
for classes
http://help.sap.com/saphelp_47x200/helpdata/en/c3/225b5c54f411d194a60000e8353423/content.htm
for methods
http://help.sap.com/saphelp_47x200/helpdata/en/08/d27c03b81011d194f60000e8353423/content.htm
for inheritance
http://help.sap.com/saphelp_47x200/helpdata/en/dd/4049c40f4611d3b9380000e8353423/content.htm
for interfaces
http://help.sap.com/saphelp_47x200/helpdata/en/c3/225b6254f411d194a60000e8353423/content.htm
check the below links lot of info and examples r there
http://www.sapgenie.com/abap/OO/index.htm
http://www.geocities.com/victorav15/sapr3/abap_ood.html
http://www.brabandt.de/html/abap_oo.html
Check this cool weblog:
/people/thomas.jung3/blog/2004/12/08/abap-persistent-classes-coding-without-sql
/people/thomas.jung3/blog/2004/12/08/abap-persistent-classes-coding-without-sql
http://help.sap.com/saphelp_nw04/helpdata/en/c3/225b6254f411d194a60000e8353423/frameset.htm
OO ABAP is nothing but a class-method apprach to write ABAP codes and define them : below are few of the informations which will be of help for a newbie :
Types of attributes and the basic concepts :
Public attributes
Private attributes
Instance attributes
Static attributes
Public methods
Private methods
Constructor method
Static constructor
Protected components
Polymorphism
Public attributes
Public attributes are defined in the PUBLIC section and can be viewed and changed from outside the class. There is direct access to public attributes. As a general rule, as few public attributes should be defined as possible.
PUBLIC SECTION.
DATA: Counter type i.
Private attributes
Private attributes are defined in the PRIVATE section. The can only be viewes and changed from within the class. There is no direct access from outside the class.
PRIVATE SECTION.
DATA: name(25) TYPE c,
planetype LIKE saplane-planetyp,
Instance attributes
There exist one instance attribute for each instance of the class, thus they exist seperately for each object. Instance attributes are declared with the DATA keyword.
Static attributes
Static attributes exist only once for each class. The data are the same for all instances of the class, and can be used e.g. for instance counters. Static attributes are defined with the keyword CLASS-DATA.
PRIVATE SECTION.
CLASS-DATA: counter type i,
Public methods
Can called from outside the class
PUBLIC SECTION.
METHODS: set_attributes IMPORTING p_name(25) TYPE c,
p_planetype LIKE saplane-planetyp,
Private methods
Can only be called from inside the class. They are placed in the PRIVATE section of the class.
Constructor method
Implicitly, each class has an instance constructor method with the reserved name constructor and a static constructor method with the reserved name class_constructor.
The instance constructor is executed each time you create an object (instance) with the CREATE OBJECT statement, while the class constructor is executed exactly once before you first access a class.
The constructors are always present. However, to implement a constructor you must declare it explicitly with the METHODS or CLASS-METHODS statements. An instance constructor can have IMPORTING parameters and exceptions. You must pass all non-optional parameters when creating an object. Static constructors have no parameters.
Static constructor
The static constructor is always called CLASS_CONSTRUCTER, and is called autmatically before the clas is first accessed, that is before any of the following actions are executed:
Creating an instance using CREATE_OBJECT
Adressing a static attribute using <classname>-><attrbute>
Calling a ststic attribute using CALL METHOD
Registering a static event handler
Registering an evetm handler method for a static event
The static constructor cannot be called explicitly.
Protected components
When we are talking subclassing and enheritance there is one more component than Public and Private, the Protected component. Protected components can be used by the superclass and all of the subclasses. Note that Subclasses cannot access Private components.
Polymorphism
Polymorphism: When the same method is implemented differently in different classes. This can be done using enheritance, by redefining a method from the superclass in subclasses and implement it differently.
Reward points if helpful.
Regards,
Harini.S -
Help with SMTP class function with authentication
My server is no longer supporting the php mail() functionality. I need to use SMTP class function with authentication in my php code and they suggested this to replace it: http://www.yrhostsupport.com/index.php?/Knowledgebase/Article/View/101/2/smtp-class-functi on-with-authentication-in-php-code
So I tried it, but can't get it to work. This is my test form:
<form method="post" action="forms/sendmail-test2.php" onsubmit="return checkEmail(this);">
<script type="text/javascript" language="JavaScript">
</script>
<fieldset><legend>Info</legend>
<label> Name </label>
<input type="text"
name="name" size="30" maxlength="40"/><br />
<label> <span class="redText">*</span> Email </label>
<input name="email" type="text" size="30" maxlength="40"/>
<br />
<label><span class="redText">*</span> Message </label>
<textarea cols="40" rows="5" name="message" type="text" /></textarea><br />
</fieldset>
<input type="reset" value="Reset" />
<input type=submit value="Submit Form" />
</fieldset>
</form>
This is sendmail-test2.php where the form goes. It won't send unless I comment out the first 10 lines.
<?php
include('Mail.php');
//$to = "[email protected]";
//$name = $_REQUEST['name'] ;
//$email = $_REQUEST['email'] ;
//$message = $_REQUEST['name'] ;
//$headers = "From: $email";
//$subject = " price quote";
//$fields = array();
//$fields{"name"} = "Name";
//$fields{"email"} = "Email";
//$fields{"message"} = "Message";
$recipients = '[email protected]'; //CHANGE
$headers['From'] = '[email protected]'; //CHANGE
$headers['To'] = '[email protected]'; //CHANGE
$headers['Subject'] = 'Test message';
$body = 'Test message';
// Define SMTP Parameters
$params['host'] = 'levy.dnsbox25.com';
$params['port'] = '25';
$params['auth'] = 'PLAIN';
$params['username'] = '[email protected]'; //CHANGE
$params['password'] = 'xxxxxx'; //CHANGE
/* The following option enables SMTP debugging and will print the SMTP
conversation to the page, it will only help with authentication issues. */
$params['debug'] = 'true';
// Create the mail object using the Mail::factory method
$mail_object =& Mail::factory('smtp', $params);
// Print the parameters you are using to the page
foreach ($params as $p){
echo "$p<br />";
// Send the message
$mail_object->send($recipients, $headers, $body);
?>
It used to work fine when I used
$send = mail($to, $subject, $body, $headers);
$send2 = mail($from, $subject2, $autoreply, $headers2);
But they said I can't use it any more. I'm good with HTML and CSS but I don't know much about php. Thanks for any help integrating a from into this new code!Thanks, bregent. I changed it to this and it sends, but nothing shows up in the body except "Test message". How would I "insert the form fields' 'email' and 'name' and 'message' in the body"?
<?php
include('Mail.php');
$to = "[email protected]";
$name = $_REQUEST['name'] ;
$email = $_REQUEST['email'] ;
$message = $_REQUEST['name'] ;
//$headers = "From: $email";
$subject = " price quote";
$fields = array();
$fields{"name"} = "Name";
$fields{"email"} = "Email";
$fields{"message"} = "Message";
$recipients = '[email protected]'; //CHANGE
$headers['From'] = '[email protected]'; //CHANGE
$headers['To'] = '[email protected]'; //CHANGE
$headers['Subject'] = 'Test message';
$body = 'Test message';
$fields = array();
$fields{"name"} = "Name";
$fields{"email"} = "Email";
$fields{"message"} = "Message";
// Define SMTP Parameters
$params['host'] = 'levy.dnsbox25.com';
$params['port'] = '25';
$params['auth'] = 'PLAIN';
$params['username'] = '[email protected]'; //CHANGE
$params['password'] = xxx'; //CHANGE
/* The following option enables SMTP debugging and will print the SMTP
conversation to the page, it will only help with authentication issues. */
$params['debug'] = 'true';
// Create the mail object using the Mail::factory method
$mail_object =& Mail::factory('smtp', $params);
// Print the parameters you are using to the page
foreach ($params as $p){
echo "$p<br />";
// Send the message
$mail_object->send($recipients, $headers, $body);
?> -
Please help with simple Classes understanding
Working further to understand Class formation, and basics.
At the Java Threads Tutorial site:
http://java.sun.com/docs/books/tutorial/essential/threads/timer.html
Goal:
1)To take the following code, and make it into 2 seperate files.
Reminder.java
RemindTask.java
2)Error Free
Here is the original, functioning code:
import java.util.Timer;
import java.util.TimerTask;
* Simple demo that uses java.util.Timer to schedule a task
* to execute once 5 seconds have passed.
* http://java.sun.com/docs/books/tutorial/essential/threads/timer.html
public class Reminder {
Timer timer;
public Reminder(int seconds) {
timer = new Timer();
timer.schedule(new RemindTask(), seconds*1000);
class RemindTask extends TimerTask {
public void run() {
System.out.println("Time's up!");
timer.cancel(); //Terminate the timer thread
public static void main(String args[]) {
new Reminder(5);
System.out.println("Task scheduled.");
}Here is what I tried to 2 so far, seperate into 2 seperate files:
Reminder.java
package threadspack; //added this
import java.util.Timer;
import java.util.TimerTask;
* Simple demo that uses java.util.Timer to schedule a task
* to execute once 5 seconds have passed.
* http://java.sun.com/docs/books/tutorial/essential/threads/timer.html
public class Reminder {
Timer timer;
public Reminder(int seconds) {
timer = new Timer();
timer.schedule(new RemindTask(), seconds*1000);
public static void main(String args[]) {
new Reminder(5);
System.out.println("Task scheduled.");
}and into
RemindTask.java
package threadspack; //added this
import java.util.Timer;
import java.util.TimerTask;
import threadspack.Reminder; //added this
* http://java.sun.com/docs/books/tutorial/essential/threads/timer.html
public class RemindTask extends TimerTask
Timer timer; /**here, I added this, because got a
"cannot resolve symbol" error if try to compile w/out it
but I thought using packages would have negated the need to do this....?*/
public void run() {
System.out.println("Time's up!");
timer.cancel(); //Terminate the timer thread
}After executing Reminder, the program does perform, even does the timing, however, a NullPointerException error is thrown in the RemindTask class because of this line:
timer.cancel(); //Terminate the timer thread
I am not sure of:
If I have packages/import statements setup correctly
If I have the "Timer" variable setup incorrectly/wrong spot.
...how to fix the problem(s)
Thank you!Hi there!
I understand that somehow the original "Timer" must
be referenced.
This is a major point of confusion for me....I
thought that when importing
Classes from the same package/other packages, you
would have directly
access to the variables within the imported Classes.I think you have one of the basic points of confussion. You are mixing up the concept of a "Class" with the concept of an "Object".
Now, first of all, you do not need packages at all for what you are trying to do, so my advice is you completely forget about packages for the moment, they will only mess you up more. Simply place both .class files (compiled .java files) in the same directory. Your program is executing fine, so that indicates that the directory in which you have your main class file is being included in your classpath, so the JVM will find any class file you place there.
As for Classes/Objects, think of the Class as the map in which the structure of a building is designed, and think of the Object as the building itself. Using the same technical map the architect defines, you could build as many buildings as you wanted. They could each have different colors, different types of doors, different window decorations, etc... but they would all have the same basic structure: the one defined in the technical map. So, the technical map is the Class, and each of the buildings is an object. In Java terminology, you would say that each of the buildings is an "Instance" of the Class.
Lets take a simpler example with a class representing icecreams. Imagine you code the following class:
public class Icecream{
String flavor;
boolean hasChocoChips;
}Ok, with this code, what you're doing is defining the "structure" of an icecream. You can see that we have two variables in our class: a String variable with the description of the icecream's flavor, and a boolean variable indicating whether or not the icecream has chocolate chips. However, with that code you are not actually CREATING those variables (that is, allocating memory space for that data). All you are doing is saying that EACH icecream which is created will have those two variables. As I mentioned before, in Java terminology, creating an icecream would be instantiating an Icrecream object from the Icecream class.
Ok, so lets make icrecream!!!
Ummm... Why would we want to make several icecreams? Well, lets assume we have an icecream store:
public class IcecreamStore{
}Now, we want to sell icecreams, so lets put icecreams in our icecream store:
public class IcecreamStore{
Icecream strawberryIcecream = new Icecream(); //This is an object, it's an instance of Class Icecream
Icecream lemonIcecream = new Icecream(); //This is another object, it's an instance of Class Icecream
}By creating the two Icecream objects you have actually created (allocated memory space) the String and boolean variable for EACH of those icecreams. So you have actually created two String variables and two boolean variables.
And how do we reference variables, objects, etc...?
Well, we're selling icecreams, so lets create an icecream salesman:
public class IcecreamSalesMan{
}Our icecream salesman wants to sell icecreams, so lets give him a store. Lets say that each icecream store can only hold 3 icecreams. We could then define the IcecreamStore class as follows:
public class IcecreamStore{
Icecream icecream1;
Icecream icecream2;
Icecream icecream3;
}Now lets modify our IcecreamSalesMan class to give the guy an icecream store:
public class IcecreamSalesMan{
IcecreamStore store = new IcecreamStore();
}Ok, so now we have within our IcecreamSalesMan class a variable, called "store" which is itself an object (an instance) of the calss IcecreamStore.
Now, as defined above, our IcecreamStore class will have three Icecream objects. Indirectly, our icecream salesman has now three icecreams, since he has an IcecreamStore object which in turn holds three Icecream objects.
On the other hand, our good old salesman wants the three icecreams in his store to be chocolate, strawberry, and orange flavored. And he wants the two first icecreams to have chocolate chips, but not the third one. Well, here's the whole thing in java language:
public class Icecream{ //define the Icecream class
String flavor;
boolean hasChocoChips;
public class IcecreamStore{ //define the IcecreamStore class
//Each icecream store will have three icecreams
Icecream icecream1 = new Icecream(); //Create an Icecream object
Icecream icecream2 = new Icecream(); //Create another Icecream object
Icecream icecream3 = new Icecream(); //Create another Icecream object
public class IcecreamSalesMan{ //this is our main (executable) class
IcecreamStore store; //Our class has a variable which is an IcecreamStore object
public void main(String args[]){
store = new IcecreamStore(); //Create the store object (which itself will have 3 Icecream objects)
/*Put the flavors and chocolate chips:*/
store.icecream1.flavor = "Chocolate"; //Variable "flavor" of variable "icecream1" of variable "store"
store.icecream2.flavor = "Strawberry"; //Variable "flavor" of variable "icecream2" of variable "store"
store.icecream3.flavor = "Orange";
store.icecream1.hasChocoChips = true;
store.icecream2.hasChocoChips = true;
store.icecream3.hasChocoChips = false;
}And, retaking your original question, each of these three classes (Icecream, IcecreamStore, and IcecreamSalesMan) could be in a different .java file, and the program would work just fine. No need for packages!
I'm sorry if you already knew all this and I just gave you a stupid lecture, but from your post I got the impression that you didn't have these concepts very clear. Otherwise, if you got the point, I'll let your extrapolate it to your own code. Should be a pice of cake! -
Help With Multiple Class Objects With Methods
I am dealing with multiple classes. I am wondering why I am getting an error on this line it's by the bottom
obj1.array() = newArray[i];
It gives the array out of bounds. On another note I believe I can change obj1 to just like incomingArray if I wanted correct since it's just a reference because I should be able to do this method sort on any array.
method : selSort
input - none
output - void
This is where we sort the arary
Pseudocode Code:
1 Initialize variable oldlocation to hold spot of smallest number in original array
2 Initialize variable smallnumber to store smallest number in original array
3 Initialize new integer array
4 Set new array length to length of original array
5 Initialize variable length to store lengh of new array
6 For i = 0 and continue till i < new array length
6.1 Find smallest number in original array
6.2 Put the smallest number in new array
6.3 Remove smallest number from original array
7 Copy contents of new array that is sorted to original array
Basic concept is to repetitively find the smallest
(or largest) item in the original array. Once smallest
is found, move it to the next spot in a new array and
remove it from the old array.
public void selSort ()
int oldlocation = 0;
int smallnumber = 0;
int [] newArray = obj1.array();
newArray = new int [obj1.length()];
int length = newArray.length;
for (int i = 0; i < newArray.length; i++)
// System.out.println("Test 1");
newArray[i] = obj1.sortSmall();
// System.out.println("Test 2");
smallnumber = obj1.sortSmall();
// System.out.println("This is the smallest number " + smallnumber);
oldlocation = obj1.location(smallnumber);
// System.out.println("This is the old location " + oldlocation);
// System.out.println("Test 3");
obj1.removeLocation(oldlocation);
// System.out.println("Test 4");
System.out.println();
System.out.println("The sorted array looks like");
for (int k = 0; k < newArray.length; k++)
System.out.print(newArray[k] + " ");
System.out.println();
System.out.println();
obj1.resize(newArray.length);
for (int i = 0; i < newArray.length; i++)
obj1.array()[i] = newArray[i];
return;method : selSort
input - none
output - void
This is where we sort the arary
Pseudocode Code:
1 Initialize variable oldlocation to hold spot of smallest number in original array
2 Initialize variable smallnumber to store smallest number in original array
3 Initialize new integer array
4 Set new array length to length of original array
5 Initialize variable length to store lengh of new array
6 For i = 0 and continue till i < new array length
6.1 Find smallest number in original array
6.2 Put the smallest number in new array
6.3 Remove smallest number from original array
7 Copy contents of new array that is sorted to original array
Basic concept is to repetitively find the smallest
(or largest) item in the original array. Once smallest
is found, move it to the next spot in a new array and
remove it from the old array.
public void selSort ()
int oldlocation = 0;
int smallnumber = 0;
int [] newArray = obj1.array();
newArray = new int [obj1.length()];
int length = newArray.length;
for (int i = 0; i < newArray.length; i++)
// System.out.println("Test 1");
newArray[i] = obj1.sortSmall();
// System.out.println("Test 2");
smallnumber = obj1.sortSmall();
// System.out.println("This is the smallest number " + smallnumber);
oldlocation = obj1.location(smallnumber);
// System.out.println("This is the old location " + oldlocation);
// System.out.println("Test 3");
obj1.removeLocation(oldlocation);
// System.out.println("Test 4");
System.out.println();
System.out.println("The sorted array looks like");
for (int k = 0; k < newArray.length; k++)
System.out.print(newArray[k] + " ");
System.out.println();
System.out.println();
obj1.resize(newArray.length);
for (int i = 0; i < newArray.length; i++)
obj1.array() = newArray[i];
return; -
Need Help with new Classes / methods
Hi, I need to create a class called Proposition. It include a Proposition object with 3 variables
Name, Description, Value
This is the constructor I wrote:
private String name;
private String description;
private boolean value;
public Proposition(){
name = "name";
description = "description";
value = false;
}Now I need a method that give values to the 3 variables in the proposition object:
public Proposition setProp(String line){
StringTokenizer ST1 = new StringTokenizer(line, ".");
String ValidLine = ST1.nextToken()+".";
StringTokenizer ST2 = new StringTokenizer(ValidLine, "=");
name = CutSpace(ST2.nextToken());
description = (ST2.nextToken()).trim();
value = false;
return name;
return description;
return value;
}An example of String line is: v = we are in Vancouver.
When I run the program, I got error message with the 3 return statements saying found String/Boolean while Proposition is needed. I'm not quite sure how to write the return statements. Can any1 help?
Thx!Your setProp() method should not be returning anything. After all it is setting not getting. So just declare it as
public void setProp(String line){and remove the return statements. -
Help with standard deviation assignment
I am having trouble with the std deviation portion of one of my assignments. Plus, only 5 test scored will print, not all 6. Could you please take a look and see what I am doing wrong? Is there a way to add the find the std dev. and mean for each semester?
----------------------Start Code------------------------------
public class Main {
int grades[][]={{15,20,15,20,15,20},
{14,21,14,21,14,21},{13,22,13,22,13},
{14,21,14,21,14,21},{15,20,15,20,15}};
int students, tests;
String output;
/** Creates a new instance of Main */
public Main() {
* @param args the command line arguments
public static void main(String[] args) {
Main m = new Main();
m.students = m.grades.length;
m.tests = m.grades[0].length;
m.output = "The scores are:\n";
m.buildString();
m.output += "\nMean: " + m.mean();
// + "\nStd Dev: " + m.StdDev() + "\n";
System.out.print(m.output);
public String mean(){
double mean = 0;
String outputMean = "";
for (int column = 0; column < students; column++){
int sumOfGrades = 0;
for (int row = 0; row < students; row++){
sumOfGrades += grades[row][column];
mean = sumOfGrades/students;
outputMean += mean + " ";
return outputMean;
// public double StdDev(){
// Main m = new Main();
// int sumOfGrades = 0;
// double StdDev = 0;
// for (int column = 0; column < students; column++){
// for (int row = 0; row < students; row++){
// sumOfGrades += Math.pow((grades[row][column]-mean()), 2);
// StdDev = Math.sqrt(mean/students) + " ";
// return StdDev;
public void buildString(){
output += " | Fall | Spring |\n";
output += " ";
for (int counter = 0; counter < tests; counter++)
output += "Test " + (counter + 1) + " ";
for (int row = 0; row < students; row++){
output += "\nStudent(" + (row + 1) + ") ";
for (int column = 0; column < tests -1; column++)
output += grades[row][column] + " ";
----------------------end code-----------------------------
------------------ Displays----------------
The scores are:
| Fall | Spring |
Test 1 Test 2 Test 3 Test 4 Test 5 Test 6
Student(1) 15 20 15 20 15
Student(2) 14 21 14 21 14
Student(3) 13 22 13 22 13
Student(4) 14 21 14 21 14
Student(5) 15 20 15 20 15
Mean: 14.0 20.0 14.0 20.0 14.0
-----------------end displays----------------What I was thinking was that mean() would be a lot more useful if
(1) you passed it an argument saying what test you were interested in. This would
take the place of "column" in your code.
(2) it returned a double value which was the mean of the given test. The snippet you
posted is OK, except that it should return a double not an int. Ie it should look like: /** Returns the mean for a given test. */
public double mean(int column) {
double mean = 0.0;
// do calculation
return mean;
}Of course if you do this you will have to change how mean() is used from within main().
Instead of a simple "m.output += "\nMean: " + m.mean();" you will need a loop: // start the string
m.output += "\nMean: ";
for(int ndx = 0; ndx < tests; ++ndx) {
// append each mean
m.output += " " + mean(ndx);
}The standard deviation method will be very similar to the mean() one, and
used in a similar way: /** Returns the sd for a given test. */
public double mean(int column) {
double sd = 0.0;
// do calculation based on what was posted,
// or what you have been told to do.
return sd;
} -
Need help with a Class.
Ok hey guys i got A project for school and i need help. I asked my teacher and he num so yea. here it is
this is my blog class
/* Project Name: .java
Name:
Class: Programing 2 #0047-02 Pds 5&6
Variable List:
Info:
import java.util.Scanner;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
public class blog
String date2;
String user;
String Entry;
public void GetInfo(String Iuser,String IEntry)
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
date2 = dateFormat.format(date);
user = Iuser;
Entry = IEntry:
public void ShowInfo()
System.out.println(date2 + " " + user + " Said: " + Entry);
}This is my test class
/* Project Name: .java
Name: Josh
Class: Programing 2 #0047-02 Pds 5&6
Variable List:
Info:
import java.util.Scanner;
public class test
String user;
String Entry;
public static void main (String[] args)
{ System.out.println("Welcome Please Eneter UserName");
Scanner kb = new Scanner(System.in);
user = kb.next();
System.out.println("Please Enter Your Entry");
Entry = kb.next();
blog info = new blog();
blog.GetInfo(user,Entry);
blog.ShowInfo();
}So what is sopost to do in the test it ask user to import user name and entery. It send it to blog Class, then it send it out. Here is my errors
G:\VOC T2\Java\Chap4\test.java:21: non-static variable user cannot be referenced from a static context
user = kb.next();
^
G:\VOC T2\Java\Chap4\test.java:25: non-static variable Entry cannot be referenced from a static context
Entry = kb.next();
^
G:\VOC T2\Java\Chap4\test.java:29: non-static variable user cannot be referenced from a static context
blog.GetInfo(user,Entry);
^
G:\VOC T2\Java\Chap4\test.java:29: non-static variable Entry cannot be referenced from a static context
blog.GetInfo(user,Entry);
^
G:\VOC T2\Java\Chap4\test.java:29: GetInfo(java.lang.String,java.lang.String,java.lang.String) in blog cannot be applied to (java.lang.String,java.lang.String)
blog.GetInfo(user,Entry);
^
G:\VOC T2\Java\Chap4\test.java:31: non-static method ShowInfo() cannot be referenced from a static context
blog.ShowInfo();
^
6 errors
Tool completed with exit code 1 Plez help-- "non-static X cannot be referenced from a static context" --
You get this error because static members don't require an instance of the object to be accessed; they belong to the class. But a non-static member belongs to an instance (an individual object). There's no way for the static method to know which instance's variable to use or method to call, and thus, the compiler happily tells you that you can't access an instance member (non-static) from a class context (static).
[The Java? Tutorial - Understanding Instance and Class Members|http://java.sun.com/docs/books/tutorial/java/javaOO/classvars.html]
~ -
Help with mysql class (Japplet)
Hi,I have found program that exactly what i want in Japplet ,but its not clean i wana use it on my other classes . Here is what i tired from changing .After all,i am not professionnel in java.
The ORGINAL HERE :
http://forum.java.sun.com/thread.jsp?forum=4&thread=197844
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.*;
import javax.swing.table.*;
import java.net.URL;
import java.sql.*;
import java.util.*;
import java.util.Properties;
import java.net.URL;
import java.sql.*;
public class Sql extends JApplet
public String tfDrv = null, tfSQL = null;
//public String dbUser,dbPass;
Connection conn = null;
private Statement stmt =null;
/*public Sql() {
public void init() {
private void initialize( String dbUser,String dbPass,String tfDrv ) {
initDB("jdbc:mysql://localhost/mysql",dbUser,dbPass,tfDrv);
private void initDB(String connect,String user,String pass,String tfDrv) {
try {
String url = connect;
this.tfDrv=tfDrv;
Class.forName("org.gjt.mm.mysql.Driver");
conn = DriverManager.getConnection( url, user, pass );//should get name, pwd
} catch( Exception e ) {
e.printStackTrace();
public ResultSet executeSQL( String sql ) throws Exception {
System.out.println( "DS exSQL " + sql );
int irs = 0;
ResultSet rs = null;
try {
stmt = conn.createStatement();
boolean bo = stmt.execute("use "+ this.tfDrv);
if( sql.startsWith( "select" ) ) {
rs = stmt.executeQuery( sql );
System.out.println( "xq rs: " + rs );
else if( sql.startsWith( "delete" ) ||
sql.startsWith( "insert" ) ) {
irs = stmt.executeUpdate( sql );
else if( sql.startsWith( "update" ) ) {
irs = stmt.executeUpdate( sql );
catch( Exception e ) {
System.out.println(e.getMessage());
e.printStackTrace();
throw e;
return rs;
private DefaultTableModel doSQL( String sql ) {
DefaultTableModel m = new DefaultTableModel();
java.util.Vector data = new java.util.Vector();
java.util.Vector headers = new java.util.Vector();
try {
String s = "";
ResultSet rs = executeSQL( sql );
System.out.println( "rs " + rs );
ResultSetMetaData rsmd = rs.getMetaData();
////List datas = new LinkedList();
////datas = new ArrayList();
for( int c = 1, cc = rsmd.getColumnCount(); c <= cc; c++ ) {
headers.addElement( rsmd.getColumnName( c ) );
java.util.Vector datum = null;
while( rs.next() )
datum = new java.util.Vector();
for( int c = 1, cc = rsmd.getColumnCount(); c <= cc; c++ ) {
s = rs.getString( c );
datum.addElement( s );
data.addElement( datum );
} catch( Exception e ) {
e.printStackTrace();
m.setDataVector( data, headers );
System.out.println( "d: " + data );
return m;
public static void main( String[] args ) throws Exception{
Sql rb = new Sql();
ResultSet rs;
rb.initialize( "root","root","test" );
//rb.doSQL("DELETE FROM `oop` WHERE `oop`.`java` = 2");
rs = rb.executeSQL("DELETE FROM `oop` WHERE `oop`.`java` = 2");
System.out.println(rs.getString("1"));
}Ok Sorry
This the same program after edditing and its works great
but the problem i don't want GUI I want to use it in other classes to connect to mysql database .So please Help.
http://forum.java.sun.com/thread.jsp?forum=4&thread=197844
permission java.lang.RuntimePermission "accessClassInPackage.sun.jdbc.odbc";
permission java.util.PropertyPermission "file.encoding", "read";
permission java.net.SocketPermission "*:*", "connect,listen,resolve,accept";
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.*;
import javax.swing.table.*;
import java.net.URL;
import java.sql.*;
import java.util.*;
import java.util.Properties;
import java.net.URL;
import java.sql.*;
public class yesSql extends JApplet
private JTextField tfDrv = null, tfSQL = null;
Connection conn = null;
private Statement stmt =null;
public yesSql() {
public void init() {
initialize( (JPanel) getContentPane() );
private void initialize( JPanel p ) {
p.setLayout( new BorderLayout() );
JLabel lDrv = new JLabel( "DB Name: " );
tfDrv = new JTextField( 25 );
tfDrv.setText( "mysql" );
JPanel pp = new JPanel();
pp.setLayout( new GridLayout( 6, 2 ) );
pp.add( lDrv );
pp.add( tfDrv );
JLabel lSQL = new JLabel( "SQL" );
tfSQL = new JTextField( 25 );
tfSQL.setText( "select * from " );
pp.add( lSQL );
pp.add( tfSQL );
JButton b = new JButton( "Submit" );
b.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent ev ) {
initDB("jdbc:mysql://localhost/mysql","root","root");
initTable( (JPanel) getContentPane() );
pp.add( b );
p.add( "North", pp );
private void initDB(String connect,String user,String pass) {
try {
String url = connect;
String drv = tfDrv.getText();
// DriverManager.registerDriver( new sun.jdbc.odbc.JdbcOdbcDriver() );
Class.forName("org.gjt.mm.mysql.Driver");
conn = DriverManager.getConnection( url, user, pass );//should get name, pwd
System.out.println( "d: " + drv + ", u: " + url );
} catch( Exception e ) {
e.printStackTrace();
public ResultSet executeSQL( String sql ) throws Exception {
System.out.println( "DS exSQL " + sql );
int irs = 0;
ResultSet rs = null;
try {
stmt = conn.createStatement();
boolean bo = stmt.execute("use "+ tfDrv.getText());
if( sql.startsWith( "select" ) ) {
rs = stmt.executeQuery( sql );
System.out.println( "xq rs: " + rs );
else if( sql.startsWith( "delete" ) ||
sql.startsWith( "insert" ) ) {
irs = stmt.executeUpdate( sql );
else if( sql.startsWith( "update" ) ) {
irs = stmt.executeUpdate( sql );
catch( Exception e ) {
System.out.println(e.getMessage());
e.printStackTrace();
throw e;
return rs;
private DefaultTableModel doSQL( String sql ) {
DefaultTableModel m = new DefaultTableModel();
java.util.Vector data = new java.util.Vector();
java.util.Vector headers = new java.util.Vector();
try {
String s = "";
ResultSet rs = executeSQL( sql );
System.out.println( "rs " + rs );
ResultSetMetaData rsmd = rs.getMetaData();
for( int c = 1, cc = rsmd.getColumnCount(); c <= cc; c++ ) {
headers.addElement( rsmd.getColumnName( c ) );
java.util.Vector datum = null;
while( rs.next() )
datum = new java.util.Vector();
for( int c = 1, cc = rsmd.getColumnCount(); c <= cc; c++ ) {
s = rs.getString( c );
datum.addElement( s );
data.addElement( datum );
} catch( Exception e ) {
e.printStackTrace();
m.setDataVector( data, headers );
System.out.println( "d: " + data );
return m;
private void initTable( JPanel p ) {
DefaultTableModel dtm = doSQL( tfSQL.getText() );
JTable tb = new JTable( dtm );
JScrollPane sp = new JScrollPane( tb );
JFrame fr = new JFrame();
fr.getContentPane().add( sp );
fr.pack();
fr.show();
public static void main( String[] args ) {
JFrame f = new JFrame();
yesSql rb = new yesSql();
JPanel p = (JPanel) f.getContentPane();
rb.initialize( p );
f.pack();
f.show();
} -
Need help with generic class with comparable type
Hi. I'm at University, and I have some coursework to do on writing a generic class which offers ordered binary trees of items which implement the comparable interface.
I cant get the code to compile which I have written.
I get the error: OBTComparable.java uses unchecked or unsafe operations
this is the more detailed information of the error when I compile with -Xlint:unchecked
OBTComparable.java:62: warning: [unchecked] unchecked call to insert(OBTType) as
a member of the raw type OBTComparable
left.insert(insertValue);
^
OBTComparable.java:64: warning: [unchecked] unchecked call to insert(OBTType) as
a member of the raw type OBTComparable
right.insert(insertValue);
^
OBTComparable.java:75: warning: [unchecked] unchecked call to find(OBTType) as a
member of the raw type OBTComparable
return left.find(findValue);
^
OBTComparable.java:77: warning: [unchecked] unchecked call to find(OBTType) as a
member of the raw type OBTComparable
return right.find(findValue);
^
and here is my code for the class
public class OBTComparable<OBTType extends Comparable<OBTType>>
// A tree is either empty or not
private boolean empty;
// If the tree is not empty then it has
// a value, a left and a right.
// These are not used it empty == true
private OBTType value;
private OBTComparable left;
private OBTComparable right;
// Create an empty tree.
public OBTComparable()
setEmpty();
} // OBTComparable
// Make this tree into an empty tree.
private void setEmpty()
empty = true;
value = null; // arbitrary
left = null;
right = null;
} // setEmpty
// See if this is an empty (Sub)tree.
public boolean isEmpty()
{ return empty; }
// Get the value which is here.
public OBTType getValue()
{ return value; }
// Get the left sub-tree.
public OBTComparable getLeft()
{ return left; }
// Get the right sub-tree.
public OBTComparable getRight()
{ return right; }
// Store a value at this position in the tree.
private void setValue(OBTType requiredValue)
if (empty)
empty = false;
left = new OBTComparable<OBTType>(); // Makes a new empty tree.
right = new OBTComparable<OBTType>(); // Makes a new empty tree.
} // if
value = requiredValue;
} // setValue
// Insert a value, allowing multiple instances.
public void insert(OBTType insertValue)
if (empty)
setValue(insertValue);
else if (insertValue.compareTo(value) < 0)
left.insert(insertValue);
else
right.insert(insertValue);
} // insert
// Find a value
public boolean find(OBTType findValue)
if (empty)
return false;
else if (findValue.equals(value))
return true;
else if (findValue.compareTo(value) < 0)
return left.find(findValue);
else
return right.find(findValue);
} // find
} // OBTComparableI am unsure how to check the types of OBTType I am comparing, I know this is the error. It is the insert method and the find method that are causing it not to compile, as they require comparing one value to another. How to I put the check in the program to see if these two are of the same type so they can be compared?
If anyone can help me with my problem that would be great!
Sorry for the long post, I just wanted to put in all the information I know to make it easier for people to answer.
Thanks in advance
DavidI have good news and undecided news.
First the good news. Your code has compiled. Those are warnings not errors. A warning is the compiler's way of saying "I understand what you are asking but maybe you didn't fully think through the consequences and I just thought I would let you know that...[something] "
In this case it's warning you that you aren't using generics. But like I said this isn't stopping it from compiling.
The undecided news is the complier is warning you about not using generics. Are you supposed to use generics for this assignment. My gut says no and if that's true then you have no problem. If you are supposed to use generics well then you have some more work. -
Need help with JComponent class
Hi,
I'm trying to create a class that has all the characteristics of several GUI components such as JButton, JLabel, JRadioButton .... combined into one big class. But when I run the codes, the object of this new class is not visible on a frame like a JButton or a JLabel would be. Someone, please give me some hints. Thanks.
The ButtonWrapper class extends JButton and the CheckBoxWrapper class extends JCheckBox and they both work without any problems. The GuiWrapper class (listed below) is the class that has the visibility problem when added to a container of a frame.
import java.awt.*;
import javax.swing.*;
public class GuiWrapper extends JComponent{
public GuiWrapper(String ptype, String p2, String p3) {
if(ptype.toLowerCase() == "button"){
ButtonWrapper b = new ButtonWrapper(p2, p3);
if(ptype.toLowerCase() == "checkbox"){
CheckBoxWrapper c = new CheckBoxWrapper(p2, p3);
}Okay, so, for starters, I think this is a Really Bad Idea. If your developers can't handle using the API/tutorial to learn how the components work, your project will fail. This UberClass will not help in the long run. It will also almost certainly turn into a maintainence nightmare for you.
Of course, since you're going to do it anyway... I suspect your issue lies with paintComponent. If I recall correctly, paintComponent doesn't render anything by default for a JComponent. You'll need to override paintComponent and have it invoke the renderer for the relevant child component. -
Help with Runtime class and timeout of Process
Hi,
Question regarding using Runtime class, and yes I have looked at the javadocs, but I am still confused and frustrated.
Here is part of my code.
Process p;
Runtime runtime = Runtime.getRuntime();
p = runtime.exec("rsh localhost ls");
if you are not familiar with rsh all it does is remote shell into the computer localhost and executes the command ls.
Now, I dont have rsh running on my computer so it will hang at that line for about 40 sec and eventually time out on its own. Is there anyway I can specify a timeout argument like there is for the ping command? Like if there is no response from localhost after 3 sec, then just kill the process?
I looked at the Runtime javadoc and Process javadoc and the closest thing I could come to with is something to do with envp (environment parameters), but I dont know what that is.
Thanks guys.You can't timeout the "runtime.exec("rsh localhost ls");" call but if you execute the call in a seperate thread you can "timeout" and continue executing on the original thread (while letting the "runtime" thread to timeout on its own).
Check the following class that I created for cases like this:
abstract public class TimeoutHelper implements Runnable
private Throwable error;
private boolean running = true;
private Object retValue;
protected String name;
private long waitTime;
private Thread thread;
* Creates a new helper. Use {@link #start} to run the code.
* @param name A name that will be used in the helper thread name
* @param waitTime The time (in msec) to wait before timeout.
public TimeoutHelper(String name, long waitTime)
this.name = name;
this.waitTime = waitTime;
public Object start() throws Throwable
return asyncExecute();
abstract protected Object execute() throws Throwable;
private synchronized Object asyncExecute() throws Throwable
createThread().start();
if (running)
try
wait(waitTime);
if (running)
// Timeout!!
abortThread();
throw new TimeOutException("Timeout for: " + name);
catch (InterruptedException ie)
// Ignore
if (error != null)
throw error;
return retValue;
private void abortThread()
if (thread != null)
thread.interrupt();
protected Thread createThread()
thread = new Thread(this, name);
return thread;
public void run()
try
retValue = execute();
catch (Throwable th)
error = th;
synchronized (this)
running = false;
notifyAll();
}You use the class by extending it and implementing "execute". For example:
TimeoutHelper helper = new TimeoutHelper("Runner", 5000)
protected Object execute() throws Throwable
Runtime runtime = Runtime.getRuntime();
return runtime.exec("rsh localhost ls");
try
Process p = (Process)helper.start();
catch (TimeOutException e)
// Handle timeout here
catch (Exception e)
// Handle other errors here.
} -
Help with making class smaller
Here goes... I used forte to design a gui and this gui is quite large. Its over 1400 lines already without any functionality added. Is there an easy way to make this into smaller classes. If this helps I used a desktop pane and inside I made around 9 internal frames with radio buttons and such. Any help is appreciated.
You might take a look at your first posting; it has replies. :)
-
Need help with a class project
I'm new to Java and I'm having problems converting a small program to be more functional. Here is my original codeimport java.util.Arrays;
public class Product
// initialize arrays
private int cdNums[] = { 0,0,0,0 };
private String cdNames[] = { "null", "null", "null", "null" };
private int cdUnits[] = { 0,0,0,0 };
private double cdValue[] = { 0.0, 0.0, 0.0, 0.0 };
private double inventoryValue[] = { 0.0, 0.0, 0.0, 0.0 };
// initialize instance variable
private double totalValue = 0;
private int count;
public Product( int invNumber[], String albumName[], int invUnits[], double invValue[] )
cdNums = invNumber; // store inventory number
cdNames = albumName; //store album name
cdUnits = invUnits; //store number of units
cdValue = invValue; // store unit price
public double calcInventoryValue()
// calculate Inventory value
for ( int count = 0; count < cdNums.length; count++ )
totalValue =0; // initialize totalValue
totalValue =( cdUnits[ count ] * cdValue [ count ] );
System.out.printf( "%s%d%s%s%s%d%s%.2f%s%.2f\n", "Item #", cdNums[ count ], " is: ", cdNames[ count ], " with ", cdUnits [ count ], " units priced at $", cdValue [ count ], " gives value of $", totalValue );
return totalValue;
} // end calcinventoryValue method
} // end classand the test application: import java.util.Arrays;
public class ProductTest
public static void main( String args[] )
int invNumber [] = { 1,2,3,4 };
String albumName[] = { "Wish You Were Here", "Abacab", "Animals", "Security" };
int invUnits[] = { 200, 150, 50, 500 };
double invValue[] = { 14.99, 9.99, 23.49, 12.99 };
Product myProduct = new Product (invNumber, albumName, invUnits, invValue );
myProduct.calcInventoryValue();
} // end main
} // end class ProductTestWhat I want to do is convert it to read in user input instead of static lists. Here is what I have so far:
import java.util.Arrays;
public class Product
// initialize arrays
private int cdNums[];
private String cdNames[];
private int cdUnits[];
private double cdValue[];
private double inventoryValue[];
// initialize instance variable
private double runValue = 0;
private double totalValue = 0;
private int count;
public Product( int invNumber[], String albumName[], int invUnits[], double invValue[] )
cdNums = invNumber; // store inventory number
cdNames = albumName; //store album name
cdUnits = invUnits; //store number of units
cdValue = invValue; // store unit price
public double calcInventoryValue()
// calculate Inventory value
totalValue = 0; // Initialize totalValue variable
for ( int count = 0; count < cdNums.length; count++ )
runValue =0; // initialize runValue
runValue =( cdUnits[ count ] * cdValue [ count ] );
System.out.printf( "%s%d%s%s%s%d%s%.2f%s%.2f\n", "Item #", cdNums[ count ], " is: ", cdNames[ count ], " with ", cdUnits [ count ], " units priced at $", cdValue [ count ], " gives value of $", runValue );
totalValue = totalValue += runValue;
calcTotalValue( totalValue );
return totalValue;
} // end calcinventoryValue method
public double calcTotalValue( double totalValue )
System.out.printf( "%s%.2f\n", "The total value of the inventory is: $", totalValue );
return totalValue;
} // end calcTotalValue method
} // end classand the new test application:
import java.util.Arrays;
import java.util.Scanner;
public class ProductTest
public static void main( String args[] )
double totalValue = 0;
do
{ // open dowhile
int count = 0; // initialize counter
Scanner input = new Scanner( System.in ); // call scanner to get input
for ( int count = 0; count > 0; count++ )
{ // open for loop
System.out.printf ( "%s%d%s\n", "Please enter the inventory # of Item ", count, " or 0 to quit: " ); // prompt for inventory number or sentinel value
int invNumber[ count ] = input.nextInt(); // get user input of Item Number
if ( invNumber[ count ] != 0 ) // check for sentinel
{ // open if
System.out.printf ( "%s%d\n","Please enter the album name of Item #", invNumber[ count ] ); // prompt for album name
String albumName[ count ] = input.nextLine(); // get input album name
System.out.printf ( "%s%d\n", "Please enter the number of units in stock for Item #", invNumber[ count ] ); // prompt for number of units in stock
int invUnits[ count ] = input.nextint(); // input rate of payment
System.out.printf ( "%s%.2f\n", "Please enter the unit price for Item #", invNumber[ count ] ); // prompt for unit price
double unitValue = input.nextDouble(); // input rate of payment
System.out.println(); // print blank line for readability
} // close if
else
{ // open else
Product myProduct = new Product (invNumber, albumName, invUnits, invValue );
myProduct.calcInventoryValue();
} // close else
} // close for loop
} while ( invNumber != 0 ); // loop back to inputting employee name and close dowhile
} // end main
} // end class ProductTestthe compiler is telling me for ProductTest that it is expecting "]" for the following line: int invNumber[ count ] = input.nextInt();Do I need to store the data in a variable first and then feed it into the array? What do I need to do to complete this code?OK, yeah. Change the Product constructor so that it takes scalar values (as opposed to arrays) -- a single int for units in stock, and single String for name, etc.
Then you can create multiple objects of that class, one for each CD or whatever.
It makes sense to hardcode values in the ProductTest class, but not really in the Product class. Your ProductTest class is almost there. You know how in the main method you create a single Product object with those arrays? Change it so that you have a loop. Loop through the prices, album names, etc., and create a Product for each set of values. Then put the Product objects in an array, or better yet (and if you've covered it in class) into a Collection like a java.util.HashSet or a java.util.ArrayList.
You said you wanted to make it take values from user input, rather than hardcoded lists. Once you've made the above change, move on to doing that. You can read user input with a java.util.Scanner. Or you can use a java.io.BufferedReader. Did the prof say to use one particular method or another? -
Help with objects, classes, etc...
Im having a little trouble grasping the concept of all of these names. I know that every Java program is a class. Now, is a method what we call in C++ a function? It seems as though this is what it is while reading this book but just want to clarify it. And also, what is a good defninition for an object. I know that parseInt() is an object but does that mean that is is some kind of function/method that was declared or made in a class?
lol ... ok; it's easy to get caught up in the jargon...
A class is a "type" of thing, complete with values which describe the thing and operations that the thing can perform. For instance, a "dog" can be described in terms of its breed, size, markings, and things that it does (eat, do tricks, bark, etc).
An object is a dinstinct instance of a class. So, if you are talking about one particular dog, let's say Lassie, you can describe it as a collie, of a certain size, etc, etc.
Object oriented programming makes use of this jargon. The act of creating an object from a class description is known as "instantiation".
You mentioned C++. In C++, you can have functions which stand alone, or functions which are part of classes. C++ functions which are part of class definitions are known as "member functions"; Java methods are like C++ member functions.
now, on to parseInt(). remember how we said that a class definition can define operations (like "eat", for a dog)? well, although we can define the eat operation, only a instance of dog (e.g., Lassie) can actually perform the operation. so, if you have Lassie and RinTinTin in front of you, and you say, "Lassie, bark!", only Lassie will perform that operation.
in object oriented programming, a method which makes sense for one object (that is, one particular instance of a class) to perform is known as an instance method. there's another abstraction, though... you can define variables and methods which belong to all instances of a class (as a group), rather than any one particular object. These are known as class variables and class methods, and Java uses the keyword "static" to identify them.
So, if I had the class dog, it might look a little like:
public class Dog {
private float weight; // each dog object will have its own weight variable
static private int count; // this is shared by all instantiated dog objects!
public void bark() {
// instance method. call this with respect to a particular dog object
System.out.println ("Woof.");
public static int getCount() {
// this method is shared by all instantiated dog objects. It's called using the syntax
// Dog.getCount(), rather than by instantiating a dog object and using the object to call
// the method
return count;
// etc...
}Does that make sense? some variables belong to each particular instantiated object, while others don't need an object in order to refer to them.
one more thing: in Java, there are objects and there are primitives. the primitives are data types such as int, float, boolean, etc. Java also provides wrappers for these primitives, so you can refer to them in object contexts; for example, Integer, Boolean, etc.
OK... now back to your question. parseInt() is a static method of class Integer. (therefore, you don't need an instance of Integer in order to call parseInt().
the parseInt() method returns an int.
make sense?
Maybe you are looking for
-
Transfer from external hard drive to Apple TV
I'm not the sharpest computer user, but I need to know how to transfer movies I've put on my external hard drive to save space on my Mac mini to Apple TV. Is this possible without loading them on the mini first?
-
Should I get an iPad mini or an iMac
-
The Video Converter for the new
I don't know if all creative players use the same video converter but for the new ZEN I have a problem with cropping the widescreen videos. I tick the box and everything but the converter doesn't crop the video, it stays exactly the same and I have t
-
Provisioning RSA ------ Excepti (login)Sd_ContinueLoginError Access Denied
hey please help me in this I am trying to provision users to RSA 5.2 from SUN IDM 6.0, I am using when I provision a user to RSA it says com.waveset.util.WavesetException:SecurId ACE/Server:(login)Sd_ContinueLoginError Access Denied I have seen that
-
"No Audio Output Device is installed." vista sound problem *Attn. HP*
I've been seeing several posts attempting to address this issue but I don't think anyone quite understands how deep it goes... therefore, I'll try to give as many details as possible. About two weeks or so ago the sound on my laptop started to behave