Skip to main content

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?


Comments

  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

Post a Comment

Popular posts from this blog

Why is this Javascript much *slower* than its jQuery equivalent?

I have a HTML list of about 500 items and a "filter" box above it. I started by using jQuery to filter the list when I typed a letter (timing code added later): $('#filter').keyup( function() { var jqStart = (new Date).getTime(); var search = $(this).val().toLowerCase(); var $list = $('ul.ablist > li'); $list.each( function() { if ( $(this).text().toLowerCase().indexOf(search) === -1 ) $(this).hide(); else $(this).show(); } ); console.log('Time: ' + ((new Date).getTime() - jqStart)); } ); However, there was a couple of seconds delay after typing each letter (particularly the first letter). So I thought it may be slightly quicker if I used plain Javascript (I read recently that jQuery's each function is particularly slow). Here's my JS equivalent: document.getElementById('filter').addEventListener( 'keyup', function () { var jsStart = (new Date).getTime()...