In: Computer Science
Write a program in Java which will search a space delimited string of integers for the two values which add up to a provided amount. The program must output th following text to the command prompt/console: Indexes: { Index of first number} { Index of second number} Example One: NumSerach( 100, " 5 75 25"); output: Indexes: 1 2
/*
* To change this license header, choose License Headers in Project
Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package javaapplication2;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Namburi Ramesh
*/
public class JavaApplication2 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
JavaApplication2 j=new JavaApplication2();
j.NumSearch(100, "10 20 30 40 50 60 50");
}
public void NumSearch(int a,String b){
StringTokenizer st=new StringTokenizer(b," "); //StringTokeniser
class has methods to get substring separated by delimiters in
string
int[] c=new int[st.countTokens()+1]; //this array will hold the
numbers passed in the string
int count=0;
while(st.hasMoreTokens()){ //runs until st has more tokens
c[count]=Integer.parseInt(st.nextToken()); // get the substring
from st and convert to int and store it in array0
count++;
}
//This below nested loop adds every element with other elements and
compares with int a and prints those indexes if the addition is
equal to a
for(int i=0;i<c.length;i++){
for(int j=i+1;j<c.length;j++){
if(c[i]+c[j]==a){
System.out.println(i+" "+j);
}
}
}
}
}