I'm trying to prompt the user to input the name a file they'd like to write to, create that .txt file and then write the qualifying lines of text into that file and save it. inside the do while, it seems to be skipping over the user input for the name of the file they'd like to save to, looping back around and then getting a FileNotFoundException, and it shouldn't even be looking for a file.
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) {
Scanner user = new Scanner(System.in);
Scanner docInName = null;
PrintWriter docOutName = null;
do {
System.out.println("Please enter the filename of the file you
would like to read from: ");
try {
docInName = new Scanner(new File(user.nextLine()));
} catch (FileNotFoundException e) {
System.out.println("File not found!");
}
} while (docInName == null);
int lineNum = docInName.nextInt();
BikePart[] bp = new BikePart[lineNum];
System.out.println("please enter the max cost for a part: ");
int cost = user.nextInt();
do {
System.out.println("please enter a name for the file to write to
(end with .txt): ");
String out = user.nextLine(); //PROBLEM HERE! SKIPS USER INPUT
try {
docOutName = new PrintWriter(out);
for (int i = 0; i < lineNum; i++) {
String line = docInName.nextLine();
String[] elements = line.split(",");
bp[i] = new BikePart(elements[0],
Integer.parseInt(elements[1]),
Double.parseDouble(elements[2]),
Double.parseDouble(elements[3]),
Boolean.parseBoolean(elements[4]));
double temp = Double.parseDouble(elements[3]);
if ((temp < cost && bp[i].isOnSale() == true)
|| (bp[i].getListPrice() < cost &&
bp[i].isOnSale() == false)) {
docOutName.write(line);
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
} while (docOutName == null);
user.close();
}
}
I just needed to skip a line before the loop began.
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) {
Scanner user = new Scanner(System.in);
Scanner docInName = null;
PrintWriter docOutName = null;
do {
System.out.println("Please enter the filename of the file you would like to read from: ");
try {
docInName = new Scanner(new File(user.nextLine()));
} catch (FileNotFoundException e) {
System.out.println("File not found!");
}
} while (docInName == null);
int lineNum = docInName.nextInt();
BikePart[] bp = new BikePart[lineNum];
System.out.println("please enter the max cost for a part: ");
int cost = user.nextInt();
user.nextLine(); //SOLUTION HERE
do {
System.out.println("please enter a name for the file to write to (end with .txt): ");
String out = user.nextLine();
try {
docOutName = new PrintWriter(out);
for (int i = 0; i < lineNum; i++) {
String line = docInName.nextLine();
String[] elements = line.split(",");
bp[i] = new BikePart(elements[0], Integer.parseInt(elements[1]), Double.parseDouble(elements[2]),
Double.parseDouble(elements[3]), Boolean.parseBoolean(elements[4]));
double temp = Double.parseDouble(elements[3]);
if ((temp < cost && bp[i].isOnSale() == true)
|| (bp[i].getListPrice() < cost && bp[i].isOnSale() == false)) {
docOutName.write(line);
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
} while (docOutName == null);
user.close();
}
}
Related
I wrote a program that reads a text file, deletes the requested string and rewrites it without the string. This program takes three arguments from the terminal: 1) the input file 2) the string 3) the output file.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
class wordfilter {
public static void main(String[] args) {
Scanner scanner = new Scanner("");
Scanner conteggio = new Scanner("");
int numel = 0;
File file = new File(args[0]); // Argomento 0: il file
try {
conteggio = new Scanner(file);
}
catch (FileNotFoundException e) {
System.out.println("File non trovato");
}
while (conteggio.hasNext()) {
numel++;
conteggio.next();
}
conteggio.close();
String[] lettura = new String[numel];
int i = 0;
try {
scanner = new Scanner(file);
}
catch (FileNotFoundException e) {
System.out.println("File non trovato");
}
while (scanner.hasNextLine()) {
lettura[i] = scanner.next();
i++;
}
System.out.println("Contarighe -> " + numel);
for (i = 0; i < lettura.length; i++) {
System.out.println("Elemento " + i + " - > " + lettura[i]);
}
scanner.close();
String escludi = args[1]; // Argomento 1: il filtro
String[] filtrato = rimuovi(escludi, lettura);
if (args.length == 3) stampaSuFile(filtrato, args[2]);
}
public static String[] rimuovi(String esclusione, String[] input) {
String[] nuovoV;
String escludi = esclusione;
int dim = 0;
for (int i = 0; i < input.length; i++) {
if (!input[i].equals(escludi))
dim++;
}
nuovoV = new String[dim];
int j = 0;
for (int i = 0; i < input.length; i++) {
if (!input[i].equals(escludi)) {
nuovoV[j] = input[i];
j++;
}
;
}
return nuovoV;
}
public static void stampaSuFile(String[] out, String path) {
String closingstring = "";
File destinazione = new File(path);
try {
destinazione.createNewFile();
} catch (IOException e) {
System.out.println("Errore creazione file");
}
try {
FileWriter writer = new FileWriter(destinazione);
for (int i = 0; i < out.length; i++)
writer.write(out[i] + (i == (out.length-1) ? closingstring : " "));
writer.close();
System.out.println("Scrittura eseguita correttamente");
} catch (IOException e) {
System.out.println("Errore scrittura file");
}
}
}
On Windows no problem, it works perfectly.
On Linux instead when i write something like java wordfilter in.txt word out.txt
I get
Exception in thread "main" java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:937)
at java.base/java.util.Scanner.next(Scanner.java:1478)
at wordfilter.main(wordfilter.java:42)
What's the problem? It's because of some difference on linux?
You're mixing line and token based functions, :hasNextLine() and next(). If the input ends with a line feed (typical on Linux) hasNextLine returns true at the end of the file, but there is no next "item".
while (scanner.hasNextLine()) {
lettura[i] = scanner.next();
i++;
}
You should use either hasNext with next, or hasNextLine with nextLine, mixing them is confusing.
while (scanner.hasNext()) {
lettura[i] = scanner.next();
i++;
}
The input file ends in a newline on Linux. Therefore, there's another line, but it's empty. If you remove the final newline from the input, the program will start working normally.
Or, import the exception
import java.util.NoSuchElementException;
and ignore it int the code
while (scanner.hasNextLine()) {
System.out.println("" + i);
try {
lettura[i] = scanner.next();
} catch (NoSuchElementException e) {}
i++;
}
The program is supposed to compare a user-inputted string to a text document. If the program finds a match in the file and in part of the string, it should highlight or change the font color of the matching string in what the user inputted. The thing is, once I enter something for user input, the program terminates. Examples of inputs that could have a match in the file are MALEKRQ, MALE, MMALEKR, MMMM, and MALEK. How do I fix this problem? I'm using Eclipse Neon on Mac OS X El Capitan.
import java.util.*;
import java.io.*;
public class ScienceFair
{
public static void main(String[] args) throws FileNotFoundException
{
java.io.File file = new java.io.File("/Users/Kids/Desktop/ScienceFair/src/MALEKRQsample.txt");
try
{
Scanner fileInput = new Scanner(file);
Scanner userInput = new Scanner(System.in);
System.out.println("Enter Protein Sequence");
String userProteinSequence = userInput.nextLine().toUpperCase();
int len = userProteinSequence.length();
int size = 4;
int start = 0;
int indexEnd = size;
while (indexEnd < len - size)
{
for (int index = start; index <= len - size; index++)
{
String search = userProteinSequence.substring(index, indexEnd);
System.out.println(search);
while (fileInput.hasNext())
{
String MALEKRQ = fileInput.nextLine();
// System.out.println(MALEKRQ);
int found = MALEKRQ.indexOf(search);
if (found >= 0)
{
System.out.println("Yay.");
}
else
{
System.out.println("Fail.");
}
}
indexEnd++;
}
size++;
if (size > 8) {
size = 8;
start++;
}
}
}
catch (FileNotFoundException e)
{
System.err.format("File does not exist.\n");
}
}
}
import java.util.*;
import java.io.*;
public class ScienceFair
{
public static void main(String[] args) throws FileNotFoundException
{
java.io.File file = new java.io.File("/Users/Kids/Desktop/ScienceFair/src/MALEKRQsample.txt");
try
{
Scanner userInput = new Scanner(System.in);
System.out.println("Enter Protein Sequence");
String userProteinSequence = userInput.nextLine().toUpperCase();
for (int size = userProteinSequence.length(); size >= 4; size--) {
for (int start = 0; start <= userProteinSequence.length()-size; start++) {
boolean found = false;
String search = userProteinSequence.substring(start, size);
System.out.println(search);
Scanner fileInput = new Scanner(file);
while (fileInput.hasNext()) {
String MALEKRQ = fileInput.nextLine();
int found = MALEKRQ.indexOf(search);
if (found >= 0) {
found = true;
}
}
if (found) {
System.out.println(search+" found (index "+start+")");
fileInput = new Scanner(file);
while (fileInput.hasNext()) {
String MALEKRQ = fileInput.nextLine();
MALEKRQ = MALEKRQ.replaceAll(search, "[["+search+"]]");
System.out.println(MALEKRQ);
}
return;
}
}
}
System.out.println(search+" not found");
Scanner fileInput = new Scanner(file);
while (fileInput.hasNext()) {
String MALEKRQ = fileInput.nextLine();
System.out.println(MALEKRQ);
}
} catch (FileNotFoundException e) {
System.err.format("File does not exist.\n");
}
}
}
I am having trouble with a ticketing system that I am trying to create using java. I am trying to utilize two files to read and write my inputs. I am testing with just salesSell method at the moment. I am passing the args using terminal. The problem that I am having is an arrayoutofbounds exception that gets thrown.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at cisc_327_frontend.Frontend_try1.main(Frontend_try1.java:763)
the two array parameters that I am passing are parsed from the same line in my current events file. an example of a line in the file is : "testevent1__________0003". I cannot seem to figure out where I am having this problem. Any type of guidance would be much appreciated.
package cisc_327_frontend;
import java.io.*;
import java.util.*;
public class Frontend_try1 {
private static File fileOutput;
private static List<StringBuilder> eventTrans = new ArrayList<>();
public static void consoleInput(String[] namesArray, int[] ticketArray,File fileCurrentEvents){
System.out.println("Enter command:");
Scanner input = new Scanner(System.in);
String inputString = input.nextLine();
boolean correct = true;
do{
if(inputString.toUpperCase().equals( "LOGIN")) {
//enter login mode
login(namesArray, ticketArray,fileCurrentEvents);
correct = true;
}
if(inputString.toUpperCase().equals("LOGOUT")){
logout(namesArray, ticketArray,fileCurrentEvents);
correct=true;
}
if (!"LOGIN".toUpperCase().equals(inputString) || !"LOGOUT".toUpperCase().equals(inputString)){
System.out.println("Incorrect command, please enter command:");
input = new Scanner(System.in);
inputString = input.nextLine();
correct = false;
}
}while(!correct);
}
public static void login(String[] namesArray, int[] ticketArray,File fileCurrentEvents) {
System.out.println("Sales or Admin?");
Scanner input = new Scanner(System.in);
String inputString = input.nextLine();
boolean correct = true ;
do {
if(inputString.toUpperCase().equals("LOGOUT")){
logout(null, null, null);
}
else if(inputString.toUpperCase().equals("SALES")) {
//enter sales mode
sales(namesArray, ticketArray,fileCurrentEvents);
correct = true;
} else if (inputString.toUpperCase().equals("ADMIN")) {
//enter admin mode
admin(namesArray, ticketArray,fileCurrentEvents);
correct = true;
} else if (inputString.toUpperCase().equals("LOGOUT")) {
//enter logout mode
logout( namesArray, ticketArray, fileCurrentEvents);
correct = true;
} else {
//ask again
System.out.println("Invalid Input");
System.out.println("Sales or Admin?");
input = new Scanner(System.in);
inputString = input.nextLine();
correct = false;
}
}while(!correct);
}
public static void sales(String[] namesArray, int[] ticketArray,File fileCurrentEvents) {
//System.out.println("SALES");
System.out.println("Sales Mode");
System.out.println("Enter Command:");
Scanner input = new Scanner(System.in);
String inputString = input.nextLine();
boolean correct = true ;
do {
if(inputString.toUpperCase().equals("LOGOUT")){
logout( namesArray, ticketArray, fileCurrentEvents);
}
else if(inputString.toUpperCase().equals("SELL")) {
//enter sales Sell mode
salesSell(namesArray, ticketArray,fileCurrentEvents);
correct = true;
} else if (inputString.toUpperCase().equals("RETURN")) {
//enter sales Return mode
salesReturn(namesArray, ticketArray,fileCurrentEvents);
correct = true;
} else if (inputString.toUpperCase().equals("LOGOUT")) {
//enter Logout mode
logout( namesArray, ticketArray, fileCurrentEvents);
correct = true;
} else {
//ask again
System.out.println("Invalid Input");
System.out.println("Enter Command:");
input = new Scanner(System.in);
inputString = input.nextLine();
correct = false;
}
}while(!correct);
}
public static void salesSell(String[] namesArray, int[] ticketArray,File fileCurrentEvents) {
int index = 0;
String eventName = null;
int numberTickets = 0;
System.out.println("Sales Sell Mode");
System.out.println("What is the name of your event?");
Scanner input = new Scanner(System.in);
String inputString = input.nextLine();
if(inputString.toUpperCase().equals("LOGOUT")){
logout( namesArray, ticketArray, fileCurrentEvents);
}
try{
for(int i = 0; i < namesArray.length; i++) {
if(namesArray[i].equals(inputString)){
index = i;
}
}
eventName= namesArray[index];
numberTickets=ticketArray[index] ;
} catch (Exception e) {
System.out.println("Error: Event not found within file");
System.exit(1);
}
int event = inputString.length();
boolean charnumber = true;
do{
if(inputString.toUpperCase().equals("LOGOUT")){
logout( namesArray, ticketArray, fileCurrentEvents);
}
if(event< 0 || event >20){
System.out.println("No more than 20 characters allowed for name!");
System.out.println("Enter name:");
input = new Scanner(System.in);
inputString = input.nextLine();
event=inputString.length();
charnumber = false;
}
else{
charnumber = true;
}
} while(!charnumber);
System.out.println("How many tickets?");
input = new Scanner(System.in);
inputString = input.nextLine();
int digit;
while(true){
try {
digit = Integer.parseInt(inputString);
break;
}
catch(NumberFormatException e){
}
System.out.println("Please type a number!");
inputString = input.nextLine();
}
if( numberTickets - digit <0){
System.out.println("Illegal amount of tickets! Buy less ticket please.");
}
else{
int tickets = numberTickets - digit;
ticketArray[index]=tickets;
}
boolean dignumber = true;
do{
if(inputString.toUpperCase().equals("LOGOUT")){
logout( namesArray, ticketArray, fileCurrentEvents);
}
if(digit<0 || digit>8){
System.out.println("Only 8 tickets allowed to be sold!");
inputString = input.nextLine();
event=inputString.length();
dignumber = false;
digit= Integer.parseInt(inputString);
}
else{
dignumber= true;
}
}while(!dignumber);
}
public static boolean logout(String[] namesArray, int[] ticketArray,File fileCurrentEvents) {
FileWriter logoutFileWriter;
FileWriter currEventsFileWriter;
int numSpaces = 0;
try{
currEventsFileWriter = new FileWriter(fileCurrentEvents, true);
for(int i = 0; i < namesArray.length; i++ ) {
currEventsFileWriter.write(namesArray[i]);
numSpaces = 20 - (namesArray[i].length() + 4);
for(int j = 0; j < numSpaces; j++) {
currEventsFileWriter.write("_");
}
currEventsFileWriter.write(ticketArray[i]);
currEventsFileWriter.write(String.format("%n"));
}
} catch(IOException e) {
System.out.println("Rewriting Current Events File Error");
System.exit(1);
}
try {
logoutFileWriter = new FileWriter(fileOutput, true);
//Cycle through event trans file and write via filewriter
for(int i = 0; i < eventTrans.size(); i++ ) {
String transact = eventTrans.get(i).toString();
logoutFileWriter.write(transact);
logoutFileWriter.write(String.format("%n"));
}
// Signify end of file
logoutFileWriter.write("00 000000 00000");
logoutFileWriter.write(String.format("%n"));
logoutFileWriter.close();
fileOutput.createNewFile();
} catch(IOException e) {
System.out.println("Output File Error");
System.exit(1);
}
return true;
/*
for( int i = 0; i < 20; i++ ) {
System.out.println("");
}
System.out.println("Logged Out");
consoleInput();
*/
}
public static void main(String[] args){
try {
File fileCurrentEvents = new File(args[0]);
fileOutput = new File(args[1]);
// Read current events file for events & dates
FileReader fileRead = new FileReader(fileCurrentEvents);
BufferedReader buffRead = new BufferedReader(fileRead);
// Create strings for data in current events file
String currentLine;
String eventName;
Integer numberTickets;
List<Integer> numticket = new ArrayList<Integer>();
List<String> list = new ArrayList<String>();
int[] numarray= new int[numticket.size()];
String[] linesArray = list.toArray(new String[list.size()]);
// Cycle through current events file line by line
while((currentLine = buffRead.readLine()) != null) {
if (currentLine.equals("END_________________00000")){
break; // End of file
}
//Parse for event name & number of tickets
eventName = currentLine.substring(0, currentLine.lastIndexOf("_")).trim();
numberTickets = Integer.parseInt(currentLine.substring(currentLine.lastIndexOf
("_") + 1));
// Place event name and # tickets into data structure
// Add event name to event array list with same index as # tickets
// Parse int to get # tickets & add to arraylist for tickets with same index
while((eventName = buffRead.readLine()) != null){
list.add(eventName);
}
for (int i =0 ; i< list.size();i++){
linesArray[i]= list.get(i);
}
while((eventName = buffRead.readLine()) != null){
numticket.add(numberTickets);
}
for (int i =0 ; i< numticket.size();i++){
numarray[i]= numticket.get(i);
}
}
while(true) {
consoleInput(linesArray, numarray, fileCurrentEvents);
}
} catch (IOException e) {
System.out.println("File I/O Error"); //Print to console to signify error
e.printStackTrace();
System.exit(1);
}
}
}
If you are getting an ArrayOutOfBoundsIndexException at this line
File fileCurrentEvents = new File(args[0]);
Then it probably means the array (args) index (0) you are using is out of bounds in that it is higher than the size of the array.
If you have an array that looks like
[] //Zero entries
You can't get element 0 (the first item), because there are none.
So you must be passing in zero parameters when you run the code. Either when you run it at the command line, add the filename after it or change the build settings in your IDE (Eclipse, IntelliJ, Sublime) to add it to the build steps.
the error is being thrown on this line in the main method. File fileCurrentEvents = new File(args[0]);
Then your args is empty (e.g. you haven't run your program with any command line arguments, like a file). You could add a default, something like
File fileCurrentEvents = new File(args.length > 0 ? args[0] : "default.txt");
In your original code, line 763 is actually:
for (int i = 0 ; i< list.size(); i++){
linesArray[i] = list.get(i); //<--------------THIS ONE!
}
which can cause an ArrayIndexOutOfBoundsException when linesArray is shorter that list. This is happening because you instantiated linesArray earlier via
String[] linesArray = list.toArray(new String[list.size()]);
when list was empty, then added to list making it longer than your array.
Since the outer while-loop doesn't appear to use the linesArray in any other capacity, you can probably remove the above for-loop and, and place
linesArray = list.toArray(new String[list.size()]);
after the first while loop to create the appropriate array with all the elements.
I had this program with which i have to check if the value the user entered is present in the text file i created in the source file. However it throws me an error everytime i try to call the method with IOException. Please help me out thanks.
import java.util.*;
import java.io.*;
public class chargeAccountModi
{
public boolean sequentialSearch ( double chargeNumber ) throws IOException
{
Scanner keyboard= new Scanner(System.in);
int index = 0;
int element = -1;
boolean found = false;
System.out.println(" Enter the Charge Account Number : " );
chargeNumber = keyboard.nextInt();
int[] tests = new int[18];
int i = 0;
File file = new File ("Names.txt");
Scanner inputFile = new Scanner(file);
while(inputFile.hasNext() && i < tests.length )
{
tests [i] = inputFile.nextInt();
i++;
}
inputFile.close();
for ( index = 0 ; index < tests.length ; index ++ )
{
if ( tests[index] == chargeNumber )
{
found = true;
element = index;
}
}
return found;
}
public static void main(String[]Args)
{
double chargeNumber = 0;
chargeAccountModi object1 = new chargeAccountModi();
try
{
object1.sequentialSearch(chargeNumber);
}
catch (IOException ioe)
{
}
System.out.println(" The search result is : " + object1.sequentialSearch (chargeNumber));
}
}
After looking on your method sequentialSearch there is everythink ok. But try to change main:
But remember that in your Names.txt file you should have only numbers because you use scanner.nextInt();, so there should be only numbers or method will throw exeption InputMismatchException.
Check also path to Names.txt file you should have it on classpath because you use relative path in code File file = new File ("Names.txt"); Names.txt should be in the same folder.
public static void main(String[]Args)
{
double chargeNumber = 0;
chargeAccountModi object1 = new chargeAccountModi();
try
{
System.out.println(" The search result is : " + object1.sequentialSearch(chargeNumber));
}
catch (IOException ioe)
{
System.out.println("Exception!!!");
ioe.printStackTrace();
}
}
Few tips and suggestions:
First of all: Don't forget to close the Scanner objects! (you left one unclosed)
Second of all: Your main method is highly inefficient, you are using two loops, in the first one you read and store variables, in the second one you check for a match, you can do both at the same time (I've written an alternative method for you)
Third little thing: The variable "element" is not used at all in your code, I've removed it in the answer.
And last but not least: The file "Names.txt" needs to be located (since you've only specificied it's name) in the root folder of your project, since you mention an IOException, I figure that's what's wrong with the app. If your project is called Accounts, then it's a folder called Accounts with it's source and whatever else is part of your project, make sure the file "Accounts/Names.txt" exists! and that it is in the desired format.
import java.util.*;
import java.io.*;
public class ChargeAccountModi {
public boolean sequentialSearch(double chargeNumber) throws IOException {
Scanner keyboard= new Scanner(System.in);
int index = 0;
boolean found = false;
System.out.print("Enter the Charge Account Number: " );
chargeNumber = keyboard.nextInt();
int[] tests = new int[18];
int i = 0;
File file = new File ("Names.txt");
Scanner inputFile = new Scanner(file);
while(inputFile.hasNext() && i < tests.length ) {
tests [i] = inputFile.nextInt();
i++;
}
inputFile.close();
for (index = 0 ; index < tests.length ; index ++ ) {
if (tests[index] == chargeNumber) {
found = true;
}
}
keyboard.close();
return found;
}
public boolean sequentialSearchAlternative(double chargeNumber) throws IOException {
Scanner keyboard= new Scanner(System.in);
boolean found = false;
System.out.print("Enter the Charge Account Number: " );
chargeNumber = keyboard.nextInt();
int tests = 18;
int i = 0;
File file = new File ("Names.txt");
Scanner inputFile = new Scanner(file);
while(inputFile.hasNext() && i<tests) {
if (inputFile.nextInt() == chargeNumber) {
found = true;
break;
}
i++;
}
inputFile.close();
keyboard.close();
return found;
}
public static void main(String[] args) {
double chargeNumber = 0;
ChargeAccountModi object1 = new ChargeAccountModi();
try {
System.out.println("The search result is : " + object1.sequentialSearch(chargeNumber));
} catch (Exception e) {
//Handle the exceptions here
//The most likely exceptions are:
//java.io.FileNotFoundException: Names.txt - Cannot find the file
//java.util.InputMismatchException - If you type something other than a number
e.printStackTrace();
}
}
}
This is a program to read a file and print out the file with some of the text edited. The code will compile the issue is that it will read the users input but will say file is not found when the file is there. I feel like I am missing something. I am brand new at this so go easy on me.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class MainTest {
public static void main(String args[]) {
// if (args[0] != null)
readFile();
}
public static void readFile() { // Method to read file
Scanner inFile = null;
String out = "";
try {
Scanner input = new Scanner(System.in);
System.out.println("enter file name");
String filename = input.next();
File in = new File(filename); // ask for the file name
inFile = new Scanner(in);
int count = 0;
while (inFile.hasNextLine()) { // reads each line
String line = inFile.nextLine();
for (int i = 0; i < line.length(); i++) {
char ch = line.charAt(i);
out = out + ch;
if (ch == '{') {
count = count + 1;
out = out + " " + count;
} else if (ch == '}') {
out = out + " " + count;
if (count > 0) {
count = count - 1;
}
}
}
}
System.out.println(out);
} catch (FileNotFoundException exception) {
System.out.println("File not found.");
}
inFile.close();
}
}
You can use System.getProperty("user.dir") to find where Scanner looking to find your file. And you should be sure your file is located here.