我需要将扫描仪输入分解为单独的单词或空格出现的位置。我有点工作,但如果该行有太多或太少的话,我不能让它工作。请帮我。我有一个星期一的截止日期。这是我目前的代码。
//import java.util.Scanner;
public class durodyne {
public static void main(String[] args) {
String name;
String part1;
String remain1;
String part2;
String part3;
String part4;
String part5;
String part6;
String part7;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter Full Product Name");
name = keyboard.nextLine();
int space=name.indexOf(' ');
part1 = name.substring(0, space);
int space2 = name.indexOf(' ', space + 1);
int space3 = name.indexOf(' ', space2 + 1);
part2 = name.substring(space, space2);
int space4 = name.indexOf(' ', space3 + 1);
int space5 = name.indexOf(' ', space4 + 1);
part3 = name.substring(space2, space3);
int space6 = name.indexOf(' ', space5 + 1);
int space7 = name.indexOf(' ', space6 + 1);
part4 = name.substring(space3, space4);
part5 = name.substring(space4, space5);
part6 = name.substring(space5, space6);
part7 = name.substring(space6, space7);]
}
答案 0 :(得分:1)
//your initialization
List<String> names = new ArrayList<String>();
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter Full Product Name");
name = keyboard.nextLine();
names = Arrays.asList(name.split(" "));
//your code
答案 1 :(得分:0)
String[] nameParts = name.split(" ");
for(String part: nameParts) {
// Use part as required
}
答案 2 :(得分:0)
这是一个例子:假设您将输入存储到名为'blah'的字符串中。你可以这样做:
String blah = "lass ias sfsf sfsfs sfsfs sfsdfs sfsdfs sfsdfs jj";
String [] parts = blah.split(" "); //all parts stored in an array
//Printing the array to show you the array content.
for(String s : parts) {
System.out.println("parts : " + s);
}
答案 3 :(得分:0)
使用类似的东西解析输入字符串会更好。
int wordCount=0;
String words[MaxPossiWords];
int j=0;
char ch;
for(int i=0;i<sent.length();i++) {
ch = sent.charAt(i);
if( ch == ' '){
words[wordCount++]= new String(curCharArray);
j=0;
}
curCharArray[j++]=sent.charAt(i);
}
//finished parsing the line to words.
for(int i=0;i<wordCount;i++)
System.out.println(words[i]+", ");
这种方式使解析有点动态。如果您想要更多动态,可以使用ArrayList
集合代替String
array
字词。
快乐编码。