Interpreting a string variables value & returning a constants int value

Let's say I have the following:
private string ballColour;
private static final int RED = 1;
the value of the variable ballColour is obtained via keyboard input from the user.
lets say they enter in the string red (or RED, whatever case, it's converted to lowercase & stored in ballColour).
I now want to create a method which returns the integer value of the RED constant (i.e. if the user enters a ballColour of red, I want to return the integer value 1 - to a new variable called intValueOfBallColour).
I've no idea how to do this & i'm sure it isn't that complicated, but I'm having trouble with incompatible data types.
Please help!

Hmm...not really.
I have a class & a driver (though the driver really
only contains the system.out.println & gets the
user's input).
The class should be doing all the work & whilst our
code is somewhat similar, i.e. same kind of
principle, it differs quite a bit.
For example, I'm not sure what this section of your
code is for:
public static void main(String[] args) {
ballColour = args[0];
setIntValueOfBall();
System.out.println("intValuOfBall=" +
Ball=" + intValuOfBall);
My class contains many more methods/constructors.
it really should work. I'll have a look at your code
more & see if i can get it work. It's so
straightforward. So frustrating as well.
Thanks so much for your help.you can post your whole code (between code tags), that'll help people spot the problem

Similar Messages

  • How i pass table column  value to string variable or return to java applete

    Hi Master,
    How do I pass a table column value into string variable. See my code below:
    import java.sql.*;
    public class Waheed {
    public Waheed() {
    public static void main (String args [])
    String s = "9 23 45.4 56.7";
    System.out.println ("going for connection");
    // DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver());
    try{
    Class.forName("oracle.jdbc.driver.OracleDriver");
    Connection conn =
    DriverManager.getConnection("jdbc:oracle:thin:@fahim:1521:aamir","muhammad","mfa786");
    Statement stmt = conn.createStatement();
    ResultSet rset = stmt.executeQuery("select accid from accbal");
    System.out.println ("going for connection");
    while (rset.next())
    s= rset.getString("accid"); this line give me error
    System.out.println (rset.getString("accid"));
    System.out.println (s);
    catch(Exception e){
    e.printStackTrace();
    This line give me an error:
    s= rset.getString("accid");
    s is string variable
    Plese give me an idea how I can pass accid in s variable.
    Thanks.
    Aamir

    See the code sample in the following thread (try using upeercase).
    JDBC  connection
    Kuassi

  • Parsing a string to formula and executing to int value

    Hi ,
    I have a String from the database which will hold symbols + - etc.
    Eg: String a =((((2+5)/(80*76)) -65)*)The above shows a string with operators and numeric values. I need to execute this String and obtain a integer value.
    How i can accomplish this. From database ill be getting may different string with different formula values.
    Any help is highly appreciated.
    Thanks in advance.
    Regards,
    Satheesh Kannan.A.B

    We already have [this post|http://forums.sun.com/thread.jspa?threadID=5144807],
    may also try [this link|http://sourceforge.net/projects/expression-tree/].

  • Doubt about  a null value assigned to a String variable

    Hi,
    I have a doubt about a behavior when assigning a null value to a string variable and then seeing the output, the code is the next one:
    public static void main(String[] args) {
            String total = null;
            System.out.println(total);
            total = total+"one";
            System.out.println(total);
    }the doubt comes when i see the output, the output i get is this:
    null
    nulloneA variable with null value means it does not contains a reference to an object in memory, so the question is why the null is printed when i concatenate the total variable which has a null value with the string "one".
    Is the null value converted to string ??
    Please clarify
    Regards and thanks!
    Carlos

    null is a keyword to inform compiler that the reference contain nothingNo. 'null' is not a keyword, it is a literal. Beyond that the compiler doesn't care. It has a runtime value as well.
    total contains null value means it does not have memory,No, it means it refers to nothing, as opposed to referring to an object.
    for representation purpose it contain "null"No. println(String) has special behaviour if the argument is null. This is documented and has already been described above. Your handwaving about 'for representation purpose' is meaningless. The compiler and the JVM don't know the purpose of the code.
    e.g. this keyword shows a hash value instead of memory addressNo it doesn't: it depends entirely on the actual class of the object referred to by 'this', and specifically what its toString() method does.
    similarly "total" maps null as a literal.Completely meaningless. "total" doesn't 'map' anything, it is just a literal. The behaviour you describe is a property of the string concatenation operator, not of string literals.
    I hope you can understand this.Nobody could understand it. It is compete nonsense. The correct answer has already been given. Please read the thread before you contribute.

  • Convert String variable value  to an Object referece type

    Hi all,
    I want to know that if there any possible way to convert String variable value to a Object reference type in java. I'll explain by example if this is not clear.
    Let's think that there is a string variable name like,
    String name="HelloWorld";
    and there is a class name same to the variable value.
    class HelloWorld
    I am passing this string variable value to a method which is going to make a object of helloworld;
    new convertobj().convert("HelloWorld");
    class convertobj{
    public void convert(String name){
    // in hert it is going to create the object of HelloWorld;
    // HelloWorld hello=new HelloWorld(); just like this.
    now i want to do this from the name variable value.( name na=new name()) like wise.
    please let me know if there any possible way to do that.
    I am just passing the name of class by string variable then i wanted to make a instance of the class which come through the variable value.
    thanx.

    Either cast the object to a HelloWorld or use the reflection API (Google it) - with the reflection API you can discover what methods are available.
    Note: if you are planning to pass in various string arguments and instantiate a class which you expect to have a certain method... you should define an interface and have all of your classes that you will call in this way implement the interface (that way you're sure the class has a method of that name). You can then just cast the object to the interface type and call the method.
    John

  • Assigning value returned from RFC call to a global variable

    If I have an RFC call to SAP how can I assign the value returned to a global variable on my data services job?

    Hi,
    For now, it seems u haven't specified the destination properly. the call function statement must be suffixed with the 'destination' addition to make sure that the function call is an RFC and the particular function be executed at the desired destination.

  • How to find out the type of the value stored in a string variable?

    Hi,
    How do i find out the type of the value stored in a string variable?
    for example,
    I have a string variable str, in which the following type of values wil be stored
    1) Intger
    2) Long
    3) boolean
    4) Char
    Is there any method to find out the type of the value, anything like str.getType()?. Please kindly help me. Thanks in advance.

    Hi All, i'm sorry for the double posting, by mistake it occured.
    Thanks for your replies, i have a string variable str, in which the value is stored and i have another string variable type, in which the type of the value is stored.
    For example,
    String str = "15";
    String type = "Integer";
    Is there any way to verify whether the value stroed in str is of type stored in the variable 'type'. I want to write a method of type boolean, it will throw true of the value stored in str is of type 'type'. Thanks

  • How to include a carriage return in a TestStand string variable

    Is there anyway to add a carriage return to a TestStand string variable. I am sending commands to an instrument using the Rs232 serial bus and they need to be terminated with a carriage return ie "\r". I know you can creat a DLL and return the string variables to TestStand but is there a beter way ?

    Hi Paul,
    Sorry about that, just noticed I left off the "" in my last response.
    Try "\\r".  that should solve it.
    Regards
    Ray Farmer
    Message Edited by Ray Farmer on 09-15-2005 09:14 AM
    Regards
    Ray Farmer

  • Can't change string variable values in Flash CS4 Debugger

    I'm using the Flash CS4 debugger, and while I can change numeric variable values in the Variables panel, I can't change string variable values. The only characters the fields accept are the numbers 1-9 and the characters "d" and "j".
    I can  paste strings  into the value fields, but that's a bit of a pain. I've tried this on a couple of different Flash CS4 installations and get the same results.
    Does anyone know if it's possible to change string values in the Variables panel of the Flash CS4 Debugger?

    See:
    http://forum.java.sun.com/thread.jspa?threadID=591012&tstart=15

  • Naming an ArrayList using value from a String variable

    I am trying to name an ArrayList the value of a String variable in this code:
    public void addstudent(String name)
    ArrayList //i need a name here// = new ArrayList();
    I want to use the String //name// that will be used when the method is called. What do I do? I tried using:
    ArrayList (String.valueOf(name)) = new ArrayList();
    That didn't work.
    Thanks in advance for any help.

    Its suppossed to allow the user to input the student's name, grades for 4 specific subjects. Then take that and organize the students by name alphabetically. It is also suppossed to allow the user to search for users by grades, like find everybody with a GPA of 3.7 or higher or find everybody with a GPA of 3.5. This was a project asigned by my intro computer science teacher. I was suppossed to make it with 2D arrays but that was lousy because you were then limited to a specific number of students without editing the code. I'm not familiar with all the different ways of doing this. My computer science teacher said that I could do it with a HashSet.
    Okay. You have a String. Let's suppose it contains "fred" or something like that -- you didn't say what was in it so we have to speculate. Next, you want to create an ArrayList from that? What does that mean? You want to end up with an ArrayList that contains one entry, that string? Or what?
    In your example I would want to start by giving the method "fred" as the name parameter. So right now the String (name) has the value of "fred". I then wanted to make an ArrayList for that student named fred. This ArrayList would have 4 grades for that student fred. This ArrayList for fred would be part of a HashSet for the whole group of students. That way when I wanted to search alphabetically, I would just sort the HashSet. My computer science teacher said this would work.
    Thanks

  • Can I preserve carriage returns in a string variable from SQL Server?

    I have an OLE data source that pulls data from sql server via a SELECT query.  One of the fields is an NVARCHAR(max) which goes into a string variable which is later used in an expression.  I am noticing that in the expression, carriage returns
    / line breaks in this field are being lost.  Does anyone know how I can preserve these in the expression?

    Thanks everyone for the suggestions.  I am certain there are both \r and \n in the database as when I print the field and then copy/paste to textedit to show the hidden characters, I can see both the CR and LF's.  
    I have implemented a workaround that is by no means elegant, but it gets the job done.
    I found that \r and \n will evaluate in an expression but if they are part of another string variable, SSIS escapes them. My workaround was to change my OLE_DB select statement (which fetches the custom SQL query) to explicitly change the hidden characters
    to '\r' and '\n' respectively:
    SELECT REPLACE(REPLACE([CUSTOM_SQL],char(13),'\r'),char(10),'\n')
    Then, in my SSIS expression, I de-escaped these characters:
    REPLACE(REPLACE(@[User::vAlertCustomSQL],"\\r","\r"),"\\n","\n")
    Now when the expression is executed, the SQL is formatted correctly and oddly placed comments in the query no longer break the query.  

  • Is there an way to get the value of a local string variable from core dump?

    Hi All,
    Please help me on this, How to extract the string variable content from the core file.
    During core file analysis using dbx, it puts value as CLASS against string local variables.
    But I need to know the exact value during the core dump.
    I'm able to print other than string variables.
    Is this possbile using dbx or is there any other tool can help me on this.
    Thanks in advance, please find the code details below:
    here is my core details:
    (dbx) where -h
    current thread: t@74
    [1] __lwp_kill(0x0, 0x6, 0x217b8, 0x7f950b94, 0x2, 0x7f0fb944), at 0x7f99fb84
    [2] raise(0x6, 0x0, 0x7f0fb958, 0x7f6a5434, 0x1, 0x7f0fb9a4), at 0x7f950b9c
    [3] abort(0x7f6bf0f8, 0x4, 0x7f6bf0b8, 0x15360, 0x1, 0x7f6bf0f8), at 0x7f936d10
    [4] exregister(0x7f6bf0fc, 0x4, 0x7f6bf0b8, 0x15360, 0x1, 0x7f6a5048), at 0x7f6a504c
    [5] exregister(0x7f6bf0f8, 0x7f6a505c, 0x7f6bf0f8, 0x7f6bb080, 0x0, 0x1), at 0x7f6a5060
    [6] exregister(0x7f0fbb28, 0x66bd8, 0xe4fd0, 0x7f6bb080, 0x7f6ba780, 0x1), at 0x7f6a4fd8
    [7] 0x7f6a5edc(0x7f6bae64, 0x0, 0x66bd8, 0x14cb8, 0x14928, 0x0), at 0x7f6a5edc
    =>[8] AreaManager::commitCombine(this = 0xe5234, parsedSetName = CLASS), line 369 in "AreaManager.cc"
    [9] TaskDispatcher::combineParsedSet(parsedSetName = CLASS), line 113 in "TaskDispatcher.cc"
    [10] CombineExecutor::run(this = 0x1312d8), line 159 in "CombineExecutor.cc"
    [11] thread_body(threadObj = 0x1312d8), line 35 in "ThreadUtils.cc"
    (dbx)
    (dbx) dump
    parsedSetName = CLASS
    parsedSetCombinedName = CLASS
    parserSetBuiltName = CLASS
    this = 0xe5234
    (dbx)
    (dbx) print parsedSetName
    dbx: cannot access address 0x7f6690f4
    (dbx)
    BR//Sahoo

    When I was running in a higher version, it gives follwing error:
    A loadobject was found with an unexpected checksum value.
    When using the same core dump binary, the result are different than the locally build binary
    This is the error it pointing now:
    if ((ptr = (CHAR *) malloc((unsigned int) size)) == NULL)
    (dbx) proc -map
    Loadobject mappings for current core file:
    0x00010000 /usr/omc/1.8.0.0.56/bin/PmLoader
    0x7fb80000 /usr/lib/libaio.so.1
    0x7fb30000 /usr/lib/libm.so.1
    0x7fbfa000 /usr/lib/libdl.so.1
    is being filtered by: /usr/lib/ld.so.1
    Warning: checksum in file(a5bd) doesn't match image(a5bf)
    0x7faf0000 /usr/lib/libelf.so.1
    Warning: checksum in file(38a7) doesn't match image(38a9)
    0x7fad0000 /usr/lib/libsocket.so.1
    0x7fa00000 /usr/lib/libnsl.so.1
    0x7f900000 /usr/lib/libc.so.1
    is being filtered by: /usr/platform/SUNW,Ultra-80/lib/libc_psr.so.1
    Warning: checksum in file(3b8c) doesn't match image(3ec6)
    0x7f890000 /usr/informix/lib/esql/libthsql.so
    0x7f830000 /usr/informix/lib/libthasf.so
    0x7f7b0000 /usr/informix/lib/esql/libthgen.so
    0x7f770000 /usr/informix/lib/esql/libthos.so
    0x7f700000 /usr/informix/lib/esql/libifgls.so
    0x7f9e0000 /usr/informix/lib/esql/libifglx.so
    0x7f6d0000 /usr/lib/libthread.so.1
    0x7f500000 /usr/lib/libCstd.so.1
    Warning: checksum in file(1fc4) doesn't match image(3f67)
    0x7f6a0000 /usr/lib/libCrun.so.1
    Warning: checksum in file(1a8d) doesn't match image(b1ea)
    0x7fba0000 /usr/lib/libw.so.1
    is being filtered by: libc.so.1
    0x7f4e0000 /usr/lib/libmp.so.2
    0x7f4a0000 /usr/lib/cpu/sparcv8plus/libCstd_isa.so.1
    Warning: checksum in file(0fc3) doesn't match image(27d6)
    0x7f9d0000 /usr/platform/sun4u-us3/lib/libc_psr.so.1
    0x7f410000 /usr/lib/nss_files.so.1
    0x7fbb0000 /usr/lib/ld.so.1 [LM_ID_LDSO]
    Warning: checksum in file(f2f2) doesn't match image(2a40)
    dbx ./PmLoader ./core
    For information about new features see `help changes'
    To remove this message, put `dbxenv suppress_startup_message 7.5' in your .dbxrc
    Reading PmLoader
    core file header read successfully
    Reading ld.so.1
    Reading libaio.so.1
    Reading libm.so.1
    Reading libdl.so.1
    Reading libelf.so.1
    Reading libsocket.so.1
    Reading libnsl.so.1
    Reading libc.so.1
    Reading libthsql.so
    Reading libthasf.so
    Reading libthgen.so
    Reading libthos.so
    Reading libifgls.so
    Reading libifglx.so
    Reading libthread.so.1
    Reading libCstd.so.1
    Reading libCrun.so.1
    Reading libw.so.1
    Reading libmp.so.2
    Reading libCstd_isa.so.1
    Reading libc_psr.so.1
    Reading nss_files.so.1
    WARNING!!
    A loadobject was found with an unexpected checksum value.
    See `help core mismatch' for details, and run `proc -map'
    to see what checksum values were expected and found.
    dbx: warning: Some symbolic information might be incorrect.
    t@1 (l@1) terminated by signal BUS (invalid address alignment)
    0x7f947974: t_delete+0x0068: clr [%o1 + 8]
    Current function is Malloc
    40 if ((ptr = (CHAR *) malloc((unsigned int) size)) == NULL)
    (dbx)
    (dbx) where -h
    current thread: t@1
    [1] t_delete(0x17c980, 0x470, 0x1ef778, 0x7f9bc000, 0x0, 0x0), at 0x7f947974
    [2] mallocunlocked(0x414, 0x0, 0x0, 0x7f9bc000, 0x0, 0x0), at 0x7f947004
    [3] malloc(0x414, 0xebae0, 0x8, 0xffbfc9a8, 0xffbfc9a0, 0x1a3791), at 0x7f946e38
    =>[4] Malloc(size = 1044U), line 40 in "Malloc.c"
    [5] Drain_Socket(sc = 0x1ab100, fd = 10, block = 0xffbfce44), line 1648 in "ipc_sockio.c"
    [6] Sockio_Refresh(instance = 0x1ab100, fd = 10U, readable = 1, writeable = 0, block = 0xffbfce44), line 3465 in "ipc_sockio.c"
    [7] do_Refresh(cid = 10U, readable = 1, writeable = 0, block = 0xffbfce44), line 1238 in "ipc_IO.c"
    [8] IO_Refresh(block = 0, file_descriptor = -1), line 685 in "ipc_IO.c"
    [9] ipc_receive_message(gid = 0xffbfcf88, reply = 0xffbfd080, buffer = 0x11ae08 "", len = 0xffbfcf34, block = 0), line 313 in "ipc_services.c"
    [10] IPCProcessor::receiveMessage(this = 0x1172d0, channelID = 2U, pReplyChannelID = 0xffbfd080), line 312 in "IPCProcessor.cc"
    [11] IPCProcessor::mainLoop(this = 0x1172d0, pHandler = 0xf9c28), line 203 in "IPCProcessor.cc"
    [12] IPCService::mainLoop(pMediator = 0x1172d0, pHandler = 0xf9c28), line 51 in "IPCService.cc"
    [13] main(argc = 3, argv = 0xffbfe1f4), line 91 in "PmLoader.cc"
    I got another instance of core dump in same m/c
    Edited by: chittusun on Nov 5, 2008 5:19 AM

  • Pass a value returned from variable to parameter ssis 2012

    DECLARE
    @var1
    sql_variant
    =
    @DatabaseName
    EXEC
    [SSISDB].[catalog].[set_execution_parameter_value]
    @execution_id,
    @object_type=30,
    @parameter_name=N'DatabaseID',
    @parameter_value=@var1hi
    all, is it possible to pass the variable value to the parameter instead of the value like above instead of value, in the above case @database holds value of the database

    "pass
    the variable value to the parameter instead of the value like
    above instead of value"
    is misleading
    where do you pass what from?
    Arthur My Blog

  • How to find a string inside another String variable

    Hi,
    I need to find whether a string is available in a String of varying length.
    i.e., i want to know string "access" is available in a String variable( may have values like "microsoft access 2000 bla bla bla .." or "bla bla access microsoft").
    so, i dont know the starting point of the word 'access' in the String variable.
    Pls help me in doing this.
    Thanks in advance,
    Rao

    Check the API documentation for this method:
    "int indexOf(String str)
    Returns the index within this string of the first occurrence of the specified substring."

  • 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.

Maybe you are looking for

  • Cannot update or backup my 3G. The new iTunes no longer has the backup menu

    Hi, looking for help. I have a 3G and want to back it up so I can buy a 5G iphone and transfer all my stuff. The new itunes nolonger has the  window to choose to backup or update. Can anyone help...please...

  • White Lines in exported JPEG or TIFFF files

    When I export a photo from Aperture onto my desktop it appears with 1 or 2 white / colorless vertical lines running through it. This seems to happen with fscanned film and digital files. The lines do not appear in Aperture, just after export......Any

  • Javax.faces.STATE_SAVING_METHOD produces invalid XHTML

    Hi to all, it seems that setting the value javax.faces.STATE_SAVING_METHOD in the web.xml causes invalid XHTML code. I checked the produced code using the validator of w3.org. All of the errors are caused by the input field which should save the stat

  • Measuring Multiple channels at a time

    Hello All, I am new to Labview trying to measure voltages and currents from a synchronous generators using LabView7.1 abd PCI-MIO-16E-4. I want to measure all the three phase voltages all at a time so that I can see the phase difference between them.

  • BIG troubles after Security Update 2007-002 (Universal): Apps gone dead!!!!

    After doing the above Update, all ADOBE apps went dead at once. Had to reinstall everything. Same thing happening with Apples iWork. Apps won't start anymore! tried to restore access rights, deleted the prefs but still there is no success. This Updat