有人可以看看我的代码。 该程序为用户提供所请求艺术家的图表位置。 它不是很有效。 另外,我使用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");
}
}
}
答案 0 :(得分: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;
}
}
答案 1 :(得分: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");
}
}
}
答案 2 :(得分:0)
你已经在for循环中,这就是为什么你应该改变“if”的“while”。两个语句(for和while)用于迭代,直到引发条件(在这种情况下,i&lt; 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;
}
}`