A. 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( "" );
} finally {
try {
if ( scan != null ) {
scan.close();
}
} catch ( Exception e2 ) {
e2.printStackTrace();
}
}
}
}
运行结果为:
请输入个数:2
请输入数字:99
123
99 123
(1)java数组添加字符串数组扩展阅读
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] + " ");
}
}
}
B. java怎么动态的往一个字符串数组里加入字符串元素,
希望把标题能把问题说明白,什么叫动态往一个字符串数据组里加入元素?我可以理解为你new一个数组之后,给这个数组赋值么?比如:
String[]arr=newString[20];
for(inti=0;i<arr.length;i++){
arr[i]="i="+i;//这里是赋值,是这个意思么?
}
C. Java数组拼接字符串
1、代码如下
publicstaticvoidmain(String[]args){
Stringstr[]={"a","b","c","d","e","f","g","h","i"};
System.out.println("字符串数组长度:"+str.length);
System.out.println("拼接后的字符串长度:"+method(str).length());
System.out.println("拼接后的字符串:"+method(str));
}
publicstaticStringmethod(String[]str){
Stringrs="";
for(Strings:str){
rs+=s;
}
returnrs;
}
2、效果如图
D. java 如何把string 加入数组中
可以使用split函数将String 字符串转化为数组
split 方法
将一个字符串分割为子字符串,然后将结果作为字符串数组返回。
例子:
String[]arr1="String".split("");
for(inti=0;i<arr1.length;i++){
System.out.println(arr1[i]);
}
结果:
S
t
r
i
n
g
E. 请问:在JAVA中怎样将一个字符串添加到一个字符串数组里面啊
String[] sport = new String[2];
String word = "word";
String temp = "temp";
sport[0] = word;
sport[1] = temp;
是这样的。
F. 在java中如何定义一个字符串数组
1. java中定义一个字符串数组方式如下,string类型和其他基本类型相似,创建数组有两种方式:
String[] str={"AAA","BBB","CCC"};
String str[]={"AAA","BBB","CCC"};
2.推荐用ArrayList<String> strArray = new ArrayList<String> (); 比较灵活。
3.也可以写为如下格式:class[] array; array = new class[number];其中前半句为声明,后半句为初始化,初始化必须要让编译器知道大小,声明的时候java是不分配内存的,只有创建的时候也就是new的时候才会分配内存。
1.数组是相同数据类型的元素的集合。
2.数组中的各元素的存储是有先后顺序的,它们在内存中按照这个先后顺序连续存放在一起。
3.数组元素用整个数组的名字和它自己在数组中的顺序位置来表示。例如,a[0]表示名字为a的数组中的第一个元素,a[1]代表数组a的第二个元素,以此类推。
4.对于VB的数组,表示数组元素时应注意:下标要紧跟在数组名后,而且用圆括号括起来(不能用其他括号)。下标可以是常量,变量,或表达式,但其值必须是整数。下标必须为一段连续的整数,其最小值成为下界,其最大值成为上界。不加说明时下界值默认为1。
G. java字符串数组增加赋值
你那是语法错误了
,[]里面给的值是数组的长度
是个数值。
string[]
forname
=
new
string[]{"name","nam2","name3"};
H. java 字符数组怎么添加字符串
数组下标是从0开始的
例如数组长度为3,那么下标就是0,1,2
//定义数组length是长度
String
[]a
=
new
String[length]
a[0]="test";
这样就给数组的第一个位置赋值为test