如何使用scan类或其他java中的String类读取和使用String数组
我可以将String读入数组,如下所示
arr[0]="apple";
arr[1]="mango";
arr[2]="banana";
.
.
.
很快
但是通过使用扫描仪类如何可能请告诉我
以及java String arrays中的每个“for each”的任何帮助......
答案 0 :(得分:0)
要读入字符串数组,然后阅读您可以使用的填充数组:
public static void main(String [] args){
// to populate string array`enter code here`
Scanner sc = new Scanner(System.in);
int length = 10, pos = -1;
String arr[] = new String[length];
while(++pos < length){
System.out.print("Enter string : ");
arr[pos] = sc.nextLine();
}
// to read the already populated string array1
for(String s: arr){
System.out.println(s);
}
}
答案 1 :(得分:0)
编程从控制台读取特定数量的元素并将其写在控制台上。
public class Test {
public static void main(String args[]) {
System.out.println("Enter string array size");
Scanner in = new Scanner(System.in);
int i = in.nextInt();
String[] arr = new String[i];
for (int j = 0; j < i; j++) {
System.out.println("Enter next element");
arr[j] = in.next();
}
for (String s : arr) {
System.out.println("Next element[" + s+"]");
}
}
}
答案 2 :(得分:0)
import java.util.Scanner;
public class StringRWrite {
public static void main(String[] args) {
Scanner sc1=new Scanner(System.in);
System.out.println("enter the length of String array");
int n=sc1.nextInt();
String[] larray=new String[n];
for(int i=0;i<n;i++){
System.out.println("enter the "+(i+1)+" String :");
larray[i]=sc1.next();
}
System.out.println("Strings Entered by user:");
for(String s:larray){
System.out.println(s);
}
}
}
答案 3 :(得分:-1)
import java.util.Scanner;
public class StringReadAndWrite {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("enter the length of String array");
int n=sc.nextInt();
String[] sarray=new String[n];
for(int i=0;i<n;i++){
System.out.println("enter the "+(i+1)+" String :");
sarray[i]=sc.next();
}
System.out.println("Strings Entered by user:");
for(String s:sarray){
System.out.println(s);
}
}
}
答案 4 :(得分:-2)
import java.util.Scanner;
public class BasketballPlayers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("enter the number of basketball players");
int numberOfPlayers = input.nextInt();
String[] playersArray =new String[numberOfPlayers];
for(int i=0;i< numberOfPlayers;i++){
System.out.println("enter the "+(i+1)+" String :");
playersArray[i]= input.next();
}
System.out.println("BasketBall Player names:");
for(String s:playersArray){
System.out.println(s);
}
}
}