2013-03-21 180 views
0

有人可以看看我的代碼。 這是一個爲用戶提供所需藝術家的圖表位置的程序。 它並沒有太多的工作。 此外,即時通訊使用while循環im告訴我應該使用if語句。 有人可以向我解釋這一點,並告訴我如何改變它。 我非常新的這個和不太明白 這裏是我的代碼如何更改此while while循環?

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"); 
} 

} 
} 

+2

只需更改單詞'while'這個詞'if'。如果(entry.equalsIgnoreCase(圖表[i ++]))' '將'I ++'放在for循環的末尾 – jonhopkins 2013-03-21 15:17:34

+0

只是將'entry.equalsIgnoreCase(圖表[i])) ' – 2013-03-21 15:17:40

+1

(學習)使用調試器並單步執行代碼,檢查變量。這將提供信息,無論如何您都需要進行真正的調試。 – 2013-03-21 15:20:14

回答

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; 
    } 
} 
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"); 
    } 

    } 
    } 
0

你是已經在for循環中,這就是爲什麼你應該改變「while」作爲「if」的原因。這兩個語句(for和while)用於迭代,直到引發一個條件(在這種情況下,我是< 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; 
    } 
}`