2013-03-21 123 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; 
    } 
}`