有人可以幫我解決這個問題。
我被要求做一些編碼練習
我需要做搜索陣列問題下面是我想要的輸出:

我有一個問題,當我輸入正確的值時,它不會出現我想要的輸出,而是會出現輸出“找不到播放器”,所以如何解決這個問題。我覺得我錯過了什么。
這是我的代碼:
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("**********************");
}
}
我希望你們能幫助我解決這個問題。
uj5u.com熱心網友回復:
你必須在你的條件下使用findheight而不是n變數if (n == height[i]):
試試這個它的作業:
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("**********************");
}
}
結果:
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
**********************
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/440670.html
下一篇:從陣列中獲取資料屬性
