[英]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.