0

The idea of this is to take in a console input and use it as the file name for the text file to fill with square root values with various decimal places

however I cannot get it to let me enter anything, it throws a NoSuchElementException and I do not get why? in a previous method, I used this exact code to get the file name as a variable

This is Current Method

    private static void FileWritting () throws IOException  {
    System.out.println("\n6.7.2 Writting Data");
    System.out.println("-----------------------");
    System.out.println("Enter the File name");
    Scanner Scanner2 = new Scanner(System.in);
    String filename = Scanner2.nextLine();
    FileWriter writehandle = new FileWriter("D:\\Users\\Ali\\Documents\\lab6\\" + filename + ".txt");
       BufferedWriter bw = new BufferedWriter(writehandle);
    int n = 10;
       for(int i=1;i<n;++i)
       {
          double value = Math.sqrt(i);
          String formattedString = String.format("%."+ (i-1) +"f", value);
          System.out.println(formattedString);
       //  bw.write(line);
          bw.newLine();
       }
       bw.close();
       writehandle.close();
       Scanner2.close();
    }

Where This is the previous method

System.out.println("6.7.1 Reading Data");
    System.out.println("-----------------------");
    System.out.println("Enter the File name");
    Scanner Scanner1 = new Scanner(System.in);
    String filename = Scanner1.nextLine();
       FileReader readhandle = new FileReader("D:\\Users\\Ali\\Documents\\lab6\\"+ filename +".txt");
       BufferedReader br = new BufferedReader(readhandle);
       String line = br.readLine ();
       int count = 0;
       while (line != null) {
          String []parts = line.split(" ");
          for( String w : parts)
          {
            count++;        
          }
          line = br.readLine();
       }         
       System.out.println("The number of words is: " + count);
       br.close();
       Scanner1.close();
}
Xray25
  • 115
  • 13
  • Possible duplicate of [java.util.NoSuchElementException - Scanner reading user input](https://stackoverflow.com/questions/13042008/java-util-nosuchelementexception-scanner-reading-user-input) – Benjamin Urquhart Mar 13 '19 at 23:06

1 Answers1

0

You're calling Scanner#close in your first method. This closes stdin, which makes reading from it impossible. I recommend creating a global variable to hold your scanner and closing it when your program terminates (instead of creating a new one in every method).

More info and a better explanation

Benjamin Urquhart
  • 1,626
  • 12
  • 18