[英]How can i change out this while loop for an if?
有人可以看看我的代码吗? 它是一个程序,可向用户提供所请求艺术家的排行榜位置。 它不是很有效。 另外,即时消息使用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");
}
}
}
for (int i=0;i<chart.length;)
{
if (entry.equalsIgnoreCase( chart[i]))
{
System.out.println( chart + "is at position " + (i+1) + ".");
location = i;
break;
}
}
我将修复程序放入注释中,查看它们并更改您的代码=)
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");
}
}
}
您已经在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;
}
}`
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.