我有一些元素path = [1, 2, 5, 7]
的ArrayList。现在我想从这些元素中获取值:
1,2
2,5
5,7
我为此目的使用了列表迭代器,但我得到的是:
1,2
2,2
5,7
7,7
我看到了这个答案: how to get all combination of an arraylist? 但我不需要像这样的所有组合。
我的代码是:
public class iterator {
public static void main(String[] args){
ArrayList<String> path=new ArrayList<>();
path.add("1");
path.add("2");
path.add("5");
path.add("7");
System.out.println(path);
ListIterator<String> itr = path.listIterator();
while(itr.hasNext())
{
System.out.println(itr.next()+ "," + itr.next());
System.out.println(itr.previous()+ "," + itr.next());
}
}
}
我的问题是如何才能获得所需的结果?
答案 0 :(得分:1)
for (int i = 0; i < path.size() - 1; i++) {
System.out.println(path.get(i) + "," + path.get(i + 1));
}
答案 1 :(得分:1)
您可以尝试使用传统的for循环计数器来实现此目的:
for (int i = 0; i < path.size() - 1; i++) {
System.out.println(path.get(i) + ", " + path.get(i+1));
}
答案 2 :(得分:-1)
问题是ListIterator
获取下一个元素并提升光标。要使用while (itr.nextIndex() + 1 < path.size()) {
System.out.println(itr.next() + "," + itr.next());
itr.previous(); // back up 1 to get the duplicate
}
,您可以这样做:
using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Timers;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
namespace bicmwinservice
{
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
public void OnDebug()
{
OnStart(null);
}
private Timer count;
protected override void OnStart(string[] args)
{
count = new Timer(1 * 60 * 1000); // 5 minutes expressed as milliseconds
count.Elapsed += new ElapsedEventHandler(OnTimerElapsed);
count.AutoReset = true;
count.Start();
}
protected override void OnStop()
{
System.IO.File.Create(AppDomain.CurrentDomain.BaseDirectory + "OnStop.txt");
}
private void OnTimerElapsed(object sender, ElapsedEventArgs e)
{
DateTime time = DateTime.Now;
DateTime date = DateTime.Now;
string connString = "Server=mysql1003.mochahost.com;Database=snowphil_tester;Uid=snowphil_test;password=snowphil_test;";
MySqlConnection conn = new MySqlConnection(connString);
MySqlCommand command = conn.CreateCommand();
StreamReader read = new StreamReader(@"C:\brcode.txt", Encoding.Default);
command.CommandText = "Update branch_monitor SET `date`='" + date.ToString("yyyy'-'MM'-'dd") + "', `time`= '" + time.ToString("HH':'mm':'ss") + "' WHERE branch_code='" + read + "'";
conn.Open();
command.ExecuteNonQuery();
conn.Close();
}
}
}