所以我有一个长度为4的数组.当我将它递增1并且数字大于数组的长度时,我希望它能翻转.
例如:
current_index = 3;
current_index++;
//current_index is now 0 again
current_index = 3;
current_index += 2;
//current_index would be 1
current_index = 0;
current_index--;
//current_index would be 3
Run Code Online (Sandbox Code Playgroud)
我正在用if-else这样解决它
if (current_index == textviewlist.length + 1)
current_index = 0;
else if (current_index == textviewlist.length + 2)
current_index = 1;
else if (current_index == -1)
current_index = 3;
Run Code Online (Sandbox Code Playgroud)
但我觉得这不是一个合适的解决方案,或"好"的代码.
编辑:我尝试了你的建议,但显然java表现出奇怪的负数.当我尝试
current_index = (current_index - 1) % textviewlist.length;
Run Code Online (Sandbox Code Playgroud)
Java取索引"0",将其减1(" - 1")然后
-1 % 4 = -1
Run Code Online (Sandbox Code Playgroud)
我预计它会是3,见Wolfram Alpha:-1 mod 4 …
每次按下按钮时,我都会在文本文件中附加一行.目前我每次按下按钮时都这样做:
...
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(f, true));
if (fileIsNew == true)
bw.write(firstLine);
bw.write(string);
bw.close();
Log.v("file", "written to file:" + f.getAbsolutePath());
} catch (IOException e) {
Log.v("IOException", e.toString());
}
...
Run Code Online (Sandbox Code Playgroud)
因为bufferedWriter的目的是缓冲输出,所以我认为在每一行之后关闭bufferedwriter并不是一个好主意,对吗?
那我该bw.close()什么时候打电话?我应该在某种形式下创建新的BufferedWriter init()吗?我认为每次按下按钮时创建一个新的BufferedWriter效率很低.