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

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

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 = 0i <arr.lengthi++ ) {

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 = 0j <a.lengthj++)

{

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

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

}

}

}

一行存入一个数组吗?

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++

}

赋给字符数组:char[] chars = s.toCharArray()

赋给字节数组:byte[] bytes = s.getBytes()

因为这里是字节,所以直接打印出来显示不是abcd,先要转换为char类型的再打印


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/bake/11648477.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-17
下一篇 2023-05-17

发表评论

登录后才能评论

评论列表(0条)

保存