【发布时间】:2015-01-11 09:20:30
【问题描述】:
如果事先不知道数组的大小,我怎么可能做到这一点?我完全糊涂了。我一直在尝试通过拆分数组来做到这一点,但它应该只使用循环来做到这一点。 这是我尝试过的不同方法,但即使遇到 *,它也不会停止接受用户输入。
第一个版本:
import java.util.*;
public class Number11 {
public static void main(String[] args) {
String line="";
Scanner input = new Scanner(System.in);
System.out.println("You are asked to enter a character one by one and terminate the list with *");
System.out.print("Please enter a character or end it with * : ");
line = input.next();
while(!(line.equals("*")))
{
System.out.print("Please enter a character or end it with * : ");
line = input.next();
if(line.equals("*"))
{
System.exit(0);
int length = line.length();
String [] sequence = new String[length-1];
for(int i=0; i<length; i++)
{
sequence[i] = line;
}
break;
}
}
}
}
第二个:
import java.util.*;
public class Number11 {
public static void main(String[] args) {
String [] character = new String[20];
Scanner input = new Scanner(System.in);
for(int i=0; i < character.length; i++)
{
System.out.print("Enter a character or press * to stop: ");
character[i] = input.next();
while(!(character[i].equals("*")))
{
System.out.print("Enter another character or press * to stop: ");
character[i] = input.next();
}
}
}
}
您的帮助将不胜感激。谢谢。
【问题讨论】:
-
不,它不能重复,因为我在另一个问题中找不到我的答案。这根本不是我要寻找的东西。
-
阅读答案并将其与您的代码进行比较。另请注意,调用
character并不会使其只是一个字符;它仍然是一个字符串。 -
How can i possibly do this without knowing the size of the array beforehand这个问题如何与http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java重复 -
正是@Saif。我的问题是基于数组的。我不想在这里比较字符串。我关心的不是字符串,而是在不知道数组大小的情况下使用循环和数组。我已经解决了另一个问题,但仍然找不到我的答案。
-
我也不认为它是一个纯粹的重复,所以我会继续进行重新投票。我强烈鼓励你修复你的代码之前我投了票,所以你使用
.equals而不是==,因为另一种方式不是去上班。完成后(希望在接下来的 20 分钟内)联系我。