Write a Java program that stores 5 values in an array. Ask the user to input a value to look for. Perform a Linear Search to look for the inputted value.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
int value;
int [] array = {10, 5, 21, 16, 11};
Scanner input = new Scanner(System.in);
System.out.println("Enter the searched value");
value=input.nextInt();
for (int i = 0; i < array.length; i );
{
if (array [i] == value);
{
System.out.println(value " is found at Index " (i 1));
{
if (i == array.length);
System.out.println(value " is not in the list");
}
}
}
}
}
I am not able to detect the errors in it. (PS I'm a beginner) Thank you so much for helping.
CodePudding user response:
try
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
int value;
int [] array = {10, 5, 21, 16, 11};
Scanner input = new Scanner(System.in);
System.out.println("Enter the searched value");
value = input.nextInt();
input.close();
int i = 0;
while( i < array.length )
{
if (array[ i ] == value)
{
System.out.println(value " is found at Index " (i 1));
}
i ;
}
if (i == array.length)
{
System.out.println(value " is not in the list");
}
}
}
CodePudding user response:
Try this
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
int value;
int[] array = {10, 5, 21, 16, 11};
Scanner input = new Scanner(System.in);
System.out.println("Enter the searched value");
value = input.nextInt();
boolean isValueFound = false;
int index = 0;
for (int i = 0; i < array.length; i ) {
if (array[i] == value) {
isValueFound = true;
index = i;
}
}
if (isValueFound) {
System.out.println(value " is found at Index " (index));
} else {
System.out.println(value " is not in the list");
}
}
}
CodePudding user response:
You have the general concept. Keep the search and the reporting separate. Use the iteration to find the index and then report what you find after the iteration is complete.
public static void main(String[] args) {
// gather the inputs
int value = getUserInput();
int[] array = {10, 5, 21, 16, 11};
// search for value in the array
int valueIndex = -1; // negative index is a flag
for (int index = 0 ; index < array.length ; index) {
if (value == array[index]) {
valueIndex = index;
break;
}
}
// report our finding!
if (valueIndex < 0) {
System.out.println(value " is not in the list");
} else {
System.out.println(value " was found at index " valueIndex);
}
}