有人能帮我吗?我们的老师说他不想在我们的程序中使用数组列表。And only array、for循环和do while。该程序是一个购买程序。(添加项目,记录交易。)这是我想要理解的第一步。
在这个程序中,我想正确地显示项目代码和描述。例如code=123和descrip=,是的。输出显示,Item code = 123, Item descrpition = yeah.,但一旦我说是,我放入另一个,示例代码=456andDesription= oh。输出Item code = 123456, Item description = yeah.oh.
import java.util.Scanner;
public class Apps {
public static void main(String[] args) {
Scanner a = new Scanner(System.in);
String code = "", des = "", ans;
String[] b = new String[1];
String[] aw = new String[1];
int x;
do {
System.out.print("Item code:");
code += "" + a.next();
System.out.print("des:");
des += "" + a.next();
System.out.println("yes or no:");
ans = a.next();
}
while (ans.equals("yes"));
for (x = 0; x < 1; x++) {
b[x] = code;
aw[x] = des;
System.out.println("Item code:" + b[x]);
System.out.println("Item description:" + aw[x]);
}
}
}发布于 2013-10-10 21:27:44
您可以对任意数量的项目使用此代码。它将数据存储在字符串中,并在用户选择no后拆分字符串。
public static void main(String[] args) {
Scanner a = new Scanner(System.in);
String ans;
String itemCounts = "";
String descriptions = "";
do {
System.out.print("Item code:");
itemCounts += "" + a.next() + "\n";
System.out.print("des:");
descriptions += "" + a.next() + "\n";
System.out.println("yes or no:");
ans = a.next();
} while (ans.equals("yes"));
String[] b = itemCounts.split("\n");
String[] aw = descriptions.split("\n");
for (int i = 0; i < b.length; i++) {
System.out.println("Item code:" + b[i]);
System.out.println("Item description:" + aw[i]);
}
}发布于 2013-10-10 21:07:42
next() 不会处理行尾,所以当您再次调用next()时,它会将您之前输入的enter (\n)作为输入。
您应该在每个next()之后调用nextLine() (这样它就会接受前一个\n )。
发布于 2013-10-10 21:14:48
例如,这是可行的:
public static void main(String[] args) {
Scanner a = new Scanner(System.in);
String ans;
int capacity = 100;
String[] b = new String[capacity];
String[] aw = new String[capacity];
int itemCount = 0;
int x;
do {
System.out.print("Item code:");
b[itemCount] = a.next();
System.out.print("des:");
aw[itemCount] = a.next();
System.out.println("yes or no:");
ans = a.next();
itemCount++;
} while (ans.equals("yes"));
for (x = 0; x < itemCount; x++) {
System.out.println("Item code:" + b[x]);
System.out.println("Item description:" + aw[x]);
}
}如果你想确定,用户可以添加“无限”数量项,你必须手动检查itemCount是否小于数组的容量,当它达到时,你必须分配容量更大的新数组,并将值复制到其中。
https://stackoverflow.com/questions/19296519
复制相似问题