JAVA中怎样把用户输入的字符串存入数组中?


char []a=new char[100];
然后提示用户输入字符串,如:adfefsxxasd
然后怎么存入数组中?

import java.util.Scanner;

import java.util.InputMismatchException;

public class saveInputToArr {

public static void main(String[] args) {

Scanner scan = null;

try {

scan = new Scanner(System.in);

System.out.print( "请输入个数: " );

int inputNum = scan.nextInt();

if( inputNum <= 0 ) {

throw new Exception( "输入有误" );

}

System.out.println( "请输入数字: " );

int arr[] = new int[inputNum];

int num = 0;

int count = 0;

while( count < inputNum ) {

num = scan.nextInt();

arr[count] = num;

count++;

}

for( int i = 0; i < arr.length; i++ ) {

System.out.print( arr[i] + "  " );

}

} catch ( Exception e ) {

throw new InputMismatchException( "\u8f93\u5165\u6709\u8bef\u002c\u0020\u8bf7\u91cd\u65b0\u8f93\u5165" );

} finally {

try {

if ( scan != null ) {

scan.close();

} catch ( Exception e2 ) {

e2.printStackTrace();

}

}

}

}

运行结果为:

请输入个数: 2

请输入数字:99

123

99 123

扩展资料

Java从输入中读取一个数组

import java.util.Scanner;

public class Main { 

public static void main(String[] args) {

// TODO Auto-generated method stub

Scanner sc = new Scanner(System.in);

String str = sc.nextLine().toString();//用nextLine()可以读取一整行,包括了空格,next()却不能读取空格

String arr[] = str.split(" ");//拆分字符串成字符串数组

int a[] = new int[arr.length];

for(int j = 0; j < a.length; j++)

{

a[j] = Integer.parseInt(arr[j]);

System.out.print(a[j] + " ");

}

}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2019-07-12

1、新建一个java文件,不妨命名为arrayTest.java

2、用代码编辑器打开,开始编写代码

3、完成代码编写,准备进入下一步

4、打开控制台程序

5、切换到代码所在目录

5、用java命令编译arrayTest.java,即输入javac arrayTest.java

6、接着进入下一步

7、编译成功后会在之前的代码目录产生一个arrayTest.class文件

8、接下来运行arrayTest。在命令行中输入:java arrayTest然后回车

9、程序运行后会显示:Please input a string and end it by Enter key:输入你想要字符串然后回车即可,接下来你就会看到程序运行结果了

本回答被网友采纳
第2个回答  推荐于2017-09-08
可以先全部读入,作为字符串str,然后将字符从字符传中取出,一个个的赋值给数组chs[].如下程序所示:
import java.util.Scanner;
public class StrIn
{
public static void main(String[] args)
{
char[] chs = new char[100];
String str;
Scanner sc = new Scanner(System.in);
System.out.print("请输入字符串:");
str = sc.nextLine();
System.out.println();
for (int i = 0; i < str.length(); i ++)
{
chs[i] = str.charAt(i);
System.out.print(chs[i] + " ");
}
}
}

参考资料:JAVA API文档,及其他书籍

本回答被提问者采纳
第3个回答  2007-03-23
先取字符串的长度,再用for(int i=0;i<字符串.length;i++)一个一个给数组附值.
相似回答