Can someone help me with this problem.
I have been given to do some coding exercise
I need to do search Array problem Below is the output that i want :
I have a problem where when I put the correct value it will not come out the output I want instead it will come out the output "Player not Found" so how to solve this. I feel like I missed something.
Here my code:
import java.util.Scanner;
public class Main{
public static void main(String[]args){
Scanner sc=new Scanner(System.in);
System.out.println(" Welcome to VictoRoar Information System " );
System.out.println( " ********************");
System.out.print(" Enter n , number of player: ");
int n = sc.nextInt();
//declare,initialize array
String [] name = new String[n];
double [] height = new double[n];
sc.nextLine();
//put input in the array
for (int i=0; i<n;i )
{
System.out.print(" Enter player's name :" );
name[i] = sc.nextLine();
System.out.print(" Enter player's height (cm) :" );
height[i] = sc.nextLine();
}
//search array
System.out.print(" Write the player height that you want to know : ");
double findheight=sc.nextDouble();
boolean noheight = false;
for(int i = 0; i<n; i )
{
if (n == height[i])
{
noheight = true;
System.out.println("Player name " name[i] " with height " height[i] " present at index " i);
}
}
if (noheight == false )
System.out.println("Player not found");
System.out.println("**********************");
}
}
I hope you guys can help me to solve this problem.
CodePudding user response:
You have to use the findheight
instead of n
variable in your if (n == height[i])
condition:
try this it's work :
import java.util.Scanner;
public class Main{
public static void main(String[]args){
Scanner sc=new Scanner(System.in);
System.out.println(" Welcome to VictoRoar Information System " );
System.out.println( " ********************");
System.out.print(" Enter n , number of player: ");
int n = sc.nextInt();
//declare,initialize array
String [] name = new String[n];
double [] height = new double[n];
sc.nextLine();
//put input in the array
for (int i=0; i<n;i )
{
System.out.print(" Enter player's name :" );
name[i] = sc.nextLine();
System.out.print(" Enter player's height (cm) :" );
height[i] = Double.valueOf(sc.nextLine());
}
//search array
System.out.print(" Write the player height that you want to know : ");
double findheight=sc.nextDouble();
boolean noheight = false;
for(int i = 0; i<n; i )
{
if (findheight == height[i])
{
noheight = true;
System.out.println("Player name " name[i] " with height " height[i] " present at index " i);
}
}
if (noheight == false )
System.out.println("Player not found");
System.out.println("**********************");
}
}
result:
Welcome to VictoRoar Information System
********************
Enter n , number of player: 2
Enter player's name :Alex
Enter player's height (cm) :120
Enter player's name :David
Enter player's height (cm) :122
Write the player height that you want to know : 120
Player name Alex with height 120.0 present at index 0
**********************