编写一个读取字符序列的程序,直到遇到符号*并使用数组-JAVA

时间:2015-01-11 09:20:30

标签: java arrays loops

如果事先不知道数组的大小,我怎么能这样做呢?我完全糊涂了。我一直试图通过拆分数组来做到这一点,但是它应该通过仅使用循环来实现。 这是我尝试过的不同方式,但即使遇到*,它也不会停止用户输入。

第一版:

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

    }
 }

}

非常感谢您的帮助。感谢。

2 个答案:

答案 0 :(得分:0)

使用集合frameworks。稍微研究一下here: 使用下面的ArrayList

的示例
public static void main(String[] args) {

    ArrayList<String>  character = new ArrayList<String>();

     Scanner input = new Scanner(System.in);
     String temp;
     while(true)
     {
         System.out.print("Enter a character or press * to stop: ");
         temp=input.next();
         character.add(temp);

         if(temp.equals("*"))
         {
            break;
         }

     }
  }

如果你完全使用它们,你也不需要两个循环。

答案 1 :(得分:0)

你可以使用这样的循环实现这个:

public static void main(String[] args) {

    String line="";
    char ch = 0;
    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 and Press Enter key or end it with * : ");
    while(ch!='*')
    {
        ch=input.next().charAt(0);
        if(ch=='*')
        {
            System.out.print(line);
            break;
        }
        else
            line+=ch;
    }

}