有没有办法限制 do-while 循环中的一行代码只完成一次?
Is there a way to restrict a line of code in a do-while loop to only complete once?
我的代码中有一个 do-while 循环,我必须在其中创建一个新的扫描器,因为我试图让 "cursor" 回到文件顶部,因为我已经阅读了通过程序中较早的文件使用不同的扫描仪。问题是我试图让扫描器逐行读取文本文件,但每次 do-while 重复它都会创建一个新的扫描器并且光标会回到顶部。 java 中是否有一种方法可以限制扫描器的创建仅在 do-while 循环中第一次完成,即使循环的其余部分可以循环多次?
int count = 0
while(condition is true){
if(count == 0){
//this statement will only execute once.
}
//main body of while loop
count++;
}
或者
boolean executeOnce = true;
while(condition is true){
if(executeOnce ){
//this statement will only execute once.
executeOnce = false;
}
//main body of while loop
}
当然可以。你可以使用 boolean
标志,
boolean runOnce = true;
do {
// ...
if (runOnce) {
// Do this once
// ...
runOnce = false;
}
// ...
} while (...);
备选方案 1:
Scanner scanner = new Scanner(...);
do {
...
scanner.nextLine();
...
} while (...);
备选方案 2:
Scanner scanner = null;
do {
if (scanner == null) {
scanner = new Scanner(...);
}
...
scanner.nextLine();
...
} while (...);
编写 post 您的代码,以便更容易理解您面临的问题。
到运行代码的特定部分只需一次,您需要做的就是将该代码片段放入特定于值(标志)的'if'语句中并更改标志值在退出 if 子句之前。使用整数或布尔标志。
整数:
do
{
int flag=1;
//some code that executes all the time
if(flag==1)
{
//scanner code that executes only once
flag=0;
}
//some code that executes all the time
}
while(condition);
布尔值:
do
{
boolean flag=true;
//some code that executes all the time
if(flag)
{
//scanner code that executes only once
flag=false;
}
//some code which executes all the time
}
while(condition);
考虑到您需要 scanner.nextLine() 到 运行 不止一次,请将其放在代码的一部分,其中写着//某些代码一直在执行。
希望这可以帮助。祝你好运!
我的代码中有一个 do-while 循环,我必须在其中创建一个新的扫描器,因为我试图让 "cursor" 回到文件顶部,因为我已经阅读了通过程序中较早的文件使用不同的扫描仪。问题是我试图让扫描器逐行读取文本文件,但每次 do-while 重复它都会创建一个新的扫描器并且光标会回到顶部。 java 中是否有一种方法可以限制扫描器的创建仅在 do-while 循环中第一次完成,即使循环的其余部分可以循环多次?
int count = 0
while(condition is true){
if(count == 0){
//this statement will only execute once.
}
//main body of while loop
count++;
}
或者
boolean executeOnce = true;
while(condition is true){
if(executeOnce ){
//this statement will only execute once.
executeOnce = false;
}
//main body of while loop
}
当然可以。你可以使用 boolean
标志,
boolean runOnce = true;
do {
// ...
if (runOnce) {
// Do this once
// ...
runOnce = false;
}
// ...
} while (...);
备选方案 1:
Scanner scanner = new Scanner(...);
do {
...
scanner.nextLine();
...
} while (...);
备选方案 2:
Scanner scanner = null;
do {
if (scanner == null) {
scanner = new Scanner(...);
}
...
scanner.nextLine();
...
} while (...);
编写 post 您的代码,以便更容易理解您面临的问题。
到运行代码的特定部分只需一次,您需要做的就是将该代码片段放入特定于值(标志)的'if'语句中并更改标志值在退出 if 子句之前。使用整数或布尔标志。
整数:
do
{
int flag=1;
//some code that executes all the time
if(flag==1)
{
//scanner code that executes only once
flag=0;
}
//some code that executes all the time
}
while(condition);
布尔值:
do
{
boolean flag=true;
//some code that executes all the time
if(flag)
{
//scanner code that executes only once
flag=false;
}
//some code which executes all the time
}
while(condition);
考虑到您需要 scanner.nextLine() 到 运行 不止一次,请将其放在代码的一部分,其中写着//某些代码一直在执行。 希望这可以帮助。祝你好运!