Void Methods and Value Returning Methods in Java

Hello,
I'm new here so please let me know if I overstep any of the rules or expectations. I merely want to learn more about Java Programming efficiently, and easily. I can ask and discuss these topics with my online prof, but she doesn't have much time.
So right now I'm trying to solve a problem. It's a typical college level computing problem which I've already turned in. So I'm not looking for someone to do my homework for me or something. It's just that the program didn't work. Even though I probably won't get a very good grade for it, I want to
make it work! I'm kind of slow when it comes to java so just bear with me.
The prof wanted us to write an algorithm that reads a student's name and 6 exam scores. Then it computes the average score for each student, assigns a letter grade, using a rating scale:
90 and above = A
80 - 89 = B
70 ? 79 = C
60 - 69 = D
Less then 60 ? F
We had to use a void method to determine the average score for each student, a loop inside the method to read the and sum the 6 scores but without outputting the average score. The sum and average had to be returned in and output in void main.
Then we had to use a value-returning method CalculateGrade to determine and return the grade for each student. But it can't output the grade because that must be done in void main.
Finally the class average must be output.
Our prof gave us a list of student names with their 6 scores.
Ward 100 54 98 65 35 100
Burris 89 65 87 84 15 32
Harris 54 21 55 87 70 54
Bettis 43 55 68 54 15 25
Staley 87 54 98 45 54 56
Randle 54 87 54 98 65 15
Maddox 56 14 40 50 40 50
Roth 30 40 54 78 24 19
Holmes 14 87 98 34 55 57
So all the data had to be read from a file and the results output to a file. Also we couldn't use 'global variables'. We had to use the appropriate parameters to pass values to and from methods.
Question 1:  What does she mean by 'no global variables'? Maybe she means: don't use "*double test1, test2, test3, test4, test5*;"
Anyway because I'm a slow learner with Java, I end up looking for sample programs that seem to do a similar job as the problem posed. So with this program I decided to adapt a program called Comparison of Class Averages.
//Program: Comparison of Class Averages.
import java.io.*;
import java.util.*;
import java.text.DecimalFormat;
public class DataComparison
public static void main (String[] args) throws
FileNotFoundException, IOException
//Step 1
String courseId1; //course ID for group 1
String courseId2; //course ID for group 2
int numberOfCourses;
DoubleClass avg1 = new DoubleClass(); //average for a course
//in group 1
DoubleClass avg2 = new DoubleClass(); //average for a course
//in group 2
double avgGroup1; //average group 1
double avgGroup2; //average group 2
String inputGroup1;
String inputGroup2;
StringTokenizer tokenizer1 = null;
StringTokenizer tokenizer2 = null;
//Step 2 Open input and output files
BufferedReader group1 =
new BufferedReader(new FileReader("a:\\group1.txt"));
BufferedReader group2 =
new BufferedReader(new FileReader("a:\\group2.txt"));
PrintWriter outfile =
new PrintWriter(new FileWriter("a:\\student.out"));
DecimalFormat twoDecimal =
new DecimalFormat("0.00"); //Step 3
avgGroup1 = 0.0; //Step 4
avgGroup2 = 0.0; //Step 5
numberOfCourses = 0; //Step 6
//print heading: Step 7
outfile.println("Course No Group No Course Average");
inputGroup1 = group1.readLine(); //Step 8
inputGroup2 = group2.readLine(); //Step 9
while((inputGroup1 != null) &&
(inputGroup2 != null)) //Step 10
tokenizer1 = new StringTokenizer(inputGroup1);
courseId1 = tokenizer1.nextToken(); //Step 10a
tokenizer2 = new StringTokenizer(inputGroup2);
courseId2 = tokenizer2.nextToken(); //Step 10b
if(!courseId1.equals(courseId2)) //Step 10c
System.out.println("Data error: Course IDs "
+ "do not match.");
System.out.println("Program terminates.");
outfile.println("Data error: Course IDs "
+ "do not match.");
outfile.println("Program terminates.");
outfile.close();
return;
else //Step 10d
calculateAverage(group1, tokenizer1, avg1); //Step 10d.i
calculateAverage(group2, tokenizer2, avg2); //Step 10d.ii
printResult(outfile,courseId1,1,avg1); //Step 10d.iii
printResult(outfile,courseId2,2,avg2); //Step 10d.iv
avgGroup1 = avgGroup1 + avg1.getNum(); //Step 10d.v
avgGroup2 = avgGroup2 + avg2.getNum(); //Step 10d.vi
outfile.println();
numberOfCourses++; //Step 10d.vii
inputGroup1 = group1.readLine(); //Step 10e
inputGroup2 = group2.readLine(); //Step 10f
}//end while
if((inputGroup1 != null) && (inputGroup2 == null)) //Step 11a
System.out.println("Ran out of data for group 2 "
+ "before group 1.");
else //Step 11b
if((inputGroup1 == null) && (inputGroup1 != null))
System.out.println("Ran out of data for "
+ "group 1 before group 2.");
else //Step 11c
outfile.println("Avg for group 1: " +
twoDecimal.format(avgGroup1 / numberOfCourses));
outfile.println("Avg for group 2: " +
twoDecimal.format(avgGroup2 / numberOfCourses));
outfile.close(); //Step 12
public static void calculateAverage(BufferedReader inp,
StringTokenizer tok,
DoubleClass courseAvg)
throws IOException
double totalScore = 0.0;
int numberOfStudents = 0;
int score = 0;
if(!tok.hasMoreTokens())
tok = new StringTokenizer(inp.readLine());
score = Integer.parseInt(tok.nextToken());
while(score != -999)
totalScore = totalScore + score;
numberOfStudents++;
if(!tok.hasMoreTokens())
tok = new StringTokenizer(inp.readLine());
score = Integer.parseInt(tok.nextToken());
}//end while
courseAvg.setNum(totalScore / numberOfStudents);
}//end calculate Average
public static void printResult(PrintWriter outp,
String courseId,
int groupNo, DoubleClass avg)
DecimalFormat twoDecimal =
new DecimalFormat("0.00");
if(groupNo == 1)
outp.print(" " + courseId + " ");
else
outp.print(" ");
outp.println("\t" + groupNo + "\t "
+ twoDecimal.format(avg.getNum()));
So my adaptation turned out like this:
//Program: Compute individual and class averages from input file.
import java.io.*;
import java.util.*;
public class Exams
public static void main (String[] args)
throws FileNotFoundException
//Step 1
String nameId; //student name ID for list
int numberOfStudents;
DoubleClass avg = new DoubleClass(); //average for a student
//in list
double avgList; //average for list
//Step 2 Open the input and output files
Scanner group1 = new Scanner(new FileReader("c:\\list.txt"));
PrintWriter outfile = new PrintWriter("c:\\student.out");
avgList = 0.0; //Step 3
numberOfStudents = 0; //Step 5
//print heading: Step 6
outfile.println("NameID List Student Average");
calculateAverage(list, avg); //Step 7d.i
printResult(outfile,nameID, avg); //Step 7d.iii
avgList = avgList + avgList.getNum(); //Step 7d.v
outfile.println();
numberOfStudents++; //Step 7d.vii
outfile.printf("Avg for List: %.2f %n",
(avgList / numberOfStudents));
public static void calculateAverage(Scanner inp,
DoubleClass courseAvg)
double totalScore = 0.0;
int numberOfStudents = 0;
int score = 0;
score = inp.nextInt();
courseAvg.setNum(totalScore / numberOfStudents);
}//end calculate Average
public static void printResult(PrintWriter outp,
String nameId,
int groupNo, DoubleClass avg)
if (list == list)
outp.print(" " + nameId + " ");
else
outp.print(" ");
outp.printf("%9d %15.2f%n", list, avg.getNum());
I guess I was trying to find a shortcut that ended up being a long cut. Here's the algorithm I wrote.
Algorithm
1.) Initialize the variables
2.) Get the student name and his/her accompanying 6 exam scores, limiting the number of scores to 6.
3a.) Calculate score of 6 exams for each student using void method called CalculateAverage.
3b.) Use a loop inside the method to read and sum the six scores.
4.) Use value-returning method CalculateGrade to determine and return each student's grade.
5.) Output each student's grade in void main.
6.) Calculate the average score for all students
7.) Output entire class average
And now I'm trying to piece together code to match each step of the algorithm starting from scratch.
So I got the code for outputting each students grade in void:
public static void printGrade(double testScore)
System.out.print("Line 10: Your grade for "
+ "the course is ");
if (testScore >= 90)
System.out.println("A");
else if (testScore >= 80)
System.out.println("B");
else if (testScore >= 70)
System.out.println("C");
else if (testScore >= 60)
System.out.println("D");
else
System.out.println("F");
This code can read the the file with the scores:
Scanner inFile =
new Scanner(new FileReader("a:\\studentlist.txt"));
PrintWriter outFile =
new PrintWriter("a:\\avg.out");
courseGrade = inFile.nextDouble();
studentName=inFile.nextChar();
while (inFile.hasNext())
studentName= inFile.next().charAt(0);
courseGrade= inFile.nextDouble();
I'm just trying to piece this thing together. Any tips would be appreciated. I will return with more pieces to the puzzle soon. As you can tell it's all kind of disorganized, and scatterbrained. Just trying to find some simplification or distillation, or recommendations.
WR

Hello,
Thanks for your reply. So I take it you are more familiar with Object Oriented Programming more than Procedural Based Programming?
Well the teacher insisted I follow the algorithm instead of trying to adapt another program to the problem. But sometimes that approach saves time I've noticed since many of the code examples we study in Java are like 'the golden oldies'.
The student gradebook problem is repeated over and over in different forms. Maybe if I just approached the problem more linearly:
Algorithm
1.) Initialize the variables
String studentId
int numberOfStudents
DoubleClass avg = new DoubleClass(); //average for a student
double avgGroup: //average for all students2.) Get the student name and his/her accompanying 6 exam scores.
Scanner group = new Scanner(new FileReader("c:\\list.txt"));
PrintWriter outfile = new PrintWriter("c:\\student.out"));
3a.) Calculate score of 6 exams for each student using void method called CalculateAverage using a loop to read and sum the six scores. The loop must be inside the method. It does not output the average score. The sum and average must be returned and output in void main.
method calculateAverage
double totalScore //to store the sum of all the scores of each student
int numberOfExams;  //to store the number of
int score; //to read and store a course score
double totalScore = 0.0
int numberOfExams = 0;
int score = 0;3b.) Use a loop inside the method to read and sum the six scores.
Using psuedocode (since the variables have been declared and initialized)
i)get the next student score
RIght here my approach of adapting another program to my new program becomes problematic
the pseudocode here is:
ii) while (score != -999):
I.) update totalScore by adding course score read in step i.
II.) increment numberOfExams by 1
III.) Get the nex student score
iii) studentAvg.setNum(totalScore / numberOfExams);
*What is the purpose of the statement while (score != -999)?*
I don't see why they picked -999?  Will this loop allow me to read an endless number of student names and theri accompanying number of exams and then find the average for each student?
I'll go into the next algorithmic steps later.
4.) Use value-returning method CalculateGrade to determine and return each student's grade.
5.) Output each student's grade in void main.
6.) Calculate the average score for all students
7.) Output entire class average
Thanks ahead of time for any suggestions, tips.

Similar Messages

  • Difference between Session method and Call transaction method

    Hi,
    Difference between Session method and Call transaction method in BDC

    Hi,
    SESSION method:
    Is a standard procedure for transferring large amount of data into the R/3 system.
    Data consistency is ensured because batch input uses all thje checks conducted on the normal screen.
    It is a two step procedure:
    1.  Progarm: creates batch input session. This session is the data file that includes everything to begin the transaction.
    2. Process session: Which then actually transfers the data to database table.
    In this method an ABAP/4 program reads the external data that is to be entered in the SAP system and stores the data in a session.
    A session stores the actions that are required to enter your data using normal SAP transactions i.e. data is transferred to session which inturn transfers data to database table. Session is an intermediate step between internal table and database table.
    Data along with it's actions are stored in session. i.e. data for screen fields, to which screen it is passed, the program name behind it and how next screen is processed.
    When the program has finished generating the session, u can run the session to execute the SAP transactions in it.
    BDC_OPEN_GROUP
              You create the session through program by BDC_OPEN_GROUP function.
    1) User Name: User Name.
    2) Group       : Name of the session
    3) Lock Date : The date when you want to process the session.
    4) Keep        : This parameter is passed as 'X' when you want to retain session even       after processing it.                    
    BDC_INSERT
         Data is transferred to session by BDC_INSERT.
    BDC_CLOSE_GROUP.
         With this function the session will be closed.
    CALL TRANSACTION method.
    Syntax: call transaction <tr code> using <bdctab>
                                 mode <A/N/E>
                                 update <S/A>
                                 messages into <internal table>.
    <tr code>   : transaction code
    <bdctab>   : Name of the BDC table
    mode: mode in which you execute the transaction.      
    A   : all screen mode ( all the screens of the transaction are displayed )
    N   : no screen mode ( no screen will be displayed when you execute the transaction )
    E   : error screen ( only those screens are displayed where in you have error record )
    Update type:
    S: synchronous update in which if you change data of one table then all the related tables gets updated and SY_SUBRC is returned for once and all.
    A: asynchronous update in which if you change data of one table, the sy-subrc is returned and then updation of other affected tables takes place. So if system fails to update other tables still sy-subrc returned is zero.(that is when first table gets updated ).
    messages: if you update database table, operation is either successful or unsuccessful. These messages are stored in internal table. This internal table structure is like BDCMSGCOLL.
           TCODE:  transaction code.
           DYNAME: batch input module name.
           DYNNUMB: batch input dyn no.
           MSGTYP:  batch input message type.
           MSGSPRA: batch input language id of message.
           MSGID:    message id.
           MSGV1….MSGV5: message variables
    For each entry which is updated in the database table message is available in BDCMSGCOLL.
    Reward if useful
    Regards
    Srinu

  • What is the difference between organisation payment method and Assignment payment method?

    What is the difference between organisation payment method and Assignment payment method?
    As i am a new bie, i am curious to know this though it might sound a silly question.
    Thank you,
    Kuton

    You can create an Organization payment method of any Payment type(Cash, Check, BACS, NACHA etc) under the same country.
    All these will be valid payment methods on the payroll description form.
    And you can even attach these to a person.
    In which case you will have a Base currency (say USD) and payment currency (say GBP).
    These cases are not normal and only used by people who use a single BG for paying employees in 3-4 countries.
    So, unless you need to pay in different currencies, do not use it.
    Cheers,
    Vignesh

  • Difference between batch input method and direct input method in LSMW.

    Hi all,
    what is difference between batch input method and direct input method in LSMW. are they same?if differences are there tell me with details?

    Hi,
    Here are few differences bw Batch Input and Direct Inputs methods.
    Batch Input: Uses classical BDC approach, but doesn't required an ABAP program to be written to format the BDC DATA. The user has to format the data using predefined structures and store it in a flat file. Yet it is a slower updation method.
    Direct Input: Works similar to Batch Input programs. The difference is, instead of processing screens they validate fields and directly load the data into tables using standard function modules. Much faster and suits for large volume of data.
    Thanks.
    DhanaLakshmi M S

  • Whats the difference between a class method and a instance method.

    I have a quiz pretty soon and one of the questions will be: "How does an instance method differ from a class method." I've tried looking this up but they gave me really complicated explanations. I know what a instance method is but not really sure what a class one is. Can someone post an example of a class method and try to explain what makes it so special?
    Edited by: tetris on Jan 30, 2008 10:45 PM

    Just have a look:
    http://forum.java.sun.com/thread.jspa?threadID=603042&messageID=3246191

  • Sum of the year digit method and declining balance method

    Hi,
    My Client want Deprecation methods Sum of the year digit and declining balance method for tax purpose. This requirement for Colombia Country.
    Which Deprecation Area I activate and how will configure above two methods.
    Regards
    Venki

    Sum-of-the-Years-Digits Method of Depreciation
    Use
    For each year of the expected useful life, the system notes the remaining useful life for the assets and totals the figures in each year. In each fiscal year, the remaining life is divided by this total in order to calculate the depreciation percentage rate for that fiscal year. This method leads to depreciation amounts that are reduced progressively by the same amount each period.
    Since the remaining useful life is no longer defined after the end of the planned useful life, this depreciation method does not allow for depreciation after the end of the planned life. However, you can change to another method after the expected useful life has expired.
    Acquisitions after the depreciation start year or post-capitalization will necessarily lead to a positive net book value at the end of planned life. For this reason, such transactions are not allowed when using the sum-of-the-years-digits method of depreciation. With this method, you have to handle subsequent acquisitions by creating sub-numbers. It is also a requirement that the acquisition year is the same as the depreciation start year.
    Calculation :
    Depreciation = APC * remaining useful life (current period) / total of remaining useful life (over entire useful life)
    APC: 1000
    useful life: 4
    Total remaining useful life: 10 (= 4 + 3 +2 +1)
    Depreciation 1st year = 1000 * 4 / 10 = 400
    Depreciation 2nd year = 1000 * 3 / 10 = 300
    Depreciation 3rd year = 1000 * 2 / 10 = 200
    Depreciation 4th year = 1000 * 1 / 10 = 100
    Declining-Balance Method of Depreciation
    Use
    For the declining-balance method of depreciation, the fixed asset is depreciated by a progressively falling rate. A constant percentage rate is calculated from the expected useful life and a given multiplication factor. This is multiplied with the falling net book value of the fixed asset. For mathematical reasons, the net book value will never reach zero using this method. You change over to straight-line or complete depreciation under these conditions:
    Declining-balance depreciation < straight-line depreciation
    Net book value < x percent of acquisition value
    Net book value < fixed amount
    Net book value < straight-line depreciation
    The changeover method is specified in the internal calculation key.
    Calculation :
    Depreciation = net book value * percentage rate from expected useful life and factor
    APC: 1000
    Exp. useful life: 10
    Net book value: 700
    Multiplication factor: 3
    Depreciation = 700 * (100% / 10 * 3) = 210
    OR You can use following link
    http://help.sap.com/saphelp_45b/helpdata/en/4f/71de3b448011d189f00000e81ddfac/frameset.htm
    http://help.sap.com/saphelp_45b/helpdata/en/4f/71de3b448011d189f00000e81ddfac/frameset.htm
    Regards,
    ANJIREDDY
    Edited by: ANJIREDDYA on May 8, 2010 12:09 PM
    Edited by: ANJIREDDYA on May 8, 2010 12:10 PM

  • Difference between calling static method and not static method?

    Hi,
    Suppose i want to write a util method, and many class might call this method. what is better? writing the method as static method or not static method. what is the difference. what is the advantace in what case?

    writing the method as static method or not static
    method. what is the difference.The difference is the one between static and non-static. Any tutorial or the JLs will clarify the difference, no need to repeat it here.
    what is the advantace in what case?It's usually not like you have much of a choice. If you need access to an instance's attributes, you can't make it static. Otherwise, make it static.

  • Hook method and supply function method

    hi guru,
    what is hook method and supplyfunction methods.when we used hook methods.
    thanks in advance

    You have made a cluster of posting today that all seem as though you are asking interview questions.  The tone of the questions combined with the subject matter would lead to this conclusion.
    Might I suggest instead that you search the forums and the WIKI as well as the SAP online Help.  I believe that you will find your answers to these very basic questions - particularly since each of these topics you posted have an entry in the online help. 
    I'm am locking these threads.

  • Where get examples of the ejbSelect METHOD and Home interface method use ?

     

    Hi,
    The UI Framework has a generic M-Getter which retrives the label from DDIC. However, you can overwrite the M-Getter to return any other label. But if you define a label in Design Layer, the framework will take the label from Design Layer instead from M-Getter. And if you define a label in Configuration, the framework will take the label from the configuration instead from Design Layer.
    A-Getter is meant to be used for showing or hiding field based on Switch ID. If you see the return parameter, it returns also switch ID. Using A-Getter to showing and hiding field not based on Switch ID is not recommended.
    You were right. A-Getter is already exists in CRM 7.0 but it is not used. It is used for the Enhancement Package release of CRM.
    Regards,
    Steve

  • Bug? Picture Ring proprty String and Values" returns error 1054 in LV 8.5

    Should that propert exist for a Picture Ring?
    Ben
    Message Edited by Ben on 09-01-2008 07:47 AM
    Ben Rayner
    I am currently active on.. MainStream Preppers
    Rayner's Ridge is under construction
    Solved!
    Go to Solution.
    Attachments:
    Error_1054.PNG ‏27 KB

    The fact that the error is gone when you don't connect the indicator is good. Even better it is super.
    It means the compiler removes that specific node from the execution stack if it isn't needed.
    Ton
    Free Code Capture Tool! Version 2.1.3 with comments, web-upload, back-save and snippets!
    Nederlandse LabVIEW user groep www.lvug.nl
    My LabVIEW Ideas
    LabVIEW, programming like it should be!

  • Native method with String return type

    Hi
    i am implementing a Native method with String Return type.
    i am able call the respective C++ method and my C++ method is printing the String (jstring in c++ code ) correctly
    i but i am getting nullpointerexcepti while loading the string in to my Java String .
    i am sure my java code calling the C++ code beacause my C++ code is printing the value and one more wonder is after the NPE my c++ code able to print the value
    the code follows
    HelloWorld.java
    public class HelloWorld {
         private native String print();
         static {
             System.loadLibrary("HelloWorld");
         public static void main(String[] args) throws InterruptedException,NullPointerException{
              HelloWorld hW= new HelloWorld();
              for(int i=0;;i++){
                   String str= new HelloWorld().print();
                   System.out.println(str);
                   Thread.sleep(10000);
    }and HelloWorld.cpp
    // HelloWorld.cpp : Defines the entry point for the DLL application.
    #include "stdafx.h"
    #include "jni.h"
    #include <stdio.h>
    #include "HelloWorld.h"
    #include <windows.h>
    #include "tchar.h"
    #include "string.h"
    #ifdef _MANAGED
    #pragma managed(push, off)
    #endif
    CHAR cpuusage(void);
    typedef BOOL ( __stdcall * pfnGetSystemTimes)( LPFILETIME lpIdleTime, LPFILETIME lpKernelTime, LPFILETIME lpUserTime );
    static pfnGetSystemTimes s_pfnGetSystemTimes = NULL;
    static HMODULE s_hKernel = NULL;
    void GetSystemTimesAddress()
         if( s_hKernel == NULL )
              s_hKernel = LoadLibrary(_T("Kernel32.dll"));
              if( s_hKernel != NULL )
                   s_pfnGetSystemTimes = (pfnGetSystemTimes)GetProcAddress( s_hKernel, "GetSystemTimes" );
                   if( s_pfnGetSystemTimes == NULL )
                        FreeLibrary( s_hKernel ); s_hKernel = NULL;
    // cpuusage(void)
    // ==============
    // Return a CHAR value in the range 0 - 100 representing actual CPU usage in percent.
    CHAR cpuusage()
         FILETIME               ft_sys_idle;
         FILETIME               ft_sys_kernel;
         FILETIME               ft_sys_user;
         ULARGE_INTEGER         ul_sys_idle;
         ULARGE_INTEGER         ul_sys_kernel;
         ULARGE_INTEGER         ul_sys_user;
         static ULARGE_INTEGER      ul_sys_idle_old;
         static ULARGE_INTEGER  ul_sys_kernel_old;
         static ULARGE_INTEGER  ul_sys_user_old;
         CHAR  usage = 0;
         // we cannot directly use GetSystemTimes on C language
         /* add this line :: pfnGetSystemTimes */
         s_pfnGetSystemTimes(&ft_sys_idle,    /* System idle time */
              &ft_sys_kernel,  /* system kernel time */
              &ft_sys_user);   /* System user time */
         CopyMemory(&ul_sys_idle  , &ft_sys_idle  , sizeof(FILETIME)); // Could been optimized away...
         CopyMemory(&ul_sys_kernel, &ft_sys_kernel, sizeof(FILETIME)); // Could been optimized away...
         CopyMemory(&ul_sys_user  , &ft_sys_user  , sizeof(FILETIME)); // Could been optimized away...
         usage  =
              (ul_sys_kernel.QuadPart - ul_sys_kernel_old.QuadPart)+
              (ul_sys_user.QuadPart   - ul_sys_user_old.QuadPart)
              (ul_sys_idle.QuadPart-ul_sys_idle_old.QuadPart)
              (100)
              (ul_sys_kernel.QuadPart - ul_sys_kernel_old.QuadPart)+
              (ul_sys_user.QuadPart   - ul_sys_user_old.QuadPart)
         ul_sys_idle_old.QuadPart   = ul_sys_idle.QuadPart;
         ul_sys_user_old.QuadPart   = ul_sys_user.QuadPart;
         ul_sys_kernel_old.QuadPart = ul_sys_kernel.QuadPart;
         return usage;
    BOOL APIENTRY DllMain( HMODULE hModule,
                           DWORD  ul_reason_for_call,
                           LPVOID lpReserved
        return TRUE;
    #ifdef _MANAGED
    #pragma managed(pop)
    #endif
    JNIEXPORT jstring JNICALL
    Java_HelloWorld_print(JNIEnv *env, jobject obj)
           int n;
         GetSystemTimesAddress();
         jstring s=(jstring)cpuusage();
         printf("CPU Usage from C++: %3d%%\r",s);
         return s;
    }actually in the above code below part does that all, in the below code the printf statement printing correctly
    JNIEXPORT jstring JNICALL
    Java_HelloWorld_print(JNIEnv *env, jobject obj)
           int n;
         GetSystemTimesAddress();
         jstring s=(jstring)cpuusage();
         printf("CPU Usage from C++: %3d%%\r",s);
         return s;
    }and the NPE i get is
    Exception in thread "main" java.lang.NullPointerException
         at HelloWorld.print(Native Method)
         at HelloWorld.main(HelloWorld.java:10)
    CPU Usage from C++:   6%any solution?
    Thanks
    R
    Edited by: LoveOpensource on Apr 28, 2008 12:38 AM

    See the function you wrote:
    JNIEXPORT jstring JNICALL Java_HelloWorld_print(JNIEnv *env, jobject obj)
           int n;
         GetSystemTimesAddress();
         _jstring s=(jstring)cpuusage();_
         printf("CPU Usage from C++: %3d%%\r",s);
         return s;
    }Here you try to cast from char to jstring, this is your problem, jstring Object should be created:
    char str[20];
    sprintf(str, "%3d", (int)cpuusage());
    printf("CPU Usage from C++: %s%%\r",str);
    jstring s=env->NewStringUTF(str);
    return s;

  • WCCP src group & redirect/return method

    Has anyone here implemented 3rd party WAN optimization such as Bluecoat or Riverbed w/ WCCP?
    What service groups and redirect/return methods did you use, and on which Cisco switch/router platforms?
    I'd like to know what works, and what doesn't...
    It looks like you generally use service group 61 & 62 to redirect all TCP traffic to WAAS, based on source/destination IP's.
    Do those two service groups also work w/ 3rd party devices?
    If they don't, do I just pick some random service groups, other than the well known ones?
    How would the switch/router know what traffic to redirect, if no redirect-list is used?
    The Networkers' wccp presentation slides say if GRE is to be used w/ 6500's, generic GRE needs to be used instead of WCCP GRE.
    Where would you configure what type of GRE is used, within WAAS?
    Does anyone know if such setting exists on 3rd party devices?
    Our Bluecoat SE isn't even aware of two different versions of GRE, and neither was I, before I watched the Networkers session.

    Hi,
    I know with Riverbed you can use wccp 61/62 as well. I don't have experience with other vendors though.
    The router knows what to redirect based on the WCCP service number. It can be a well-known service or a custom service where you define what to redirect directly on the optimizer/web-cache device. The redirect list is only used to further limit what is redirected.
    In h/w forwarding platform WCCP GRE is handled in s/w, this is why using generic GRE is suggested. On WAAS you can configure it using "egress-method generic-gre intercept-method wccp"
    For more details check the "Egress Method" section in the following doc:
    http://www.cisco.com/en/US/prod/collateral/switches/ps5718/ps708/white_paper_c11-629052.html
    Here you have WCCP redirection method supported and suggested for different Cisco platforms:
    http://www.cisco.com/en/US/prod/collateral/contnetw/ps5680/ps6870/white_paper_c11-608042.html
    hope this helps,
    Fabrizio

  • Error while updating data using session and call transaction method

    Hi all,
        i have to update data using MM01 transaction from flat file to database.i have used both session method and call transaction method to do that.in both the methods data has been transferred from internal tables to screens but while updating the data that is by clicking the ok-code at the end of the transaction iam getting a dialogue box stating
       SAP EXPRESS DOCUMENT "UPDATE WAS TERMINATED" RECEIVED FROM AUTHOR "SAP".
      please tell whether the problem lies and solution for that.
                                       thanks and regards.

    hi,
    check your recording.check whether u saved your material no in recording or not.
    once again record the transacton mm01.
           MATNR LIKE RMMG1-MATNR,
           MBRSH LIKE RMMG1-MBRSH,
           MTART LIKE RMMG1-MTART,
           MAKTX LIKE MAKT-MAKTX,
           MEINS LIKE MARA-MEINS,
           MATKL LIKE MARA-MATKL,
           BISMT LIKE MARA-BISMT,
           EXTWG LIKE MARA-EXTWG,
    these are the fields which u have to take in internal table.
    this is the record which i took in my flatfile.use filetype as asc and hasfieldseperator as 'X'.
    SUDHU-6     R     ROH     MATSUDHU     "     001     7890     AA
    i did the same.but i didn't get any error.

  • Mappimg and updation in bdc 'session ' and 'call transaction' methods

    What will happen if error record comes while updating in session method and call transaction method.

    Hi,
    If any error comes in Session method U can find that error in SM35->Log
    and updste again database for those enteries
    In cll transaction Method U have to handel error manually . for this u have to use structure BDCMSGCOL and Table T100.
    Regards
    Gaurav

  • Action Method vs. HandleEvent method

    Hello,
    Can anyone tell me what the difference between the action method and the handleEvent method?
    Or more specifically, what can you do in one method that you can't do in the other?
    Thanks

    schapel is correct. Those are methods from the old JDK 1.0.x hiearchical event model and have been deprecated. But to answer your questioin, the action() method is overriden to handle action events (e.g., menu item selection, button press, ENTER key pressed in a TextField) whereas the handleEvent() method is where all events are dispatched from (including the action() method). Typically you override the handleEvent() method to dispose of a frame (see attached sample JDK 1.0.x application code).
    import java.awt.*;
    public class Hiearchical {
    public static void main(String args[]) {
      new HiearchicalFrame();
    class HiearchicalFrame extends Frame {
    Button ok = new Button("OK");
    HiearchicalFrame() {
      super();
      /* Size the frame */
      resize(200,200);
      /* Center the frame */
      Dimension screenDim = Toolkit.getDefaultToolkit().getScreenSize();
      Rectangle frameDim = bounds();
      move((screenDim.width - frameDim.width) / 2,(screenDim.height - frameDim.height) / 2);
      /* Add button to frame */
      add("South",ok);
      /* Show the frame */
      show();
    public boolean handleEvent(Event evt) {
      if (evt.id == Event.WINDOW_DESTROY) {
       dispose(); System.exit(0);
      return super.handleEvent(evt);
    public boolean action(Event evt, Object obj)
      if (obj.equals("OK"))
       System.out.println("You pressed the OK button!");
      return false; //don't propogate the event up the containment chain

Maybe you are looking for

  • Catalyst + dual head = incorrect primary monitor

    I have Radeon HD 3450 that has VGA-, DVI- and HDMI-ports. I have connected two LCD-monitors to VGA (19") and DVI (24"). After that I installed catalyst (9.8-1) and catalyst-utils (9.8-1). I managed to get GNOME work ok with two screen, I have two sep

  • 10g Upgrade Order (DEV - QAS - PRD)

    If I am upgrading Oracle 9.2.0.6 to 10.2.0.2, what issues will I face if I upgrade the landscape in the order of DEV, QAS, PRD. I will wait a week between upgrades. Will transports fail? Will SAP face any issues having different Oracle versions? Do I

  • Export form of smartforms

    i want to export form of smartforms from client 300 and import this form to client 400 by transport request. please help me. thanks

  • 9i to 10G Forms

    Somewhere, I saw a posting asking if we will be able to patch from 9i (9.0.2) to 10G (9.0.4) but I cannot find it now. Will 10G be a complete install or will we be able to patch up to 10G?

  • Log file does not exist

    I have recently installed p6.8 and when I try to view my log after I have scheduled the project I get a message that my "SCHEDLOG.TXT does not exist", I've hit the elliptical button and created the file path that I want the file stored in but, when I