Write a program in Java which will search a space delimited

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

Solution

import java.io.*;
import java.util.Scanner;
class myCode
{
static void NumSearch(int sum, String list)
{
// Using split to seperate each number from the list
String[] split = list.split(\"\\\\s+\");
  
//arr is array of input numbers to be searched
int[] arr = new int[split.length];
int i=0,j;
for (String string : split) {
arr[i++] = Integer.parseInt(string);
}
  
for (i=0; i<arr.length; i++)
{
for (j=i; j<arr.length; j++)
{
if((arr[i] + arr[j]) == sum)
System.out.println(i + \" \" + j);
}
}
}

public static void main (String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println(\"Enter the numbers seperated by spaces: \");
String input = sc.nextLine();
  
System.out.println(\"Enter the SUM: \");
int sum = sc.nextInt();
  
System.out.println(\"Indexes :\");
NumSearch(sum,input);
}
}

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

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site