「java字符串放入数组」java怎么定义一个字符串数组
今天给各位分享java字符串放入数组的知识,其中也会对java怎么定义一个字符串数组进行解释,如果能碰巧解决你现在面临的问题,别忘了关注本站,现在开始吧!
本文目录一览:
用java将字符串存入数组
一行存入一个数组吗?
String[] array;
string str;
int i;
FileReader word = new FileReader("word.txt");
BufferedReader br = new BufferedReader(word);
while((str = br.readLine()) != null){
array[i] = str;
i++;
}
JAVA中怎样把用户输入的字符串存入数组中?
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] + " ");
}
}
}
java 如何把string 加入数组中
可以使用split函数将String 字符串转化为数组
split 方法
将一个字符串分割为子字符串,然后将结果作为字符串数组返回。
例子:
String []arr1 = "String".split("");
for(int i = 0;iarr1.length;i++){
System.out.println(arr1[i]);
}
结果:
S
t
r
i
n
g
java字符串放入数组的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于java怎么定义一个字符串数组、java字符串放入数组的信息别忘了在本站进行查找喔。
发布于:2022-12-11,除非注明,否则均为
原创文章,转载请注明出处。