【发布时间】:2017-08-04 04:30:54
【问题描述】:
我正在尝试使用循环和数组替换两个括号之间的每个实例。 array1a 和 array1b 是括号打开和关闭位置的索引。我想获取两个括号之间的数字并将其加一并替换当前存在的值,但由于字符串文本当前是一个列表(例如“列表项(0)列表项(10)列表项(1023) " 我想使用循环来增加每个值,而不是将括号内的所有值设置为相同的值。我希望这是有道理的!
String text = myString.getText();
for (int x = 0; x < 10; x++) {
array2[x] = text.substring(array1a[x], array1b[x]);
array2[x] = array2[x] + 1;
array3[x] = "(" + array2[x] + ")";
String text2 = text.replaceAll("\\(.*\\)", array3[x]);
myString.setText(text2);
}
完整代码:
public class CreateVideoList extends JFrame implements ActionListener {
JButton play = new JButton("Play Playlist");
JButton addVideo = new JButton("Add Video");
TextArea playlist = new TextArea(6, 50);
JTextField videoNo = new JTextField(2);
private int x = 0;
@Override
public void actionPerformed(ActionEvent e) {
String key = videoNo.getText();
String name = VideoData.getName(key);
String director = VideoData.getDirector(key);
Integer playCount = VideoData.getPlayCount(key);
String text = playlist.getText();
String rating = CheckVideos.stars(VideoData.getRating(key));
String output = name + " - " + director + "\nRating: "
+ rating
+ "\nPlay Count: " + playCount;
String newItem = key + " " + name + " - " + director + " ("
+ playCount + ") " + "\n";
String addToList = "";
String[] array3 = new String[100];
if ("Add Video".equals(e.getActionCommand())) {
if (Character.isDigit(text.charAt(0)) == false) {
playlist.setText("");
}
if (addToList.indexOf(key) == -1) {
addToList += addToList + newItem;
playlist.append(addToList);
array3[x] = key;
x++;
} else if (addToList.indexOf(key) != -1) {
JOptionPane.showMessageDialog(CreateVideoList.this,
"This video is already in the playlist. Please select a"
+ " different video.", "Add to playlist error", JOptionPane.INFORMATION_MESSAGE);
}
}
if ("Play Playlist".equals(e.getActionCommand())) {
Integer length = (text.length());
int counta = 0;
Integer[] array1a = new Integer[100];
Integer[] array1b = new Integer[100];
String strPlayCount = "";
for (x = 0; x < length; x++) {
if (text.charAt(x) == '(') {
counta++;
array1a[counta - 1] = x;
array1a[counta - 1] = array1a[counta - 1] + 1;
}
if (text.charAt(x) == ')') {
array1b[counta - 1] = x;
array1b[counta - 1] = array1b[counta - 1];
}
}
String[] array2 = new String[counta];
String[] array4 = new String[100];
for (int y = 0; y < counta; y++) {
array2[y] = text.substring(array1a[y], array1b[y]);
array2[y] = array2[y] + 1;
playCount = Integer.parseInt(array2[y]);
array4[y] = "(" + array2[y] + ")";
String text2 = text.replaceAll("\\(.*\\)", array4[y]);
playlist.setText(text2);
}
}
}
【问题讨论】:
-
请展示一个完整的代码示例,我们可以编译并获得与您相同的结果。您缺少一个类、一个方法和几个变量声明。
-
只是好奇,你真的想做什么?
-
将数字表示为字符串的目的是什么?你需要重新考虑你的数据结构。
-
我正在尝试制作一个播放列表,当按下“播放”按钮时,我希望每首歌曲的播放次数增加一
-
字符串表示是歌曲状态的渲染。不要将状态存储在字符串中。创建一个带有
int plays字段和toString()方法的 Song 类,该方法返回歌曲标题以及括号中的播放次数。
标签: java arrays loops replace replaceall