New to Java: Populating Arrays and searching

I am really stuck. I need to know how to search for an array that is already populated. The user will type in a string, and the string must match with one of the populated array. What is the best way to go?

You mean you want to know if a String matches an element in an array? If so, turn the array into a List and use contains();
import java.util.*;
String [] stringArray = // already populated
List stringList = Arrays.asList(stringArray);
now test:
String s = // input from user
if (stringList.contains(s)) {
// found a match

Similar Messages

  • TS1347 when i add new contact to my iphone , and search for it i did't find it but it store in my phone and apperars when called me or i write the no

    when i add new contact to my iphone , and search for it i did't find it but it store in my phone and apperars when called me or i write the no

    In the Contacts app, select "Groups" in the upper left hand corner.
    Then select all the groups that are desired to be displayed.
    Select Done.
    Now search for the contact(s) in question.  Do they appear now?

  • New in java server pages and j2ee

    hello, im new in jsp and servlet..im new in j2ee..
    my OS is Windows XP ..
    i dont know how to start learning...
    i installed J2EE development kit.. also.. i start the server from (Start Default Server)
    i dont know how to create jsp files. and java files..
    where to write the java code and where to write html code..
    also.. where should i save these files.. i mean.. in which directory?
    i want to know how can i start the servlet and JSP.. someone told me.. to put http://localhost:8080.. when i put this in the browser.. it works correctly..
    can anybody help me????

    http://java.sun.com/learning/training/index.html

  • How to ask for an array and how to save the values

    I'm supposed to be learning the differences between a linear search and a binary search, and the assignment is to have a user input an array and search through the array for a given number using both searches. My problem is that I know how to ask them how long they want their array to be, but I don't know how to call the getArray() method to actually ask for the contents of the array.
    My code is as follows:
    import java.util.Scanner;
    import java.util.ArrayList;
    public class Main
        private static Scanner input = new Scanner(System.in);
        public static void main (String args[])
            //creates ArrayList
            int List[];
            System.out.println("How long would you like the array to be?");
            int arrayLength = input.nextInt();
            //Initializes array list
            List = new int [arrayLength];
            System.out.println("Please enter the first value of the array");
        public static void getArray(int List[], int arrayLength)
            for(int i=0; i < arrayLength; i++) {
                 System.out.println("Enter the next value for array");
                 List[i] = input.nextInt();
         public static void printArray(int List[])
             for(int i=0; i < List.length; i++)
                 System.out.print(List[i] + " ");
    public class search
        public static int binarySearch(int anArray[], int first, int last, int value)
            int index;
            if(first > last) {
                index = -1;
            else {
                int mid = (first + last)/2;
                if(value == anArray[mid]) {
                    index = mid; //value found at anArray[mid]
                else if(value < anArray[mid]) {
                    //point X
                    index = binarySearch(anArray, first, mid-1, value);
                else {
                    //point Y
                    index = binarySearch(anArray, mid+1, last, value);
                } //end if
            } //end if
            return index;
        //Iterative linear search
        public int linearSearch(int a[], int valueToFind)
            //valueToFind is the number that will be found
            //The function returns the position of the value if found
            //The function returns -1 if valueToFind was not found
            for (int i=0; i<a.length; i++) {
                if (valueToFind == a) {
    return i;
    return -1;

    I made the changes. Two more questions.
    1.) Just for curiosity, how would I have referenced those methods (called them)?
    2.) How do I call the searches?
    import java.util.Scanner;
    import java.util.ArrayList;
    public class Main
        private static Scanner input = new Scanner(System.in);
        public static void main (String args[])
            //creates ArrayList
            int List[];
            System.out.println("How many values would you like the array to have?");
            int arrayLength = input.nextInt();
            //Initializes array list
            List = new int [arrayLength];
            //Collects the array information
            for(int i=0; i < arrayLength; i++) {
                 System.out.println("Enter a value for array");
                 List[i] = input.nextInt(); 
            //Prints the array
            System.out.print("Array: ");
            for(int i=0; i < List.length; i++)
                 System.out.print(List[i] + " ");
            //Asks for the value to be searched for
            System.out.println("What value would you like to search for?");
            int temp = input.nextInt();
            System.out.println(search.binarySearch()); //not working
    }

  • Creating or updating a java.sql.array object

    I've created an oracle object table which contains a nested table. I've published these types using JPublisher and can extract an object from the table and read the data both the object and the nested table. (The nested table is typed within the java class as java.sql.array).
    Now I'd like to create an object in java and add it to the database. Populating the object attributes and writing them to the database table is not a problem, but how do I populate java.sql.array and write it to the nested table?
    Werner Reiche

    Array sqlArray = rs.getArray("LINES");
    ResultSet data = sqlArray.getResultSet();
    while (data.next()) {
    System.out.println(data.getString(1));
    .getString(1)); // the line's index #
    System.out.println(data.getString(2));
    .getString(2)); // the line's string value
    } I wonder what this would do
    String[] values = (String[]) sqlArray.getArray();

  • Difference between Java Server Faces and Apache Struts

    Hi ,
    I'm quite new to Java Server Faces and Apache Struts. I wonder are they two comparable Frameworks for web presentation?
    And can anybody elaborate please, if they differ in what aspects?
    Thanks
    Jaffar Shaikh

    Here are slides from a presentation by Craig McClanahan that compares them (I believe you can search for other articles on this topic): http://www.baychi.org/calendar/files/Struts-And-Faces/Struts-And-Faces.pdf

  • New on java Card

    HI all !
    I'm new on java card technology and would like to compil my first cardlet :)
    I'm getting problem while charging my cardlet into my chip, Eclipse does not generate the cap file.
    I'm using Eclipse 3.3.1 and JCop Tools 3.2.7.
    I created a Java card projet and a Java card Applet file and here is my code :
    package pck_calculator;
    import javacard.framework.APDU;
    import javacard.framework.Applet;
    import javacard.framework.ISO7816;
    import javacard.framework.ISOException;
    import javacard.framework.Util;
    public class Calculator extends Applet
         private static final byte[] CALC = { //
         (byte) 0x63, // c
         (byte) 0x61, // a
         (byte) 0x6c, // l
         (byte) 0x63, // c
         (byte) 0x75, // u
         (byte) 0x6c, // l
         (byte) 0x61, // a
         (byte) 0x74, // t
         (byte) 0x72, // r
         (byte) 0x69, // i
         (byte) 0x63, // c
         (byte) 0x65  // e
         }; // Tableau de bytes (code ASCII) qui va être renvoyé si on envoit l'INS 0x00
         //methode d'installation de l'applet dans la carte
         public static void install(byte[] bArray, short bOffset, byte bLength)
              // Enregistrement de l'applet (méthode register()) auprès du JCRE
              // Lors de la création de l'applet (new)
              new Calculator().register(bArray, (short) (bOffset + 1), bArray[bOffset]);
         public void process(APDU apdu)
              //pour verifier que cette applet n'est pas entrain d'être sélectionné
              if (selectingApplet())
                   return;
              //réception de la commande APDU
              byte[] buf = apdu.getBuffer();
              switch (buf[ISO7816.OFFSET_INS])
                   case (byte) 0x00 :
                        Util.arrayCopy(CALC, (short) 0, buf, (short) 0, (short) CALC.length);
                        apdu.setOutgoingAndSend((short) 0, (short) CALC.length);
                        return;
                        // Ici, on copie le tableau (défini en haut) dans le buffer et on l'envoi sur la sortie
                        // En précisant la taille du champ de données
                   case (byte) 0x01 :
                        buf[0] = (byte) (buf[ISO7816.OFFSET_P1] + buf[ISO7816.OFFSET_P2]);
                        // Ici, on additionne P1 et P2
                        break;
                   case (byte) 0x02 :
                        //Soustraction de P1 et P2
                        buf[0] = (byte) (buf[ISO7816.OFFSET_P1] - buf[ISO7816.OFFSET_P2]);
                        break;
                   case (byte) 0x03 :
                        //Multiplication
                        buf[0] = (byte) (buf[ISO7816.OFFSET_P1] * buf[ISO7816.OFFSET_P2]);
                        break;
                   case (byte) 0x04 :
                        //Division
                        if (buf[ISO7816.OFFSET_P2] == 0)
                             //Test de la division par 0
                             ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2);
                             //Envoie de l'exception "mauvais paramètres"
                        buf[0] = (byte) (buf[ISO7816.OFFSET_P1] / buf[ISO7816.OFFSET_P2]);
                        break;
                   case (byte) 0x05 :
                        //Somme du champ de données de la commande APDU
                        short n = (short) (ISO7816.OFFSET_CDATA + apdu.setIncomingAndReceive());
                        byte sum = 0;
                        while (n-- > ISO7816.OFFSET_CDATA)
                             sum += buf[n];
                        buf[0] = sum;
                        break;
                   default :
                        //Envoie de l'exception "mauvais champ INS"
                        ISOException.throwIt(ISO7816.SW_INS_NOT_SUPPORTED);
              //Pour tous les cas la réponse APDU a des données de 1 octet
              //Sauf pour le cas INS = 00
              apdu.setOutgoingAndSend((short) 0, (short) 1);
    }It's a simple calculator :)
    To compile, I use right click on the projet => debug as... => Open debug dialog
    and I set the correct AID of the package and class in the "Package upload".
    Then I start debug and here is the problem :
    The .cap is never created (cm> upload -d -b 250 path/file.cap)
    The comunication with the card is ok because it answers some request like /card-info.
    Do you have any idea about a step I forget or anything else ??
    Thanks a lot :)

    At first, I tried java compiler 5.0 as the over topic and could get a cap file but I think it is not usable.
    I changed to your configuration as compiler 1.3 and class compatibility 1.2 and problem is still the same.
    cm>  /term "tcl:10"
    --Opening terminal
    /card -a a000000003000000 -c com.ibm.jc.CardManagerresetCard with timeout: 0 (ms)
    --Waiting for card...
    ATS=0D 77 80 81 02 00 73 C8 40 13 00 90 00             .w....s.@....
    ATS: FSC=128, DS=1/DR=1 (symmetrical), FWI=8 (FWT=0.077 sec), SFGI=1, NAD=1/CID=0, Hist=0073C84013009000
    => 00 A4 04 00 08 A0 00 00 00 03 00 00 00 00          ..............
    (19856 usec)
    <= 6F 19 84 08 A0 00 00 00 03 00 00 00 A5 0D 9F 6E    o..............n
        06 40 51 42 04 22 00 9F 65 01 FF 90 00             .@QB."..e....
    Status: No Error
    cm>  set-key 255/1/DES-ECB/404142434445464748494a4b4c4d4e4f 255/2/DES-ECB/404142434445464748494a4b4c4d4e4f 255/3/DES-ECB/404142434445464748494a4b4c4d4e4f
    cm>  init-update 255
    => 80 50 00 00 08 CE F3 CB 4A D0 3D 1C 37 00          .P......J.=.7.
    (69487 usec)
    <= 00 00 43 52 00 32 72 90 68 81 FF 02 00 45 46 93    ..CR.2r.h....EF.
        AD C1 8D 1D 50 D5 2C F4 14 89 82 3E 90 00          ....P.,....>..
    Status: No Error
    cm>  ext-auth plain
    => 84 82 00 00 10 E5 7B 57 1A 9D EA 91 DF AD 6E 18    ......{W......n.
        A3 B7 B8 64 73                                     ...ds
    (66179 usec)
    <= 90 00                                              ..
    Status: No Error
    cm>  delete -r 012345678900
    => 80 E4 00 80 08 4F 06 01 23 45 67 89 00 00          .....O..#Eg...
    (22288 usec)
    <= 6A 88                                              j.
    Status: Reference data not found
    jcshell: Error code: 6a88 (Reference data not found)
    jcshell: Wrong response APDU: 6A88
    Ignoring expected error
    cm>  upload -d -b 250 "workspace\calc\bin\pck_calculator\javacard\pck_calculator.cap"
    => 80 E6 02 00 13 06 01 23 45 67 89 00 08 A0 00 00    .......#Eg......
        00 03 00 00 00 00 00 00 00                         .........
    (25722 usec)
    <= 00 90 00                                           ...
    Status: No Error
    => 80 E8 00 00 FA C4 82 01 A1 01 00 1F DE CA FF ED    ................
        02 02 04 00 01 06 01 23 45 67 89 00 0E 70 63 6B    .......#Eg...pck
        5F 63 61 6C 63 75 6C 61 74 6F 72 02 00 21 00 1F    _calculator..!..
        00 21 00 0B 00 0B 00 2E 00 0E 00 C8 00 19 00 13    .!..............
        00 00 00 67 02 69 00 02 00 01 00 0C 01 01 00 04    ...g.i..........
        00 0B 01 03 01 07 A0 00 00 00 62 01 01 03 00 0B    ..........b.....
        01 07 01 23 45 67 89 00 01 00 08 06 00 0E 00 00    ...#Eg..........
        00 80 03 00 FF 00 07 01 00 00 00 1C 07 00 C8 00    ................
        01 10 18 8C 00 09 7A 05 30 8F 00 08 3D 8C 00 0A    ......z.0...=...
        18 1D 04 41 18 1D 25 8B 00 07 7A 05 23 18 8B 00    ...A..%...z.#...
        05 60 03 7A 19 8B 00 01 2D 1A 04 25 73 00 8E 00    .`.z....-..%s...
        00 00 05 00 13 00 2B 00 38 00 45 00 52 00 6A 7B    ......+.8.E.R.j{
        00 03 03 1A 03 7B 00 03 92 8D 00 00 3B 19 03 7B    .....{......;..{
        00 03 92 8B 00 02 7A 1A 03 1A 05 25 1A 06 25 41    ......z....%..%A
        5B 38 70 5E 1A 03 1A 05 25 1A 06 25 43 5B 38 70    [8p^....%..%C[8p
        51 1A 03 1A 05 25 1A 06 25 45 5B 38 70 44 1A 00    Q....%..%E[8pD..
    (1746 msec)
    <= 6A 80                                              j.
    Status: Wrong data
    jcshell: Error code: 6a80 (Wrong data)
    jcshell: Wrong response APDU: 6A80
    Unexpected error; aborting execution
    {code}                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Search given string array and replace with another string array using Regex

    Hi All,
    I want to search the given string array and replace with another string array using regex in java
    for example,
    String news = "If you wish to search for any of these characters, they must be preceded by the character to be interpreted"
    String fromValue[] = {"you", "search", "for", "any"}
    String toValue[] = {"me", "dont search", "never", "trip"}
    so the string "you" needs to be converted to "me" i.e you --> me. Similarly
    you --> me
    search --> don't search
    for --> never
    any --> trip
    I want a SINGLE Regular Expression with search and replaces and returns a SINGLE String after replacing all.
    I don't like to iterate one by one and applying regex for each from and to value. Instead i want to iterate the array and form a SINGLE Regulare expression and use to replace the contents of the Entire String.
    One Single regular expression which matches the pattern and solve the issue.
    the output should be as:
    If me wish to don't search never trip etc...,
    Please help me to resolve this.
    Thanks In Advance,
    Kathir

    As stated, no, it can't be done. But that doesn't mean you have to make a separate pass over the input for each word you want to replace. You can employ a regex that matches any word, then use the lower-level Matcher methods to replace the word or not depending on what was matched. Here's an example: import java.util.*;
    import java.util.regex.*;
    public class Test
      static final List<String> oldWords =
          Arrays.asList("you", "search", "for", "any");
      static final List<String> newWords =
          Arrays.asList("me", "dont search", "never", "trip");
      public static void main(String[] args) throws Exception
        String str = "If you wish to search for any of these characters, "
            + "they must be preceded by the character to be interpreted";
        System.out.println(doReplace(str));
      public static String doReplace(String str)
        Pattern p = Pattern.compile("\\b\\w+\\b");
        Matcher m = p.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (m.find())
          int pos = oldWords.indexOf(m.group());
          if (pos > -1)
            m.appendReplacement(sb, "");
            sb.append(newWords.get(pos));
        m.appendTail(sb);
        return sb.toString();
    } This is just a demonstration of the technique; a real-world solution would require a more complicated regex, and I would probably use a Map instead of the two Lists (or arrays).

  • New to Java and I guess a scope question.

    Hello and thank you for taking the time to read this. I am not a real programmer, everything I have ever done was a total hack, or written without a full understanding of how I was doing it. One thing about Java is that you might have like 20 classes (or interfaces or whatever), and that code is "all over" (which means to me not on one big page). My comment statements may look odd to others, but the program is for me alone and well, only I need to understand them.
    Through some hacking, I wrote/copied/altered the following code:
    import java.io.*;
    import java.util.*;
    public class readDataTest
         public static void main(String[] args)
              /* get filename from user, will accept and work with drive name
              e.g. c:\java\data.txt, if it is the same drive as the compiler
              does not need the directory. however, it always needs the extension.
              userInput is created by me, File, StringBuffer, BufferReader
              are part of java.io */
              userInput fileinput = new userInput();
              String filename = fileinput.getUserInput("What is the file's name");
              File file = new File(filename);
              StringBuffer contents = new StringBuffer();
              BufferedReader reader = null;
              //try to read the data into reader
              try
                   reader = new BufferedReader(new FileReader(file));
                   String text = null;
                   while((text = reader.readLine()) !=null)
                        //create a really big string, seems inefficient
                        contents.append(text).append(System.getProperty("line.separator"));
                   //close the reader
                   reader.close();
              catch (IOException e)
                   System.out.println(e);
              //take the huge string and parse out all the carriage returns
              String[] stringtext = contents.toString().split("\\r");
              //create mmm to get take the individual string elements of stringtext
              String mmm;
              //create ccc to create the individual parsed array for the ArrayList
              String[] ccc = new String[2];
              //create the arraylist to store the data
              ArrayList<prices> data = new ArrayList<prices>();
              /*go through the carriage returned parsed array and feed the data elements
              into appropriate type into the arraylist, note the parse takes the eof as an
              empty cell*/
              //prices pricestamp = new prices();
              for(int c=0; c < stringtext.length-1; c++)
                   prices pricestamp = new prices();
                   mmm=stringtext[c];
                   /*trims the extra text created by the carriage return, if it is not
                   trimmed, the array thinks its got an element that is "" */
                   mmm=mmm.trim();
                   //whitespace split the array
                   ccc=mmm.split("\\s");
                   pricestamp.time=Integer.parseInt(ccc[0]);
                   pricestamp.price=Double.parseDouble(ccc[1]);
                   //System.out.println(ccc[1]);
                   data.add(pricestamp);
                   //System.out.println(data.get(c).price);
                   //pricestamp.time=0;
                   //pricestamp.price=0;
                   pricestamp=null;
              //pricestamp=null;
              //System.out.println(pricestamp.price);
              System.out.println(data.size());
              double totalprice=0;
              for(int c=0; c<data.size(); c++)
                   //System.out.println(data.get(c).price);
                   totalprice+=data.get(c).price;
              System.out.println("This is the total price: " + totalprice);
    public class prices
         int time;
         double price;
    public class evenOdd
         public int isEven(double number)
              int evenodd;
              double half = number/2;
              int half2 = (int) half;
              if(half == half2)
                   evenodd = 1;
              else
                   evenodd = 0;
              return evenodd;
    So the program works and does what I want it to do. I am very sure there are better ways to parse the data, but thats not my question. (For argument's sake lets assume the data that feeds this is pre-cleaned and is as perfect as baby in its mother's eyes). My question is actually something else. What I originally tried to do was the following:
    prices pricestamp = new prices();
              for(int c=0; c < stringtext.length-1; c++)
                   mmm=stringtext[c];
                   mmm=mmm.trim();
                   ccc=mmm.split("\\s");
                   pricestamp.time=Integer.parseInt(ccc[0]);
                   pricestamp.price=Double.parseDouble(ccc[1]);
                   data.add(pricestamp);
    however, when I did this, this part:
    for(int c=0; c<data.size(); c++)
                   //System.out.println(data.get(c).price);
                   totalprice+=data.get(c).price;
              System.out.println("This is the total price: " + totalprice);
    would only use the last price recorded in data. So each iteration was just the last price added to totalprice. I spent hours trying to figure out why and trying different ways of doing it to get it to work (as you probably can tell from random commented out lines). I am completely dumbfounded why it doesn't work the other way. Seems inefficient to me to keep creating an object (I think thats the right terminology, i equate this to dim in VB) and then clearing it, instead of just opening it once and then just overwriting it). I really would appreciate an explanation of what I am missing.
    Thank you.
    Rich

    prices pricestamp = new prices();
    for(int c=0; c < stringtext.length-1; c+)
    mmm=stringtext[c];
    mmm=mmm.trim();
    ccc=mmm.split("\\s");
    pricestamp.time=Integer.parseInt(ccc[0]);
    pricestamp.price=Double.parseDouble(ccc[1]);
    data.add(pricestamp);
    }This is definitely wrong. You have only created one instance of pricestamp and you just keep overwriting it with new values. You need to put the new inside the loop to create a new instance for each row.
    Also I doubt you really mean .length - 1, that doesn't include the last row.
    Style wise:
    Class names should always start with capital letters, fields and variable always with lower case letters. These conventions aren't imposed by the compiler but are established practice, and make your code a lot easier to follow. Use "camel case" to divide you names into words e.g. priceStamp
    When using single letter names for integer indices people tend to expect i through n. This is a historical thing, dating back to FORTRAN.

  • Help with arrays and Exception in thread "main" java.lang.NullPointerExcept

    Hi, I have been having trouble all day getting this array sorted and put into a new array. I think it is something simple with my nested loops in sortCityArray() that is causing the problem. Any help would be greatly appreciated. The error is thrown on line 99 at Highway.sortCityArray(Highway.java:99)
    import java.util.Scanner;
    import java.io.*;
    import java.util.Arrays;
    public class Highway
    private String[] listOfCities=new String[200];
    private City[] cityArray=new City[200];
    private City[] sortedCityArray=new City[200];
    private String city="";
    private String city2="";
    private String fileName;
    private City x;
    private int milesToNextCity;
    private int milesAroundNextCity;
    private int speedToNextCity;
    public Highway(String filename)
    String fileName=filename;//"I-40cities.txt";
           File myFile = new File(fileName);
           try {
           Scanner scan=new Scanner(myFile);
           for(int i=0; scan.hasNextLine(); i++){
           String city=scan.nextLine();
           String city2=scan.nextLine();
           int milesToNextCity=scan.nextInt();
           int milesAroundNextCity=scan.nextInt();
           int speedToNextCity=scan.nextInt();
                   if(scan.hasNextLine()){
              scan.nextLine();
           cityArray=new City(city,city2,milesToNextCity,milesAroundNextCity,speedToNextCity);
    // System.out.println(cityArray[i].getCity());
    // System.out.println(cityArray[i].getNextCity());
    // System.out.println(cityArray[i].getLengthAB());
    // System.out.println(cityArray[i].getLengthAroundB());
    // System.out.println(cityArray[i].getSpeedAB());
    catch (Exception e) {
    System.out.println(e);
    //return cityArray;
    /*public City[] doCityArray(){
    File myFile = new File(fileName);
    try {
    Scanner scan=new Scanner(myFile);
    for(int i=0; scan.hasNextLine(); i++){
    String city=scan.nextLine();
    String city2=scan.nextLine();
    int milesToNextCity=scan.nextInt();
    int milesAroundNextCity=scan.nextInt();
    int speedToNextCity=scan.nextInt();
         if(scan.hasNextLine()){
              scan.nextLine();
    cityArray[i]=new City(city,city2,milesToNextCity,milesAroundNextCity,speedToNextCity);
    // System.out.println(cityArray[i].getCity());
    // System.out.println(cityArray[i].getNextCity());
    // System.out.println(cityArray[i].getLengthAB());
    // System.out.println(cityArray[i].getLengthAroundB());
    // System.out.println(cityArray[i].getSpeedAB());
    catch (Exception e) {
    System.out.println(e);
    return cityArray;
    public City[] sortCityArray(){
    sortedCityArray[0]=new City(cityArray[0].getCity(),cityArray[0].getNextCity(),cityArray[0].getLengthAB(),cityArray[0].getLengthAroundB(),cityArray[0].getSpeedAB());
    for(int j=0; j<cityArray.length; j++ )
         for(int i=0; i<cityArray.length ;i++)
              if(sortedCityArray[j].getNextCity().equals(cityArray[i].getCity())){
              sortedCityArray[j+1]=new City(cityArray[i].getCity(),cityArray[i].getNextCity(),cityArray[i].getLengthAB(),cityArray[i].getLengthAroundB(),cityArray[i].getSpeedAB());
              break;
    /*     for(int i=0; i<cityArray.length ;i++)
              if(sortedCityArray[j].getNextCity().equals(cityArray[i].getCity())){
              sortedCityArray[j+1]=new City(cityArray[i].getCity(),cityArray[i].getNextCity(),cityArray[i].getLengthAB(),cityArray[i].getLengthAroundB(),cityArray[i].getSpeedAB());
         break;
              for(int i=0; i<cityArray.length ;i++)
              if(sortedCityArray[j].getNextCity().equals(cityArray[i].getCity())){
              sortedCityArray[j+1]=new City(cityArray[i].getCity(),cityArray[i].getNextCity(),cityArray[i].getLengthAB(),cityArray[i].getLengthAroundB(),cityArray[i].getSpeedAB());
         break;
              for(int i=0; i<cityArray.length ;i++)
              if(sortedCityArray[j].getNextCity().equals(cityArray[i].getCity())){
              sortedCityArray[j+1]=new City(cityArray[i].getCity(),cityArray[i].getNextCity(),cityArray[i].getLengthAB(),cityArray[i].getLengthAroundB(),cityArray[i].getSpeedAB());
         break;
    //     j++;
    System.out.println(sortedCityArray[0].getCity());
    System.out.println(sortedCityArray[0].getNextCity());
    System.out.println(sortedCityArray[0].getLengthAB());
    System.out.println(sortedCityArray[0].getLengthAroundB());
    System.out.println(sortedCityArray[0].getSpeedAB());
    System.out.println(sortedCityArray[1].getCity());
    System.out.println(sortedCityArray[1].getNextCity());
    System.out.println(sortedCityArray[1].getLengthAB());
    System.out.println(sortedCityArray[1].getLengthAroundB());
    System.out.println(sortedCityArray[1].getSpeedAB());
    System.out.println(sortedCityArray[2].getCity());
    System.out.println(sortedCityArray[2].getNextCity());
    System.out.println(sortedCityArray[2].getLengthAB());
    System.out.println(sortedCityArray[2].getLengthAroundB());
    System.out.println(sortedCityArray[2].getSpeedAB());
    System.out.println(sortedCityArray[3].getCity());
    System.out.println(sortedCityArray[3].getNextCity());
    System.out.println(sortedCityArray[3].getLengthAB());
    System.out.println(sortedCityArray[3].getLengthAroundB());
    System.out.println(sortedCityArray[3].getSpeedAB());
    System.out.println(sortedCityArray[4].getCity());
    System.out.println(sortedCityArray[4].getNextCity());
    System.out.println(sortedCityArray[4].getLengthAB());
    System.out.println(sortedCityArray[4].getLengthAroundB());
    System.out.println(sortedCityArray[4].getSpeedAB());
    return cityArray;
    /*public String[] listOfCities(){
    File myFile = new File("I-40cities.txt");
    try {
    Scanner scan=new Scanner(myFile);
    for(int i=0; scan.hasNextLine(); i++){
         String city=scan.nextLine();
         city=city.trim();
    scan.nextLine();
    scan.nextLine();
         listOfCities[i]=city;
         System.out.println(listOfCities[i]);
    catch (Exception e) {
    System.out.println(e);
    return listOfCities;
    public static void main(String args[]) {
    Highway h = new Highway("out-of-order.txt");
    h.sortCityArray();

    the ouput is perfect according to the print lines if I use (increase the int where j is in the loop manually by one) :
         for(int i=0; i<cityArray.length ;i++)
              if(sortedCityArray[0].getNextCity().equals(cityArray.getCity())){
              sortedCityArray[0+1]=new City(cityArray[i].getCity(),cityArray[i].getNextCity(),cityArray[i].getLengthAB(),cityArray[i].getLengthAroundB(),cityArray[i].getSpeedAB());
              break;
         for(int i=0; i<cityArray.length ;i++)
              if(sortedCityArray[1].getNextCity().equals(cityArray[i].getCity())){
              sortedCityArray[1+1]=new City(cityArray[i].getCity(),cityArray[i].getNextCity(),cityArray[i].getLengthAB(),cityArray[i].getLengthAroundB(),cityArray[i].getSpeedAB());
         break;
              for(int i=0; i<cityArray.length ;i++)
              if(sortedCityArray[2].getNextCity().equals(cityArray[i].getCity())){
              sortedCityArray[2+1]=new City(cityArray[i].getCity(),cityArray[i].getNextCity(),cityArray[i].getLengthAB(),cityArray[i].getLengthAroundB(),cityArray[i].getSpeedAB());
         break;
              for(int i=0; i<cityArray.length ;i++)
              if(sortedCityArray[3].getNextCity().equals(cityArray[i].getCity())){
              sortedCityArray[3+1]=new City(cityArray[i].getCity(),cityArray[i].getNextCity(),cityArray[i].getLengthAB(),cityArray[i].getLengthAroundB(),cityArray[i].getSpeedAB());
         break;
    But I cant do this for 200 elements. Are the loops nested right?
    Edited by: modplan on Sep 22, 2008 6:49 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Copy array and sort the numbers in the new array

    Hi!
    I have an array containing some digits where some of the digits are zeros. I want to copy the digits to another array but the zeros (well, I actually want to copy the zeros as well but I want to have them in the end of the new array).
    I suppose I need an if-statement that checks if the old array contains any zeros and in that if-statement copy the content to the new array and put the zeros in the end.
    This is my code so far and I don�t know how to go on from here:
    int[] new_array = new int[array.length];
              for (int i = 0; i < array.length; i++)
                   if (array[i] > 0)
                        new_array[i] = array;
                        new_array = array;
                   System.out.print(new_array[i] + " ");

    Roxxor wrote:
    I think I know how to do it but only if I can catch the digits bigger than zero.
    My code below just checks if there are positive digits and if there are, the whole old array is copied to the new one.Yes. Don't do that, you can see it's wrong.
    So my problem is that I don�t know how to catch the digits bigger than zero and copy them. Is there any built in java keyword that catches signs, number etc?
    if (array>=0)
         new_array[i] = array[i];
         new_array = array;
    Yes, there is such a keyword. And you are already using it correctly in your code. You are already testing if the array entry is bigger than zero. Your only problem is, you don't know what to do when it is. But now you've been given two hints about what to do.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Passing Array of java objects to and from oracle database-Complete Example

    Hi all ,
    I am posting a working example of Passing Array of java objects to and from oracle database . I have struggled a lot to get it working and since finally its working , postinmg it here so that it coudl be helpful to the rest of the folks.
    First thinsg first
    i) Create a Java Value Object which you want to pass .
    create or replace and compile java source named Person as
    import java.sql.*;
    import java.io.*;
    public class Person implements SQLData
    private String sql_type = "PERSON_T";
    public int person_id;
    public String person_name;
    public Person () {}
    public String getSQLTypeName() throws SQLException { return sql_type; }
    public void readSQL(SQLInput stream, String typeName) throws SQLException
    sql_type = typeName;
    person_id = stream.readInt();
    person_name = stream.readString();
    public void writeSQL(SQLOutput stream) throws SQLException
    stream.writeInt (person_id);
    stream.writeString (person_name);
    ii) Once you created a Java class compile this class in sql plus. Just Copy paste and run it in SQL .
    you should see a message called "Java created."
    iii) Now create your object Types
    CREATE TYPE person_t AS OBJECT
    EXTERNAL NAME 'Person' LANGUAGE JAVA
    USING SQLData (
    person_id NUMBER(9) EXTERNAL NAME 'person_id',
    person_name VARCHAR2(30) EXTERNAL NAME 'person_name'
    iv) Now create a table of Objects
    CREATE TYPE person_tab IS TABLE OF person_t;
    v) Now create your procedure . Ensure that you create dummy table called "person_test" for loggiing values.
    create or replace
    procedure give_me_an_array( p_array in person_tab,p_arrayout out person_tab)
    as
    l_person_id Number;
    l_person_name Varchar2(200);
    l_person person_t;
    l_p_arrayout person_tab;
    errm Varchar2(2000);
    begin
         l_p_arrayout := person_tab();
    for i in 1 .. p_array.count
    loop
         l_p_arrayout.extend;
         insert into person_test values(p_array(i).person_id, 'in Record '||p_array(i).person_name);
         l_person_id := p_array(i).person_id;
         l_person_name := p_array(i).person_name;
         l_person := person_t(null,null);
         l_person.person_id := l_person_id + 5;
         l_person.person_name := 'Out Record ' ||l_person_name ;
         l_p_arrayout(i) := l_person;
    end loop;
    p_arrayout := l_p_arrayout;
         l_person_id := p_arrayout.count;
    for i in 1 .. p_arrayout.count
    loop
    insert into person_test values(l_person_id, p_arrayout(i).person_name);
    end loop;
    commit;
    EXCEPTION WHEN OTHERS THEN
         errm := SQLERRM;
         insert into person_test values(-1, errm);
         commit;
    end;
    vi) Now finally create your java class which will invoke the pl/sql procedure and get the updated value array and then display it on your screen>Alternatively you can also check the "person_test" tbale
    import java.util.Date;
    import java.io.*;
    import java.sql.*;
    import oracle.sql.*;
    import oracle.jdbc.driver.*;
    import java.text.DateFormat;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    public class ArrayDemo
    public static void passArray() throws SQLException
    Connection conn = getConnection();
    ArrayDemo a = new ArrayDemo();
    Person pn1 = new Person();
    pn1.person_id = 1;
    pn1.person_name = "SunilKumar";
    Person pn2 = new Person();
    pn2.person_id = 2;
    pn2.person_name = "Superb";
    Person pn3 = new Person();
    pn3.person_id = 31;
    pn3.person_name = "Outstanding";
    Person[] P_arr = {pn1, pn2, pn3};
    Person[] P_arr_out = new Person[3];
    ArrayDescriptor descriptor =
    ArrayDescriptor.createDescriptor( "PERSON_TAB", conn );
    ARRAY array_to_pass =
    new ARRAY( descriptor, conn, P_arr);
    OracleCallableStatement ps =
    (OracleCallableStatement )conn.prepareCall
    ( "begin give_me_an_array(?,?); end;" );
    ps.setARRAY( 1, array_to_pass );
         ps.registerOutParameter( 2, OracleTypes.ARRAY,"PERSON_TAB" );
         ps.execute();
         oracle.sql.ARRAY returnArray = (oracle.sql.ARRAY)ps.getArray(2);
    Object[] personDetails = (Object[]) returnArray.getArray();
    Person person_record = new Person();
    for (int i = 0; i < personDetails.length; i++) {
              person_record = (Person)personDetails;
              System.out.println( "row " + i + " = '" + person_record.person_name +"'" );
                        public static void main (String args[]){
         try
                             ArrayDemo tfc = new ArrayDemo();
                             tfc.passArray();
         catch(Exception e) {
                        e.printStackTrace();
              public static Connection getConnection() {
         try
                             Class.forName ("oracle.jdbc.OracleDriver");
                             return DriverManager.getConnection("jdbc:oracle:thin:@<<HostNanem>>:1523:VIS",
                             "username", "password");
         catch(Exception SQLe) {
                        System.out.println("IN EXCEPTION BLOCK ");
                        return null;
    and thats it. you are done.
    Hope it atleast helps people to get started. Comments are appreciated. I can be reached at ([email protected]) or [email protected]
    Thanks
    Sunil.s

    Hi Sunil,
    I've a similar situation where I'm trying to insert Java objects in db using bulk insert. My issue is with performance for which I've created a new thread.
    http://forum.java.sun.com/thread.jspa?threadID=5270260&tstart=30
    I ran into your code and looked into it. You've used the Person object array and directly passing it to the oracle.sql.ARRAY constructor. Just curios if this works, cos my understanding is that you need to create a oracle.sql.STRUCT out of ur java object collection and pass it to the ARRAY constructor. I tried ur way but got this runtime exception.
    java.sql.SQLException: Fail to convert to internal representation: JavaBulkInsertNew$Option@10bbf9e
                        at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
                        at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:146)
                        at oracle.jdbc.oracore.OracleTypeADT.toDatum(OracleTypeADT.java:239)
                        at oracle.jdbc.oracore.OracleTypeADT.toDatumArray(OracleTypeADT.java:274)
                        at oracle.jdbc.oracore.OracleTypeUPT.toDatumArray(OracleTypeUPT.java:115)
                        at oracle.sql.ArrayDescriptor.toOracleArray(ArrayDescriptor.java:1314)
                        at oracle.sql.ARRAY.<init>(ARRAY.java:152)
                        at JavaBulkInsertNew.main(JavaBulkInsertNew.java:76)
    Here's a code snippet I used :
    Object optionVal[] =   {optionArr[0]};   // optionArr[0] is an Option object which has three properties
    oracle.sql.ArrayDescriptor empArrayDescriptor = oracle.sql.ArrayDescriptor.createDescriptor("TT_EMP_TEST",conn);
    ARRAY empArray = new ARRAY(empArrayDescriptor,conn,optionVal);If you visit my thread, u'll see that I'm using STRUCT and then pass it to the ARRAY constructor, which works well, except for the performance issue.
    I'll appreciate if you can provide some information.
    Regards,
    Shamik

  • New to Java, new to array(compacting ,removing etc..)

    hey everybody,
    bear with me im new to JAVA, currently taking my first course in Programming, and one of the assignments is on arrays. my question is i need to compact the array so if an element is removed then i would have to shift each one down so it doesnt waste memory and also have the array packed which means i have to keep all valid elements in the beginning and nulls at the end any suggestions or examples?. i didnt write any part of the code yet so im not sure if my description helps...
    BTW any suggestions as to where i can get practice in Java Programming? my hws sorta help but its not enough practice, and this is all new to me so any suggestions either websites or books?

    thanks for the replies and the link, i think i sorta got an idea how to shift
    well the thing with the array is that if the user inputs a number that is the same as an element in the array i need to remove it, well i guess you can say i have a problem starting the code does any one have a simple example on arrays? and im still confused about creating temps also, can anyone explain in what situation do we have to create temp variables? from my understanding is it only when you wanna change the size of the array? thanks in advance

  • Yet another case of new type[array] and parametrized type

    I suppose this is an often asked question, to which I seem not to be able to find a simple answer. I know of the "incompatibility" of arrays and generics, and yet in such a seemingly simple case I run into a mystery, or a compiler bug. Look at this warning:
    Set<Integer>  C[];
    foo/bar/some.java:1148: warning: [unchecked] unchecked conversion
    found   : java.util.HashSet[]
    required: java.util.Set<java.lang.Integer>[]
                    C=new HashSet[H-L+1];So far so good, but precisely this *"Set<type>[]"* does not exists, does it? When I try to add a parametrized type to this new statement, compiler says:
    Set<Integer>  C[];
    foo/bar/some.java:1148: generic array creation
                    C=new HashSet<Integer>[H-L+1];
                      ^
    1 errorIn a regular case we can easy deal with the "unchecked" warnings, e.g. Effective Java 2nd Ed, Item 24 discusses this, but all this seem to be ignoring this case. When generic array creation is not permitted, than why this warning stating that *"java.type<typeparam>[] required"* appear, and how to resolve this for safety and correctness? Of course, I can still ignore the warning and do a few instanceof checks and casts, like before, but I am really curious how to transfer this into the new paradigm.
    As much generics improve and help in many cases, I regret their arcane complexity. To paraphrase C.A.R. Hoare, the Java language itself becomes now the problem, not its solution.
    Thomas

    I wonder if we have someplace recent measure just an array stack against a current implementation of a set in Java? In JDK1.4 I remember array was several times faster, 350% faster if my memory serves me, and I do have the classic "inner loop" operation, very repetitive. I can live with the warning, what's the problem?
    Of course all this are considerations fully aside of the issue at hand, that the JDK1.6 compiler prints a nonsense warning message that a parametrized array is expected, what is in fact illegal in current implementation of generics. Which is in my eyes severely faulty, but that would be yet another assault on the Braha Ivory Tower, wouldn't it?
    Thomas

  • New to java: have to develop for palm, symbian and pocket pc

    Hello,
    I am fairly new to Java. After a long time of searching for a technology which allows it to develop an application for Palm OS, Symbian OS and Pocket PC I am curious if one can do this with Java. I searched the Palm and Symbian homepages and found that those OSes can handle MIDlets. I could not found if they also can handle full Java-applications. For the Pocket PC I could not found a solution to run Java applications or MIDlets.
    My questions:
    - is it possible to run Java applications on Palm, Symbian an Pocket PC?
    - if yes, which tools are the best to use? (SUN One?)
    - is it possible to write "real" applications (for instance a spreadsheet) as MIDlet or can one use "real"-Java to develop applications for Palm/Symbian/Pocket PC?
    Sorry if this questions sound a little stupid an thanks for every help/suggestion!
    Kind regards,
    Martijn

    Normaly such devices only know MIDlets. This is becaus they do not have the power of a PC. In addition to that they are to different in hardware so an other API is to use.
    I think it is notpossible to write a VM to do the same as a PC now.
    Hope this will help you.

Maybe you are looking for

  • PP - creation of planned order

    HI, I have a  finished product  say F001 which has the semi finished product -  say-  a001 and a001 has another semi finished product - aa001 aa001 has another semi finished product - aaa001 Now When I run MRP for finished product F001 and after that

  • How do I find S/N if the sticker has gone..(and the box)

    the title pretty much says it all..... Recently, I am seeing some artifacts with my CF280x... also trying to get fast boot with 8.1 feature working.. but it says GOP not found on cards.... After reading the forum, I gotta get S/N for getting the righ

  • How can i retrieve photos that have been lost when I've synced my new iPhone to my old one

    I upgraded my iPhone 5 to an iPhone 6 yesterday, and got carried away taking photos. I've just synced it with my iTunes so i could get all my apps etc from my 5 onto my new 6. It has deleted all the photo's I'd taken- Can and How can I get them back?

  • インストールでエラーが発生しました. adobe cs 5.5 master collection [ERROR: Install MSI payload failed with error: 1620]

    Adobe creative suite 5.5 Master collection をインストールしようとしたところ.2枚目のCDをいれたところで.下記のようなエラーが出て.インストールできません. (エラー内容が多いので.最下部に表示します) どのようにしたら.インストールできますでしょうか? 再起動し.何度.インストールしても.同じ結果となります. なお.パソコンの環境は以下のとおりです. 宜しくお願いします ■■■■■■■インストール環境■■■■■ Windows 7 Professio

  • How do I get it to show the date & time.

    How do I get it to show the date & time at all times. I don't want to have to click on the day & time to get the date. In the OS 10.4 I could at least get it in the "analog" format. Under leopard it just show a little clock that can't be read. I just