我是Java的新手。我当前的程序循环遍历一个块,该块要求用户在控制台中输入,直到他们键入的值等于完成。我想将用户键入的每个值存储在一个类属性的数组中。当我尝试附加此数组时,出现错误Error:(59, 18) java: not a statement
。我的代码如下。我将指出代码内部发生错误的行。谢谢你的时间!
package com.example.java;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Welcome to the musical key calculator!");
System.out.println("Enter your notes one at a time.");
System.out.println("Use uppercase letters A-G and # for sharp and b for flat.(Ex. Eb)");
System.out.println("Remember that E# and B# do not exist in music!");
System.out.println("When you have entered all of your notes, type 'done'");
System.out.println("------------------------------------------------------------------");
boolean finished = false;
Scale YourScale = new Scale();
while(finished == false) {
System.out.print("Enter a note: ");
String note = scanner.nextLine();
if (note == "done'") {
finished = true;
} else {
YourScale.addNote(note);
}
}
if(finished == true){
StringBuilder output = new StringBuilder("Your notes are ");
String[] completedNotes = YourScale.notes;
for (int i = 0; i < completedNotes.length; i++) {
output.append(completedNotes[i] + " ");
}
}
}
public static class Scale {
public String[] notes = {};
public void addNote(String note){
notes[] = note; //Error occurs here.
}
}
}
答案 0 :(得分:3)
Java数组是固定长度的,而不是您创建(或填充数组)的方式。我更喜欢使用Collection
之类的,
public List<String> notes = new ArrayList<>();
public void addNote(String note){
notes.add(note);
}
但是,你可以使用Arrays.copyOf(T[], int)
和
public String[] notes = new String[0];
public void addNote(String note){
int len = notes.length;
notes = Arrays.copyOf(notes, len + 1);
notes[len] = note;
}
最后,您不会使用String
==
平等
if (note == "done'") {
应该是
if (note.equals("done")) {
答案 1 :(得分:1)
notes
是一个String数组,这意味着它里面有很多String
个对象。你也将它初始化为一个空数组。数组应该有固定的大小。
//Declare a variable notes, and initialize it as an empty array?
public String[] notes = {};
public void addNote(String note)
{
//This doesn't make sense in java - it's syntax is wrong
notes[] = note;
}
如果你想使用数组,这就是一个例子:
//Declare a variable notes, and initialize it as an array of
//specific size (I used 5 as example)
public String[] notes = new String[5];
public void addNote(String note)
{
//Here you should have some short of counter that counts in which
// position of the array you will save 'note' or just run a 'for'
//loop and the first element that is not initialized can get the note
for (int i = 0; i < notes.length; i++)
if (notes[i] == null)
{
notes[i] = note;
break;
}
}
虽然此方法允许您保存固定大小,这在您的情况下是不可取的,但它使用Array
并且可以帮助您了解如何使用它们。
如果要正确实施,请使用ArrayList
。 ArrayList
是一个数组,您可以在其中添加新元素并将其删除。您可以在线找到大量有关如何使用它们的文档。
答案 2 :(得分:-1)
您正在尝试将String分配给String数组。您可能打算将其添加到数组中。