Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Loops do while上的无限循环_Loops_While Loop_Integer - Fatal编程技术网

Loops do while上的无限循环

Loops do while上的无限循环,loops,while-loop,integer,Loops,While Loop,Integer,我正在尝试一种简单的方法,要求输入一个数字,但我遇到了条件方面的问题,以下是我的代码: private static int rows(){ int w = 0; Scanner sc = new Scanner(System.in); do { System.out.println("What is the number of rows?"); if(sc.hasNextInt()) { w = sc.nextInt();

我正在尝试一种简单的方法,要求输入一个数字,但我遇到了条件方面的问题,以下是我的代码:

private static int rows(){
    int w = 0;
    Scanner sc = new Scanner(System.in);
    do {
    System.out.println("What is the number of rows?");
    if(sc.hasNextInt()) {
        w = sc.nextInt();
        if (w <= 0){
            System.out.println("Error: the rows can't be 0 or negative number.");
        }
    }
    else { 
        System.out.println("Error: please only use digits.");
    }
    }
    while (w<=0);
    return w;
}

w
仅在
sc.hasnetint()的情况下更改。
。如果输入字母/无效字符,
w
永远不会更改,循环无法结束。

您没有刷新
w
的值。重新启用该选项,以便为
w
输入新值。比如:

int w = 0;
Scanner sc = new Scanner(System.in);
do {
    System.out.println("What is the number of rows?");
    if(sc.hasNextInt()) {
        w = sc.nextInt();
        if (w <= 0){
            System.out.println("Error: the rows can't be 0 or negative number.");
        }
    }
    else { 
        System.out.println("Error: please only use digits.");
        sc.next(); // Clear default input on invalid input
        continue; // Restart the loop so it gets newer value again
    }
}
    while (w<=0);
    return w;
intw=0;
扫描仪sc=新的扫描仪(System.in);
做{
System.out.println(“行数是多少?”);
if(sc.hasnetint()){
w=sc.nextInt();

如果(我知道,但我怎么能修复它呢?)斯塔克:我不知道java API是什么(我更喜欢C++)。,我不想查找
Scanner
类的详细信息以及它生成的内容。但是,既然您要求的是一个值,那么似乎循环在一开始就没有多大用处?那太好了,非常感谢,现在可以完美地工作了,我的教授告诉我应该避免递归,所以我尝试使用循环。
int w = 0;
Scanner sc = new Scanner(System.in);
do {
    System.out.println("What is the number of rows?");
    if(sc.hasNextInt()) {
        w = sc.nextInt();
        if (w <= 0){
            System.out.println("Error: the rows can't be 0 or negative number.");
        }
    }
    else { 
        System.out.println("Error: please only use digits.");
        sc.next(); // Clear default input on invalid input
        continue; // Restart the loop so it gets newer value again
    }
}
    while (w<=0);
    return w;