0

有人可以看看我的代码。它是一个程序,可以为用户提供所请求艺术家的图表位置。它不太管用。此外,我使用了一个 while 循环,我告诉我应该使用 if 语句。有人可以向我解释一下,并告诉我如何改变它。我对此非常陌生,不太明白这是我的代码

import java.util.*;

public class chartPosition
{
public static void main (String [] args)
{


    System.out.println("Which artist would you like?");
    String [] chart = { "Rihanna", "Cheryl Cole", "Alexis Jordan", "Katy Perry", "Bruno Mars", "Cee Lo Green",
                                 "Mike Posner", "Nelly", "Duck Sauce", "The Saturdays"};

    String entry = "";
    Scanner kb = new Scanner (System.in);

    entry = kb.nextLine();
    find (entry, chart);
 }

public static void find (String entry,String [] chart) {

int location = -1 ;
for (int i=0;i<chart.length;)
{
    while (entry.equalsIgnoreCase( chart[i])) 

    {
        System.out.println( chart + "is at position " + (i+1) + ".");
        location = i;
        break;
    }
    }
if (location == -1);
{
    System.out.println("is not in the chart");
}

}
}

4

3 回答 3

0
for (int i=0;i<chart.length;)
{
    if (entry.equalsIgnoreCase( chart[i])) 
    {
        System.out.println( chart + "is at position " + (i+1) + ".");
        location = i;
        break;
    }
}
于 2013-03-21T15:19:37.653 回答
0

我将修复放在评论中,查看它们并更改您的代码 =)

import java.util.*;

    public class chartPosition
    {
    public static void main (String [] args)
    {


        System.out.println("Which artist would you like?");
        String [] chart = { "Rihanna", "Cheryl Cole", "Alexis Jordan", "Katy Perry", "Bruno Mars", "Cee Lo Green",
                                     "Mike Posner", "Nelly", "Duck Sauce", "The Saturdays"};

        String entry = "";
        Scanner kb = new Scanner (System.in);

        entry = kb.nextLine();
        find (entry, chart);
     }

    public static void find (String entry,String [] chart) {

    int location = -1 ;

// in for loop there should be defined step, in your case you must change for loop on for (int i=0;i<chart.length;i++), becouse your loop stands on same i value

    for (int i=0;i<chart.length;)
    {

//there should be WHILE changed for IF...the if is condition and while is loop...
        while (entry.equalsIgnoreCase( chart[i])) 

        {
            System.out.println( chart + "is at position " + (i+1) + ".");
            location = i;
            break;
        }
        }
    if (location == -1);
    {
        System.out.println("is not in the chart");
    }

    }
    }
于 2013-03-21T15:22:20.023 回答
0

您已经在 for 循环中,这就是为什么您应该将“while”更改为“if”。两个语句(for 和 while)都用于迭代,直到出现条件(在这种情况下,i < chart.length);另外,我没有测试它,但我认为你的代码不起作用,因为你没有增加 i:

for (int i=0; i<chart.length; i++) 
{

    if (entry.equalsIgnoreCase( chart[i])) 
    {
        System.out.println( chart + "is at position " + (i+1) + ".");
        location = i;
        break;
    }
}`
于 2013-03-21T15:22:25.760 回答