我需要在数组中打印字符串的特定索引,例如
String[] words = {car, bike, truck};
打印words[0][0]
,结果为c
并打印words[0][1] = a
。
此外,我必须从文本文件中读取数组。到目前为止我将打印数组的第一个单词。
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
import java.io.FileNotFoundException;
public class DemoReadingFiles
{
public static void main (String[] args)
{
String[] words = readArray("words.txt");
System.out.println(words[0]);//i can get it to print specific elements
}
public static String[] readArray(String file)
{
int ctr = 0;
try
{
Scanner s1 = new Scanner(new File(file));
while (s1.hasNextLine())
{
ctr = ctr + 1;
s1.next();
}
String[] words = new String[ctr];
Scanner s2 = new Scanner(new File(file));
for (int i = 0; i < ctr; i = i + 1)
{
words[i] = s2.next();
}
return words;
}
catch (FileNotFoundException e)
{
}
return null;
}
}
答案 0 :(得分:0)
public static void main(String[] args) {
String[] words = {"cars", "bike", "truck"};
System.out.println("Specific character print:" + words[0].charAt(0));
System.out.println("Multi character selection printed as follows:" + words[0].substring(1, words[0].length() - 1));
}
输出:
Specific character print:c
Multi character selection printed as follows:ar