Home > Back-end >  Ckecking if a folder from the input exists and asking to type again in java
Ckecking if a folder from the input exists and asking to type again in java

Time:12-10

I am trying to read a folder path from the user and check if exists or not.If it does not exist I want to ask from the user to type the path again using a while loop .The problem is that even if the user types a correct path my program asks to type again .I am preety sure that the solution is easy and that the problem is in the loop but I can not see it. Please help me because I am a new programmer in Java.


public class JavaProject {

    public static void main(String[] args) throws IOException {
        
        
        //Taking the name of the folder from the user
        System.out.println("Give me the path of the folder");
        Scanner fold =new Scanner(System.in);
        String folderName= fold.nextLine();
        File f= new File(folderName);
        
        //Check if the file exists
        
        
        boolean exists = f.exists();
        boolean folderIsValid=true;
        
        while(folderIsValid){
         
         
         if(!exists){
            
            
            System.out.println("The folder you are searching does not exist :"  exists);
            System.out.println("Try again!");
            folderName= fold.nextLine();
            
            
         }else{
            System.out.println("The folder you are searching exists :"  exists);
            folderIsValid=false;
         }  
            
        }
  }   
}

CodePudding user response:

use do while loop, do at least once, then while check exit do while loop or contine do next loop.

import java.util.Scanner;
import java.io.File;
public class JavaProject {
    public static void main(String[] args){
        boolean isExistingDir = false;
   do {
       System.out.println("Give me the path of the folder");
       Scanner input = new Scanner(System.in);
       String dirName = input.nextLine();
       System.out.println(">>"   dirName);
       File f =new File(dirName);
       if (f.exists()==true) {
           isExistingDir=true;
           System.out.println("EXISTING >>"   dirName);
       } else {
           System.out.println("NOT EXISTING >>"   dirName);
           System.out.println("PLEASE INPUT A EXISTING AGAIN");
       }
      } while (!isExistingDir);
   } //main
}
  • Related