How to create multiple directories? - java

I am new to programming and recently have tried to make a simple program to create multiple directories with names as I want. It is working but at the beginning, it is adding first "number" without asking me. After this, I can make as many folders as I want.
public class Main {
public static void main(String args[]) throws IOException{
Scanner sc = new Scanner(System.in);
System.out.println("How many folders do you want?: ");
int number_of_folders = sc.nextInt();
String folderName = "";
int i = 1;
do {
System.out.println("Folder nr. "+ i);
folderName = sc.nextLine();
try {
Files.createDirectories(Paths.get("C:/new/"+folderName));
i++;
}catch(FileAlreadyExistsException e){
System.err.println("Folder already exists");
}
}while(number_of_folders > i);
}
}
If I chose to make 5 folders, something like this is happening:
1. How many folders do you want?:
2. 5
3. Folder nr. 0
4. Folder nr. 1
5. //And only now I can name first folder nad it will be created.
If it is a stupid question, I will remove it immediately. Thank you in advance.

It's because your sc.nextInt() in this line :
int number_of_folders = sc.nextInt();
doesn't consume last newline character.
When you inputted number of directories you pressed enter, which also has it's ASCII value (10). When you read nextInt, newline character haven't been read yet, and nextLine() collect that line first, and than continue normally with your next input.

In this case, you can just use the mkdir part of the File class as so:
String directoryName = sc.nextLine();
File newDir = new File("/file/root/"+directoryName);
if (!newDir.exists()) { //Don't try to make directories that already exist
newDir.mkdir();
}
It should be clear how to incorporate this into your code.

Related

Item Counter program that will display the number of names that are stored on a file

Can someone help me with this java program that I've been puzzled on for a while. I'll post the question alone with the code but its a Files in java that I've recently started and I'm having trouble adding a loop counter variable to hold and display the number of names stored in the file.
For better understanding here the question I'm working on:
Assume that a file containing a series of names (as strings) is named names.dat and exists on the computers disk. Design a program that displays the number of names that are stored in the file. (Hint: Open the file and read every string stored in it. Each time you read a string, increment a counter variable. When you've read all the strings from the file, the counter variable will contain the number of names stored in the file.)
I don't know how much trouble it will be to aid assist being that this question is file related in java.
Here is my java code so far for better understanding:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Item_Counter {
public static void main(String[] args) throws FileNotFoundException {
int numLines = 0;
int sum = 0;
File namesFile = new File("C:\\Users\\Tyrese\\JAVA 2\\Chapter 10\\names.dat");
Scanner bot = new Scanner(namesFile);
System.out.println(bot.nextLine());
while (bot.hasNext()) {
numLines = numLines + 1;
numLines = bot.nextInt();
}
System.out.println("The file has" + numLines);
}
}
Feel free to replace my file path and name that is a simple notepad document containing a few names, with your own if necessary.
You have some errors in your code, the way Scanner works for file reading is simple, you open the file the way you did like this : Scanner bot = new Scanner(namesFile); but in order to go to the next line you need to do bot.nextLine() so if you do it before you are in the while or do it twice it will go on 2 lines, so you just need to do like this :
public static void main(String[] args) throws FileNotFoundException {
int numLines = 0; // initialise variable
File namesFile = new File("C:\\Users\\Tyrese\\JAVA 2\\Chapter 10\\names.dat"); // fetch the file
Scanner bot = new Scanner(namesFile); // open the file
while (bot.hasNextLine()) { // while the file has a next line -> go on
numLines++; // add +1 to the variable numLines
numLines = bot.nextLine(); // go to the next line (if it has one)
}
System.out.println("The file has" + numLines); // print the result
}
You can ask me if you have any further questions
This is the problematic part of your code:
System.out.println(bot.nextLine());
while (bot.hasNext()) {
numLines = numLines + 1;
numLines = bot.nextInt();
}
Your println types a line being read and therefore that line will be ignored later. You need hasNextLine in the while loop and nextLine instead of nextInt.
Fix:
while (bot.hasNextLine()) {
numLines = numLines + 1;
bot.nextLine();
}
You can compute the sum of integers inside a file similarly. However, the actual solution depends on the structure of the file. If the file contains the integers as lines, without white characters beside the newline, such as
1
5
4
7
2
7
then the solution is:
int sum = 0;
while (bot.hasNextLine()) {
sum += 1;
bot.nextLine();
}
however, if the file is a list of numbers, separated by space, such as
3 7 8 2 8 3 6 9
then you read the content of the file via
String content = bot.nextLine();
String[] splited = str.split("\\s+");
int sum = 0;
for (int index = 0; index < splited.length; index++) {
sum += Integer.parseInt(splited[index])
}

Scanning a file and getting two tokens at a time and saving those in an ArrayList

Hi everyone this is my first question here so I apologize in advance if it is not in the correct format for this forum. I'm a comp sci student and I am really a novice programmer. For an assignment, I need to read in a file of polynomials and then sort them from highest degree to lowest. On each line of the file I have a coefficient and an exponent separated by a space.
This is what my .txt file looks like:
"5.6 3
4 1
8.3 0" which represents the polynomial 5.6x^3 + 4x + 8.3
I have to scan the file from a JFileChooser and then add the tokens to an ArrayList of type Polynomial. My question/problem is how can I run the file contents through a for loop and separate the first token(coefficients) from the second token(exponents) and then add them to the ArrayList? I'm going to need the exponents to be of type int and the coefficients should be double.
This is what I have so far:
ArrayList aList = new ArrayList();
// scanner used to read each line
try {
scan = new Scanner(file);
if (file.isFile()) {
while (scan.hasNext()) {
for (int i = 0; i < something.size(); i++) {
//this is where I'm lost, not sure what I need to do here
}
}
}
....
Thank you guys I appreciate the assistance.
-Linden
EDIT:
Alright I figured it out, it was a lot more complicated than I thought. Here's what I did:
Scanner scan = new Scanner(file);
if (file.isFile()) {
for (int i = 0; i <=2; i ++) {
term(scan);
}
}
static void term(Scanner scan) {
String s = scan.nextLine();
String [] splitter = s.split(" ");
String coefficient = splitter[0];
String exponent = splitter[1];
//populating
try {
arrayList.add(new Polynomial(coefficient, exponent));
} catch (InvalidPolynomialSyntax e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Thanks to the two guys that tried to help me out and the 24 viewers who didn't lol
First, you need to look at the scanner class. What methods does it have that you should use to get the data you need?
I don't want to give you the answer to your homework out of respect but broadly what you need is a way to get each line of that file from the scanner so you can compare the contents of each line to each other.
So look at the scanner class documentation and see what it has that you can use.
Start by simply trying to print out each line. Once you do that you can think about how you want to compare them.
you can read file as one sentence. First get all the text such as 5.6 3 4 1 8.3 0 as string. Then you can just use String [] arrayOfNumbers = yourString.split(" ");
This will split the string according to " " character so you get numbers directly.

Reading from a text file and changing the strings to int's to be entered in arrays is not working

Basically I am asking for the filename with a method called CS160Input (provided by my instructor) to ask for the filename. The text document has a bunch of entries each on their own lines, and I am trying to assign each number to a place in an array, but I am failing to actually write to the array. I know it is finding the file, because when i print out the counter, it tells me the correct amount of lines in the file. But when I try to print out a place in the array, I tried index 3 as you can see in my code, and it gives me 0 regardless of what I try. I tried creating an array of strings first and I ended up getting null for each index value as well.
public static void caclulate() throws FileNotFoundException {
String fileName = CS160Input.readString("Please enter the name of the file: ");
Scanner sc = new Scanner (new File (fileName));
int value, counter = 0;
int array[] = null;
while (sc.hasNextLine()) {
sc.nextLine();
counter++;
}
Scanner scanner = new Scanner(new File(fileName));
int[] calcArray = new int [counter];
int i = 0;
while(scanner.hasNextInt()){
calcArray[i++] = scanner.nextInt();
}
System.out.println(calcArray[3]);
System.out.println(counter);
}
Thanks to #Gendarme pointing out that hasNextInt() could be spitting out false if there were values in between, it made me take a closer look and I realized that in a previous program the numbers being written to the text file were doubles with 2 decimal places. Once I changed to hasNextDouble(), the program worked as intended.

How do I ask a user for a input file name, and then use that file name?

I am trying to ask the user for the name of their file, then I am going to scan the file to see how many indices are in the file, and then put it in an array and go from there.
Here is my code:
import java.util.*;
import java.io.*;
public class TestScoresAndSummaryStatistics {
public static void main(String[] args) throws IOException {
int scores;
int indices = -1;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the name of the file");
String fileName = keyboard.next();
//I believe something is wrong here, am I incorrectly bring inputFile into new File?
File inputFile = new File(fileName);
Scanner data = new Scanner(inputFile);
while (data.hasNext()) {
indices++;
}
System.out.println("There are: " + indices + "indices.");
}
}
I believe something went wrong with the = new File(filename); part: maybe because I didn't have quotes, but I'm not exactly sure. How can I fix this?
Solution:
Change
while (data.hasNext()) {
indices++;
}
to
while (data.hasNext()) {
indices++;
data.next();
}
Explanation:
You want to increment indices for every line. To achieve this, you should go to the next line and check if there are other available lines. Q: How can you go to the next line ? A: data.next();
E.g. - file.txt:
Your approach - bad:
Step 1
line a <--- here you are
line b
line c
Step 2
line a <--- here you are
line b
line c
...
data.hasNext() will be true forever because you will be on the first line at every step => infinite loop
Correct approach:
Step 1
line a <--- here you are
line b
line c
Step 2
line a
line b <--- here you are
line c
Step 3
line a
line b
line c <--- here you are
In this case data.hasNext() will return true only 3 times, then it will return false ( the file doesn't have any line after the 3rd line )
You only check if there is data in Scanner but you never consume it.
The java.util.Scanner.hasNext() method Returns true if this scanner has another token in its input. This method may block while waiting for input to scan. The scanner does not advance past any input.
The below code will never end if there is any data in file, you increase your counter with out reading the data.
while (data.hasNext()) {
indices++;
}

How to grab a number from a text file, while ignoring the word in front of it?

So I have a .txt file with only this as the contents:
pizza 4
bowling 2
sleepover 1
What I'm trying to do is, for example in the first line, ignore the "pizza" part but save the 4 as an integer.
Here is the little bit of code I have so far.
public static void addToNumber() {
PrintWriter writer;
Int pizzaVotes, bowlingVotes, sleepOverVotes;
try {
writer = new PrintWriter(new FileWriter("TotalValue.txt"));
}
catch (IOException error) {
return;
}
// something like if (stringFound)
// ignore it, skip to after the space, then put the number
// into a variable of type int
// for the first line the int could be called pizzaVotes
// pizzaVotes++;
// then replace the number 4 in the txt file with pizzaVote's value
// which is now 5.
// writer.print(pizzaVotes); but this just overwrites the whole file.
// All this will also be done for the other two lines, with bowlingVotes
// and sleepoverVotes.
writer.close();
} // end of method
I am a beginner. As you can see my actual, functioning code is very short and I don't know to proceed. If anyone would be so kind as to point me in the right direction, even if you just give me a link to a site, it would be extremely helpful...
EDIT: I stupidly thought PrintWriter could read a file
It's pretty simple actually. All you need is a Scanner, and it's function nextInt()
// The name of the file which we will read from
String filename = "TotalValue.txt";
// Prepare to read from the file, using a Scanner object
File file = new File(filename);
Scanner in = new Scanner(file);
int value = 0;
while(in.hasNextLine()){
in.next();
value = in.nextInt();
//Do something with the value here, maybe store it into an ArrayList.
}
I have not tested this code, but it should work, but the value in the while loop is going to be the current value of the current line.
I don't fully understand your question, so comment if you want some clearer advice
Here is a common pattern you'll use in Java:
Scanner sc=new Scanner(new File(.....));
while(sc.hasNextLine(){
String[] line=sc.nextLine().split("\\s");//split the string up by writespace
//....parse tokens
}
// now do something
In your case, it seems like you want to do something like:
Scanner sc=new Scanner(new File(.....));
FrequencyCloud<String> votesPerActivity=new FrequencyCloud<String>()
while(sc.hasNextLine(){
String[] line=sc.nextLine().split("\\s");//split the string up by writespace
//if you know the second token is a number, 1st is a category you can do
String activity=line[0];
int votes=Integer.parseInt(line[1]);
while(votes>0){
votesPerActivity.incremendCloud(activity);//no function in the FrequencyCloud for mass insert, yet
votes--;
}
}
///...do whatever you wanted to do,
//votesPerActivity.getCount(activity) gets the # of votes for the activity
/// for(String activity:votesPerActivity.keySet()) may be a useful line too
FrequencyCloud: http://jdmaguire.ca/Code/JDMUtil/FrequencyCloud.java
String num = input.replaceAll("[^0-9]", " ").trim();
For sake of diversity this uses regular expressions.

Categories

Resources