Method return problem

Hi, please help me to see the problem I facing for my assignment.
I need to do a few of non-duplicate random number and store them into an array. Then assign a KEY and search the array to get the index number of the array. I'm doing a linear search in a different method(not main).
Here is the algorithm for the linear search and I need to do exactly like it.
ALGORITHM SearchSorted(A[0..n − 1], K)
// Searches for a given value K in a given array A of n numbers which
// is sorted into nondecreasing order. The index of the first item in A that
// matches K is returned, or −1 if there are no such items.
i �� 0
while i < n do
if K < A[i]
return &#8722;1
else
if K = A[i]
return i
else
i �� i + 1
return &#8722;1
And here is my coding.
public static int Linear(int A[], int K) // method called, array and key
     int i = 0;
          while(i<A.length)
          if(K<A) // will stop when array's element is greater than the key and return -1
               return -1;
          else
               if(K==A[i]) // will return index number of the array is key found
                    return i;
               else
                    i = i + 1;
          return -1; // will return -1 if no match of element
     return -1; // method ask for return value, any way to get rid of this?
The problem I facing is, each time I run it, it will only return one -1 instead of many -1 until the Key is been found.
If I delete the last "return -1", the program can't run. If I change the last second "return -1" to "System.out.println("-1", the program can run smoothly but it will extra one more -1 at the output and i think it cause by the last return.
What should I do to make it better? Thank you very much for helping.

I think you should delete this line:
return -1; // will return -1 if no match of elementWith this line the cycle will run only once.

Similar Messages

  • Java.nio select() method return 0 in my client application

    Hello,
    I'm developing a simple chat application who echo messages
    But my client application loop because the select() method return 0
    This is my code
    // SERVER
    package test;
    import java.io.IOException;
    import java.net.InetSocketAddress;
    import java.nio.channels.SelectionKey;
    import java.nio.channels.Selector;
    import java.nio.channels.ServerSocketChannel;
    import java.nio.channels.SocketChannel;
    import java.util.Iterator;
    import java.util.Set;
    public class Server {
         private int port = 5001;
         public void work() {               
              try {
                   ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
                   serverSocketChannel.configureBlocking(false);
                   InetSocketAddress isa = new InetSocketAddress(port);               
                   serverSocketChannel.socket().bind(isa);
                   Selector selector = Selector.open();
                   serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
                   System.out.println("Listing on "+port);
                   while(selector.select()>0) {
                        Set keys = selector.selectedKeys();
                        for(Iterator i = keys.iterator(); i.hasNext();) {
                             SelectionKey key = (SelectionKey) i.next();
                             i.remove();
                             if (key.isAcceptable()) {
                                  ServerSocketChannel keyChannel = (ServerSocketChannel)key.channel();                              
                                  SocketChannel channel = keyChannel.accept();
                                  channel.configureBlocking(false);                              
                                  channel.register(selector, SelectionKey.OP_READ );
                             } else if (key.isReadable()) {
                                  SocketChannel keyChannel = (SocketChannel) key.channel();
                                  String m = Help.read(keyChannel );
                                  Help.write(m.toUpperCase(), keyChannel );
              } catch (IOException e) {                                             
                   e.printStackTrace();                         
         public static void main(String[] args) {
              Server s = new Server();
              s.work();
    // CLIENT
    package test;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.io.IOException;
    import java.net.InetSocketAddress;
    import java.nio.channels.SelectionKey;
    import java.nio.channels.Selector;
    import java.nio.channels.SocketChannel;
    import java.util.Iterator;
    import java.util.Set;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    public class Client extends JFrame  {
         private String host = "localhost";
         private int port = 5001;
         private SocketChannel socketChannel;
         private Selector selector;
         public void work() {               
              try {
                   socketChannel = SocketChannel.open();
                   socketChannel.configureBlocking(false);
                   InetSocketAddress isa = new InetSocketAddress(host, port);               
                   socketChannel.connect(isa);
                   selector = Selector.open();
                   socketChannel.register(selector, SelectionKey.OP_CONNECT | SelectionKey.OP_READ );
                   while(true) {
                        selector.select();
                        Set keys = selector.selectedKeys();
                        for(Iterator i = keys.iterator(); i.hasNext();) {
                             SelectionKey key = (SelectionKey) i.next();
                             i.remove();
                             if (key.isConnectable()) {
                                  SocketChannel keyChannel = (SocketChannel) key.channel();
                                  if (keyChannel.isConnectionPending()) {
                                       System.out.println("Connected "+keyChannel.finishConnect());                                                                           
                             } else if (key.isReadable()) {                                                                                                                                                           
                                  SocketChannel keyChannel = (SocketChannel) key.channel();                                             
                                  String m = Help.read(keyChannel);
                                  display(m);                                                                                                                                                                                                                   
              } catch (IOException e) {                                             
                   e.printStackTrace();                         
         private void display(final String m) {
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        area.append(m+"\n");
                        textFieed.setText("");
         private void sendMessage(final String m) {
              Thread t = new Thread(new Runnable() {               
                   public void run() {                                                                                
                        try {                         
                             Help.write(m, socketChannel);
                        } catch (IOException e) {               
                             e.printStackTrace();
              t.start();                    
         public Client() {
              addWindowListener(new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
                        System.exit(1);
              textFieed.addKeyListener(new KeyAdapter() {
                   public void keyPressed(KeyEvent e) {
                        if (e.getKeyCode()== KeyEvent.VK_ENTER) {
                             String m = textFieed.getText();
                             sendMessage(m);     
              area.setEditable(false);
              getContentPane().add(textFieed, "North");
              getContentPane().add(new JScrollPane(area));
              setBounds(200, 200, 400, 300);
              show();
         private String messageToSend;
         private JTextArea area = new JTextArea();
         JTextField textFieed = new JTextField();
         public static void main(String[] args) {
              Client s = new Client();
              s.work();
    // HELPER CLASS
    package test;
    import java.io.IOException;
    import java.nio.ByteBuffer;
    import java.nio.CharBuffer;
    import java.nio.channels.SocketChannel;
    import java.nio.charset.Charset;
    import java.nio.charset.CharsetDecoder;
    import java.nio.charset.CharsetEncoder;
    public class Help {
         private static Charset charset = Charset.forName("us-ascii");
         private static CharsetEncoder enc = charset.newEncoder();
         private static CharsetDecoder dec = charset.newDecoder();
         private static void log(String m) {
              System.out.println(m);
         public static String read(SocketChannel channel) throws IOException {
              log("*** start READ");                              
              int n;
              ByteBuffer buffer = ByteBuffer.allocate(1024);
              while((n = channel.read(buffer)) > 0) {
                   System.out.println("     adding "+n+" bytes");
              log("  BUFFER REMPLI : "+buffer);
              buffer.flip();               
              CharBuffer cb = dec.decode(buffer);          
              log("  CHARBUFFER : "+cb);
              String m = cb.toString();
              log("  MESSAGE : "+m);          
              log("*** end READ");
              //buffer.clear();
              return m;                    
         public static void write(String m, SocketChannel channel) throws IOException {          
              log("xxx start WRITE");          
              CharBuffer cb = CharBuffer.wrap(m);
              log("  CHARBUFFER : "+cb);          
              ByteBuffer  buffer = enc.encode(cb);
              log("  BUFFER ALLOUE REMPLI : "+buffer);
              int n;
              while(buffer.hasRemaining()) {
                   n = channel.write(buffer);                         
              System.out.println("  REMAINING : "+buffer.hasRemaining());
              log("xxx end WRITE");

    Here's the fix for that old problem. Change the work method to do the following
    - don't register interest in things that can't happen
    - when you connect register based on whether the connection is complete or pending.
    - add the OP_READ interest once the connection is complete.
    This doesn't fix all the other problems this code will have,
    eg.
    - what happens if a write is incomplete?
    - why does my code loop if I add OP_WRITE interest?
    - why does my interestOps or register method block?
    For code that answers all those questions see my obese post Taming the NIO Circus
    Here's the fixed up Client code
    // CLIENT
    package test
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.io.IOException;
    import java.net.InetSocketAddress;
    import java.nio.channels.SelectionKey;
    import java.nio.channels.Selector;
    import java.nio.channels.SocketChannel;
    import java.util.Iterator;
    import java.util.Set;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    public class Client extends JFrame  {
         private String host = "localhost";
         private int port = 5001;
         private SocketChannel socketChannel;
         private Selector selector;
         public void work() {
              try {
                   socketChannel = SocketChannel.open();
                   socketChannel.configureBlocking(false);
                   InetSocketAddress isa = new InetSocketAddress(host, port);
                   socketChannel.connect(isa);
                   selector = Selector.open();
                   int interest = 0;
                   if(socketChannel.isConnected())interest = SelectionKey.OP_READ;
                   else if(socketChannel.isConnectionPending())interest = SelectionKey.OP_CONNECT;
                   socketChannel.register(selector, interest);
                   while(true)
                        int nn = selector.select();
                        System.out.println("nn="+nn);
                        Set keys = selector.selectedKeys();
                        for(Iterator i = keys.iterator(); i.hasNext();)
                             SelectionKey key = (SelectionKey) i.next();
                             i.remove();
                             if (key.isConnectable())
                                  SocketChannel keyChannel = (SocketChannel) key.channel();
                                  System.out.println("Connected "+keyChannel.finishConnect());
                                  key.interestOps(SelectionKey.OP_READ);
                             if (key.isReadable())
                                  SocketChannel keyChannel = (SocketChannel) key.channel();
                                  String m = Help.read(keyChannel);
                                  display(m);
              } catch (IOException e) {
                   e.printStackTrace();
         private void display(final String m) {
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        area.append(m+"\n");
                        textFieed.setText("");
         private void sendMessage(final String m) {
              Thread t = new Thread(new Runnable() {
                   public void run() {
                        try {
                             Help.write(m, socketChannel);
                        } catch (IOException e) {
                             e.printStackTrace();
              t.start();
         public Client() {
              addWindowListener(new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
                        System.exit(1);
              textFieed.addKeyListener(new KeyAdapter() {
                   public void keyPressed(KeyEvent e) {
                        if (e.getKeyCode()== KeyEvent.VK_ENTER) {
                             String m = textFieed.getText();
                             sendMessage(m);
              area.setEditable(false);
              getContentPane().add(textFieed, "North");
              getContentPane().add(new JScrollPane(area));
              setBounds(200, 200, 400, 300);
              show();
         private String messageToSend;
         private JTextArea area = new JTextArea();
         JTextField textFieed = new JTextField();
         public static void main(String[] args) {
              Client s = new Client();
              s.work();

  • The class of the deferred-methods return type "{0}" can not be found.

    I am developing a multilingual portal application.
    I have the method that changes the locale based on user's choice in the bean and the method is being referred to as below.
    <af:selectOneChoice label="Select Language" autoSubmit="true"
    value="#{localeBean.locale}"
    valueChangeListener="localeBean.changeLocale">
    <af:selectItem label="English" value="en" id="si1"/>
    <af:selectItem label="French" value="fr" id="si2"/>
    <af:selectItem label="Dutch" value="nl" id="si3"/>
    </af:selectOneChoice>
    when i try to run the application, i am getting compile time errors as below,
    The class of the deferred-methods return type "{0}" can not be found.
    No property editor found for the bean "javax.el.MethodExpression".
    After going through the discussion forums i learned that the compilation errors can be resolved by setting the <jsp:directive.page deferredSyntaxAllowedAsLiteral="false> at the starting of the page.
    Even after that i am getting the compilation error.
    Any solutions, suggestions or possible approaches would be helpful as i am new to Webcenter Portal development.
    Thanks,

    The error you get points to a problem on the page (somewhere). Switch to source mode and check the right margin if you see orange or red marks. These are pointing to problems (not all are show stoppers, but they give you hints that something is not according to the standard for jsf, jsff, jsp or jspx pages.
    Have you checked that the bean is correctly defined and that it's reachable?
    Start a fresh page and isolate the problem, e.g. build a selectOneChoiuce on the new page (don't copy it as you might copy the error too) and make it work on the new page. Once you have it running you can compare the solution to your not running page.
    Timo

  • Ugent help with return problem

    Hello everyone,
    please can someone help me with this return problem? I'm getting a retrun error problem with this code
    public static float getVitaminPrice()
              for(int j=0;j<Vitamins.length;j++)
                        if(Vitamins[j].getCode().equals(s))
                             return Vitamins[j].getPriceByBox();               
         }

    OK thanks every one but there are things that I don't fully understand yet, just some exprience but not alot, however I'll take all the advise into consideration. I'm a person who most times only learn from examples. I have some classes called VitaminInfo, and one for Customer apart from the one that contains the main method.
    the following code is all that main contains, what I'll like to accomplish is getting back the vitamin price which was already stored in an array based on the vitamin code the user typed in.
    can you help me with that?
    public static void main(String args[])
              for(int j=0;j<Vitamins.length;j++)
                   String vitaminCode = new String(JOptionPane.showInputDialog("Please Enter the Vitamin Code"));
                   String vitaminDesc = new String(JOptionPane.showInputDialog("Please Enter the Vitamin Description"));
                   int vitaminWeight = Integer.parseInt(JOptionPane.showInputDialog("Please Enter the Vitamin Weight"+"/n" + "Vitamin Weight must be between 50 to 500 grams"));     
                   while(vitaminWeight >500 || vitaminWeight< 50){
                        vitaminWeight = Integer.parseInt(JOptionPane.showInputDialog("Please Enter the Vitamin Weight"+"/n" + "Vitamin Weight must be between 50 to 500 grams"));          
                   int vitaminPrice = Integer.parseInt(JOptionPane.showInputDialog("Please Enter the Vitamin Price"));
                   VitaminInfo vita = new VitaminInfo(vitaminCode , vitaminDesc, vitaminWeight, vitaminPrice);
                   Vitamins[j] = vita;           
              for(int j=0;j<Customers.length;j++)
                   String customerName = new String(JOptionPane.showInputDialog("Please Enter a Customer Name"));
                   String customerAddress = new String(JOptionPane.showInputDialog("Please Enter the Customer's Address"));
                   String postalCode = new String(JOptionPane.showInputDialog("Please Enter the Customer's Postal Code"));
                   Customer cust = new Customer(customerName, customerAddress, postalCode);
                   Customers[j] = cust;
              float  vprice = getVitaminPrice();
              String vcode = getVitaminOrderCode();
              int vamount = getVitaminCount(vcode);
              JOptionPane.showMessageDialog(null,"You have ordered " + vamount + " Vitamin (" + vcode + ")."+ " VitaminPrice (" + vprice + ").","Your Order",JOptionPane.INFORMATION_MESSAGE);
              showCatalog();
              showCustomers();
              System.exit(0);
         }

  • Using nio, read method return 0 when readable key was selected.

    I'm so sorry for my ugly English. -_-;;
    Our server(that was designed by me).
    read method return 0 continuously. when readble key was selected.
    So the code fallen into infinite loop. and the server was hanged.
    How can i solve this problem?

    Best to eliminate the most obvious possibilities first. Next question is which JDK are you using? There were bugs in this area in 1.4.0 and 1.4.1.

  • 11g bug(?)--AM client methods returning collections

    Hi all,
    I've got an application module with a method returning a collection of view rows, and I've exposed it on my client interface. The problem is that, in the data control palette, the method's return is just an untyped "element"--there's no declarative way of accessing the view row's data, that I can see.
    I've tried setting the "Element Java Type" in the "Edit Client Interface" dialog (after generating a custom view row class and exposing accessors on a VR client interface), but that seems to have no effect. I've tried right-clicking on the "element" node in the DCP and selecting "Edit Definition," but that doesn't seem to do anything either (no editor appears). Is there a way to return a typed collection (or, even better, a ViewObject with all attributes pertaining thereto) from a service method and have valuable stuff appear in the DCP?

    Couple of comments
    - wrong forum, should go to: JDeveloper and OC4J 11g Technology Preview
    - if the method returns rows, or ideally a VO, why can't this be done through a VO directly ?
    Frank

  • Method return

    I'm having a lot of trouble grasping the concept of method return when making classes and programs that utilize them.
    examples:
    first is a constructor and the method I'm using to retrieve its information
    ==========================
    //constructor in Time class
    public Time(int ho, int mi, int se, boolean a) {
    count++;
    if (ho>12 || mi>59 || se>59)
    {hour=12; minute=00; second=00; am=true;}
    else{
    hour = ho;
    minute = mi;
    second = se;
    am = a;}
    //method in TimeTester test harness
    public static void testConstructor12() {
    String r1, r2, r3, r4;
    r1 = JOptionPane.showInputDialog("Enter Hour (0-12):");
    r2 = JOptionPane.showInputDialog("Enter Minute:");
    r3 = JOptionPane.showInputDialog("Enter Second:");
    r4 = JOptionPane.showInputDialog("0 for PM, 1 for AM:");
    Time a = new Time(Integer.parseInt(r1),
    Integer.parseInt(r2),
    Integer.parseInt(r3),
    Boolean.getBoolean(r4));
    JOptionPane.showMessageDialog(null, "Time is " +
    a.toString());
    ===========================
    in the above I get responses like "Time is Time@269997" and I know that constructors aren't supposed to have return values, so I'm problably hitting a few problems.
    Next is an accessor I can't seem to get to work- all it's supposed to do is return a value without any input.
    ============================
    //accessor in Time class
    public int getHour() {return hour; }
    //method in TimeTester harness
    public static void testGetHour() {
    Time r = new Time();
    int returnedHour = r.getHour();
    JOptionPane.showMessageDialog(null, "Hour is " +
    r.toString());
    ============================
    I get responses similar to the above. Am I doing something wrong with toString()? I'm not even sure how to work toString, quite honestly.
    The ones that have me completely baffled are mutators and methods in the class. I have no idea how to return a value from a mutator and, once returned, how to retrieve it in the harness program.
    =============================
    //method from Time class
    //the method takes in three integers
    //if any of the integers don't fit within parameters, it does not change them
    //if all the integers are correct, the method updates the instance variables
    //the return needs to be all instance variables, updated or not
    public int setTime(int ho, int mi, int se, boolean a) {
    if (ho>12 || mi>59 || se>59)
    {hour=hour; minute=minute; second=second; am=am;}
    else{
    hour = ho;
    minute = mi;
    second = se;
    am = a;}
    return ??????;
    ======================
    I really have no idea how to write the method to retrieve this returned value in the harness program, so I'll spare you that pain.
    Any instructions/tips/hints/explanations? Like I said, I'm really just trying to learn how to get a value to return from a method and how to put that return in a method of my test harness.
    /Cancel_Man

    The line
      boolean cstring = r.setTime();will cause the compiler to look in the Time class for a method like
      boolean setTime() {...}with no arguments. If you have one, great; if not, compile time error.
    The setTime method that you do have returns a boolean and has four arguments.
    So, options (fun and/or insantiy):
    1. You could make a new method that returns a boolean that lets you know if the time was
    successfully re/set. This would probably return a class variable that was set during
    the call to setTime, or,
    2. You could use your four argument setTime method and save the return value, like this
      boolean cstring = r.setTime(7, 15, 39, true);
      System.out.println("The time was " + (cstring == true ? "" : "not") + " changed!");or,
    3. You could call
      r.setTime(7, 15, 39, true);to set the time in the Time class (with no return value) and have the setValue method
    validate the input(as you are trying to do now) and make the announcement that the
    time has been reset or not. There are always other options . . .
    Here's an idea -
    import java.awt.*;
    public class DesignPossibility {
      public static void main(String[] args) {
        ColorState cs = new ColorState(200, 100, 220, 150);
        System.out.println("current color = " + cs.getColor());
        System.out.println("is it transparent? " + cs.isTransparent());
        cs.setColor(100, 200, 255, 190);
        System.out.println("current same as original? " +
                            cs.confirmColor(200, 100, 220, 150));
        cs.setColor(120, 25, 300, 240);
    class ColorState {
      int red, green, blue, alpha;
      public ColorState(int r, int g, int b, int a) {
        if(isValid(r,g,b,a)) {
          this.red   = r;
          this.green = g;
          this.blue  = b;
          this.alpha = a;
        else
          throw new IllegalArgumentException("data out of bounds");
      public Color getColor() {
        return new Color(red, green, blue, alpha);
      public void setColor(int r, int g, int b, int a) {
        if(isValid(r,g,b,a)) {
          this.red   = r;
          this.green = g;
          this.blue  = b;
          this.alpha = a;
        else
          throw new IllegalArgumentException("data out of bounds");
      public boolean confirmColor(int r, int g, int b, int a) {
        if(red == r && green == g && blue == b && alpha == a)
          return true;
        return false;
      public boolean isTransparent() {
        if(alpha < 255)
          return true;
        return false;
      private boolean isValid(int r, int g, int b, int a) {
        if(r < 0 || r > 255 || g < 0 || g > 255 || b < 0 || b > 255 ||
           a < 0 || a > 255)
          return false;
        return true;
    }

  • SimpleDateFormat format() method returning string as ??/??/????

    private String dateTimeFormat(Long time) {
              SimpleDateFormat sf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
              if (time != null) {
                   Date date = new Date(time);
                   return sf.format(date);
              return null;
         }Above function is returning date string as ??/??/???? ??:??:?? on particular system(LINUX-RHEL4). Its Default Locale is en_US.
    What would be the problem ?

    rathi123 wrote:
    Tired running it locally,its working fine. I double checked locale settings of other machine (+locale+ command in Linux) it is also fine.
    I want to know in which exceptional cases SimpleDateFormat format() method returns such (??/??/????) a string ?As I said, it doesn't (If I'm correct). It's more likely that you have an invalid encoding specified somewhere. What happens if you print the value into a log?

  • How to map AM method return values in the bean

    Hello -
    I have this requirement to map AM method return values in the bean as explained below. Please suggest a solution.
    Scenario: I am calling an AM method, which returns a String object on page load.
    AMImpl Method-
    public String getProfileName (){
    return "Profile";
    I wish to catch this retun value in the Bean Variable on page Load. I have created a methodAction biding on page and invokeAction to call this method on Page Load, but I don't know how to catch this value in the bean. Please suggest how to achieve this. Also, I need to achieve this in jsp page. I can't use TaskFlow for this.
    I am using ADF 11g.
    Regards -
    Rohit
    Edited by: Rohit Makkad on Apr 21, 2010 12:23 AM

    Hi, I think there are two ways, from the data control drag n drop the methods return value to the page. This way a binding for that will be created at the page definition eg retVal.
    and in the backing bean you can access it by calling resolveExpression("#{bindings.retVal.inputValue}")
    You can also call your method directly from the backbean
    ((YourAppModuleImpl) getBindings().getDataControl().getApplicationModule()).yourMethod();
    public DCBindingContainer getBindings() {
    return (DCBindingContainer) resolveExpression("#{bindings}");
    I dont know if the second method suits you
    Tilemahos

  • Can a method return a class ?

    hi,
    i have a simple question.
    can a method return class value ?
    in the below script i did'nt understand the commented line.
    package com.google.gwt.sample.stockwatcher.client;
    import com.google.gwt.user.client.rpc.RemoteService;
    import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
    @RemoteServiceRelativePath("login")
    public interface LoginService extends RemoteService {
      public LoginInfo login(String requestUri);  //What is this ? is this a sample of what i asked ?
    }

    The answer to your question is yes.
    The idea is that an object calls a function of another object (passing in objects to the function as arguments) in which that object returns an object (note the arguments or returned value of the function may alternately be primitive types). Each object typically encapsulates data and provides a rich set of functions to the calling object so that calling object doesn't have to deal with the raw data directly. Therefore, not only does the calling object get the data it wants, but also a rich set of functions that can manipulate that data.
    Example:
    Book book = new Book();
    int characterCount = book.getChapter(3).getParagraph(4).getSentence(12).getWord(8).getCharacterCount();
    In the above, each object (Book, Chapter,Paragraph,Sentence,Word) has a rich set of functions it provides to its caller.
    Example: the Sentence Object has a collection of word objects (raw data). Functions it provides to Paragraph object are:
    Word getWord(int index), Words getWords(), int getWordCount().
    If you haven't already done so, I suggest reading a book on Java from cover to cover to pick up such Object Oriented concepts.

  • Custom Login Module - Commit Method return TRUE always?

    Hi,
    I am creating a custom login module for my portal authentication.
    For the login module, should the commit() method always return TRUE?
    The example code on help.sap.com indicates yes to this question.
    However, the JAVA Sun standard indicates that commit should return FALSE if the preceding login method returned FALSE.
    Does the SAP example stray from the SUN standard?  How should I code the commit() method such that it works (Always TRUE, or follow lead of login() method)?
    Regards,
    Kevin

    Hi Kevin,
    I'm actually working with this document: <a href="https://www.sdn.sap.comhttp://www.sdn.sap.comhttp://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/com.sap.km.cm.docs/library/events/webinars/jaas%20login%20module%20development%20on%20webas%20java%20640.pdf#search=%22classloader%20sda%20jar%20reference%22">JAAS Login Modules</a>.
    There is also example code. If it should be ignored they return false, otherwise true (page 32).
    Regards,
    Marcus
    Message was edited by: Marcus Freiheit

  • Abstract class method returning unknown class

    Hi
    I have created an abstract class having one of the method returning an object of a class which is not present at the compiletime. surprisingly the compiler didn't check the availability of the returning class at compilation time. it gave exception of classnotfound when I tried to rum it.
    is there any explanation of it??

    Thanks for the replay. I got the reason.
    actually evenif I did not compile to class file, but I have kept my java file in the same directory. while compiling the abstract class the compiler automatically compiled the reffered class and generated the required class file.
    I got the error when I moved the java file to another dir
    the code is like
    <code>
    abstract class AbstractTest{
         CompleteClass method1(){
              System.out.println("inside method1 of abstract class");
              return new CompleteClass();
         ExtraClass method2(){
                   System.out.println("inside method2 of abstract class");
                   return new ExtraClass(); // this class was not compiled before
         } // only java file is there in the dir
         abstract void demoMethod();
    </code>

  • Can a method return multiple items

    Can a method return more than one thing?
    I want to have a method return a boolean and a String. My method is saying if something is right or wrong, then its saying the reason why.
    help, please.
    Thanx

    Afternoon_Delight wrote:
    My question is:
    Is there a way so that it can be more like this:
    public boolean, String checkValidity (){
    To expand on the previous posts, one way (not saying it's the best one!) is to create an object that combines the information that you want returned:
    public class MyValid
      private boolean valid;
      private String text;
      public MyValid(boolean valid, String text)
        this.valid = valid;
        this.text = text;
      public boolean isValid()
        return valid;
      public String getText()
        return text;
    class DoFoo
      public MyValid checkValidity()
        return new MyValid(false, "Because I said so!");
    }

  • Methods returning String

    Do Methods returning String create a String object in memeory and pass back the reference to the calling Method?
    Thanks

    hmm, i'll take a shot at answering your query - hope this meets your requirement ... Java does manipulate objects by reference, and all object variables are references. So when a method returns a String object (this object would be created within the scope of the method) the object reference is returned to the caller.
    Now the point of confusion usually happens since, Java doesn't pass method arguments by reference; it passes them by value. Java passes object references by value as well. What this means is the references passed to the method are actually copies of the original references.Java copies and passes the reference by value, not the object. Thus, method manipulations on the object reference will alter the objects, since the references point to the original objects. But since the references are copies, swaps will fail.
    Hope the above helps.
    John Morrison

  • Find(String pkey) method returns multiple object of the same row

    I'm not quite sure what i've done or havent done, but I've implemented updating a row using the em.persist(Object) method.....works great, but after i did that a few times the find(String pkey) method returns multiple copies of 1 row in the db
    here are two rows in the db
    personid(PK) firstName lastName
    1234 joe jones
    2345 rachel jones
    when i execute any query looking for people with the last name jones, ie
    select object(p) from Person p where p.lastName='jones'
    it returns multiple objects of each row ie
    1234 joe jones
    1234 joe jones
    1234 joe jones
    1234 joe jones
    2345 rachel jones
    2345 rachel jones
    2345 rachel jones
    2345 rachel jones
    There is only one row for both rachel and joe in the db, but why is the entity manager returning multiple objects of each, and how do i prevent that without using DISTINCT?
    Thanks for the help in advance

    Sorry, i forgot to mention i'm using ejb 3 and jboss

Maybe you are looking for