Friday, February 10, 2012

Java code to find a particular number from a given list of numbers


How would you solve the following java problem?



Write code that finds a particular number from a given list of numbers which are stored as strings?



I assume you would have to convert the strings to ints or doubles, using double.parse double or int.parse int and then do some kind of binary search maybe?



Here's what I have tried so far



import java.io.*; import java.util.Scanner;



public class FindNum {




static int nElems;
static String[] array;

public static void main (String[] args) throws IOException {
File testFile = new File("X:\\numbers.txt");

Scanner in = new Scanner(System.in);
System.out.println("What number would you like to find?");
nElems = in.nextInt();
while(true){
System.out.println("Binary search");
array = new String[nElems];
getContents(testFile);//loads the file



That's just basic input to get the access the file witht the list of numbers wondering how would I go about coding a binary search method on the list of strings using the parse method to change them to ints first?

1 comment:

  1. Instead of converting string to int or double, load it in to array list, then you use collection api, to search a number from a list. the java collection api itself provides some searching technique like binary search.

    for more information refer the below links

    http://www.java-examples.com/perform-binary-search-java-arraylist-example

    http://www.java-examples.com/search-element-java-arraylist-example

    ReplyDelete