0

for example, i have the string "12,456,544,233" from the user input,

I want to take each number that is separated by commas and push each one into a Stack, converting it to an int in the process because the Stack is . (array implementation of a stack by the way)

So 12 would be at 0, 456 at 1, 544 at 2, etc...

I KNOW I have to use the Integer class to parse, but just not sure how to setup the loop to do everything, if i didn't provide enough info, ask and I will do so! thanks.

The code I tried:

String input = scan.nextLine();

    stack.push(Integer.parseInt(String.valueOf(input.charAt(2))));
4

2 回答 2

1

听起来像家庭作业。所以只是给出一些提示

  1. 您可以使用String.split方法将字符串拆分为以逗号分隔的标记
  2. 现在遍历拆分后得到的数组并推送到堆栈。

注意,如果它真的是一个家庭作业,那么您可能需要实施自己的拆分

于 2013-10-07T16:23:23.117 回答
0

这是拆分字符串的方法

String string = "12,456,544,233";
String[] individualStrings = string.split(",");

split()方法 围绕给定正则表达式的匹配拆分此字符串。

接下来,您可以对字符串数组进行交互并将每个元素转换为整数。

for(int i = 0; i < individualStrings.length; i++)
{
  int m = Integer.parseInt(individualStrings[i]);
}

干杯!!

于 2013-10-07T16:23:33.133 回答