If does not work when Y is entered as the statement.
+And how do I read and change config.cfg file?
My code is as below.
package myfirstpgram;
import java.io.*;
import java.util.*;
public class MidiBot {
public static void main(String args[]) throws InterruptedException, SecurityException, IOException {
File FolderDD = new File("./ProgramMF_Data"); // Set Program data to var(./ProgramMF_Data)
try {
FolderDD.mkdir(); // create Folder ProgramMF_Data
System.out.println("successfully created folder."); // print success to create folder
}
catch(Exception e) { //Catch error
e.getStackTrace(); // ?
e.printStackTrace(); // print error info 1
System.out.println("ERROR1 - Can't create Directory."); // print error info 2
System.exit(1);
}
System.out.println("Did you run the program for the first time? [Y/n]");
String FirstEM;
FirstEM = sc.nextLine();
if ("Y".equals(FirstEM)) {
System.out.println("Please Create ./ProgramMF_Data/config.cfg");
System.out.println("and set content like below");
System.out.println("\n[Config]"); //
System.out.println("FirstTime=1"); //
Thread.sleep(60000); // Sleep 60 seconds
System.out.println("\nProgram closes in 4 seconds!"); // info
Thread.sleep(4000); // sleep 4 seconds
System.exit(0); // Close program
}
System.out.println("Welcome again"); // print "Welcome again"
}
}
It looks like your post is mostly code; please add some more details.
your code seems correct, though an issue could arise when you enter a lower case "y".
a better approach would be
"y".equalsIgnoreCase(FirstEM);
And also you need to initialize scanner.
Scanner sc = new Scanner(System.in);
as for the config file, if it is a properties file then
check this link
You need to declare and initiaize a scanner before being able to use it
Please add Scanner sc = new Scanner(System.in); before using it.
I would also recommend you to take a small break and look up some naming conventions.
Related
import java.util.Scanner;
public class HelloWorld
{
public static void main(String[] args)
{
Scanner math = new Scanner(System.in);
System.out.println("What is 2 + 2?");
int num = math.nextInt();
System.out.println("Wrong."); // Displays "Wrong." no matter the answer.
{
Thread.sleep(2000); // Adds a timer for 2 seconds.
}
catch(InterruptedException e)
{
System.out.println("Please, try again :-)");
}
int num1 = math.nextInt();
System.out.println(""); //Displays some message.
}
}
The code is supposed to display "What is 2 + 2?", a user inputs an answer, the code returns "Wrong." no matter what the answer. After a 2 second pause, the code displays "Please, try again :-)" and a user inputs an integer and the code returns a message.
The errors occur on the line with the catch token. The errors are:
Syntax error on token "catch", ( expected,
Syntax error, insert "-> LambdaBody" to complete LambdaExpression,
Syntax error, insert "AssignmentOperator Expression" to complete Assignment,
Syntax error, insert ";" to complete Statement
To use a catch in java you need to have a try. It is called a try..catch block. Please read the documentation here
So, adding a try as follows should get rid of the errors you are asking about here :
System.out.println("Wrong."); // Displays "Wrong." no matter the answer.
try // Looks like you missed the try here
{
Thread.sleep(2000); // Adds a timer for 2 seconds.
} catch (InterruptedException e) {
System.out.println("Please, try again :-)");
}
I cant see try block. you can use this way also without try catch. Main method can throw InterruptedException ...
public class HelloWorld {
public static void main(String[] args) throws InterruptedException {
Scanner math = new Scanner(System.in);
System.out.println("What is 2 + 2?");
int num = math.nextInt();
System.out.println("Wrong."); // Displays "Wrong." no matter the answer.
{
Thread.sleep(2000); // Adds a timer for 2 seconds.
}
int num1 = math.nextInt();
System.out.println(""); //Displays some message.
}
}
Here is my code: https://pastebin.com/1Cmg5Rt8
The program asks the user for their name.
It then generates random math problems, and counts correct answers and incorrect answers.
The user is rewarded $0.05 for correct answers and penalized $0.03 for incorrect answers.
All of the above has been done.
I am stuck starting from here:
A file is created using their name.
The amount of answers they got correct/incorrect are recorded to a text file.
If a file under their name already exists, I must combine their results with the results of the ones on the file.
Example of existing text file:
Correct answers: 1
Incorrect answers: 0
Earnings: $0.05
If the user runs the program again and gets 1 correct answer, it must be updated like this:
Correct answers: 2
Incorrect answers: 0
Earnings: $0.10
Currently, instead of updating, it is being overwritten.
If I choose show stats at the beginning, this is the result (it uses the initialized values):
Correct answers:0
Incorrect answers: 0
Earnings: $0.00
I have spent hours trying to figure this out. I refuse to sleep until I solve this. Someone please help me. I will greatly appreciate it.
You need to read the name in /before/ you retrieve the stats, i.e. your main method should look like this:
public static void main(String[] args) {
validateCreditsResponse();
name();
retrieveStats();
menu();
saveStats();
}
Also, in this method, you need to also output a println like you do in the 'else' branch:
if (money > 0) {
outputfile.printf("Earnings: $%.2f", money);
// Add outputfile.println();
}
Finally, in this method you need to read in the data:
//Creates new text file for the user unless one already exists.
public static void retrieveStats() {
try {
writer = new FileWriter(userName + "Stats.txt", true);
outputfile = new PrintWriter (writer);
} catch (IOException e) {
}
}
You would start doing this with a FileReader, rather than a FileWriter.
For example in Java 8, like this:
//Reads existing text file for the user.
public static void retrieveStats() {
try (BufferedReader br = new BufferedReader(new FileReader(userName + "Stats.txt"))) {
String line;
while ((line = br.readLine()) != null) {
Matcher correctMatcher = Pattern.compile("Correct Answers:(.*)").matcher(line);
if (correctMatcher.matches()) {
correct = Integer.valueOf(correctMatcher.group(1));
}
// TODO complete other matchers
}
} catch (IOException e) {
}
}
I'm in a computer science (java) class right now and our task is to create a program that reads integers from an input.txt file (the professor will have this) and prints out all the integers into an output.txt file. Any exceptions/errors will need to be printed to an errors.txt file that our program creates. (We are learning about Exceptions in class now).
My program is able to read from an input file and print out just the integers to an output.txt, but I'm having problems printing out all the exceptions that might occur. For example, if the input file has "abc" as one of the lines, it should print out a message in the errors.txt file saying that it isn't an integer.
What happens with my program is that as soon as one exception is thrown, it doesn't keep going to print out all the other exceptions even if there are more to print. It just stops at that point.
So for example, something like this:
try{
while (fileScan.hasNext())
{
num = fileScan.nextInt();
}
}catch(Exception e)
{
erout.println(e); //prints the error to the file.
fileScan.nextLine();
}
erout is my PrintWriter object for the error.txt file. fileScan for the input.txt.
I'm just not sure how to get it to go through all of the input.txt file and keep track of all the exceptions it will throw, then print all those to an error.txt file. Any help would be appreciated, thanks. :)
You could move the while loop outside of the try statement.
while (fileScan.hasNext())
{
try{
num = fileScan.nextInt();
}catch(Exception e)
{
erout.println(e); //prints the error to the file.
fileScan.nextLine();
}
}
You need to re-order your while and try/catch:
List<Exception> exceptions = new ArrayList<>();
while (fileScan.hasNext()) {
try {
num = fileScan.nextInt();
// more code here to process num
} catch (Exception e) {
// Might also want to create a custom exception type to track
// The line/file that the error occurred upon.
exceptions.add(e);
fileScan.nextLine();
}
}
All you gotta do is move the try/catch within the while:
while (fileScan.hasNext())
{
try {
num = fileScan.nextInt();
}
catch (Exception e) {
erout.println(e); //prints the error to the file.
fileScan.nextLine();
}
}
This question already has answers here:
How do I create a file and write to it?
(35 answers)
Closed 8 years ago.
I've just started on my college journey ( 'Yay' ). I'm also new to the site so feel free to lecture me on things I may have done wrong as far as asking questions is concerned.
I was given a project, which has already been graded and all, and the program should ==>> first read lines of standard input (Input file name using keyboard) and for each line of input, if the user enters exit, the application terminates; otherwise, the application interprets the line as a name of a text file. The application creates or recreates this file and writes to it two lines of output, the name of the file and the current date and time. The application then closes the file, reopens it for reading, and writes its contents to standard output. The application writes to standard output the name of the file enclosed by square brackets. After writing the file name,
the application writes the contents of the file with each line prefixed by its corresponding line
number, a full colon, and a space.
I have worded it just as my professor did, so I apologize for any unclear statements. Here's what I got for it:
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.io.File;
import java.io.ObjectInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Scanner;
public class Project1
{
public static void main() throws IOException
{
String input = "";
while(!sc.equals("exit"))
{
System.out.println("Enter file here!\n Type 'exit' to terminate");
Scanner sc = new Scanner(System.in);
input = sc.nextLine();
try
{
File file = new File (input,".txt"); // Creates pointer to a file.
ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
file.createNewFile();
file.getAbsolutePath();
printFileAndDate(file);
}
catch(IOException e)
{
System.out.print("Something wrong :(");
e.printStackTrace();
}
}
System.exit(0);
}
static void printFileAndDate(File temp)
{
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
System.out.println("[ " + temp.getPath() + " ]");
System.out.println(dateFormat.format(cal.getTime()));
}
}
What I attempted to do there was the following:
-Get User Input => Save Input as a file => Call method "printFileAndDate" and print the file along with the current date and time in the correct format.
However, whenever I run it, it always gives me an exception error, which means the file was never really created or that it isn't able to find it.
The list of ISSUEs, I could find :
First, your main method signature is totally wrong
public static void main() throws IOException
change to
public static void main(String[] args) throws IOException
Second, it is not a good practice to throws exception inside main method.
The good practice is to use try catch block
Third, you have your Scanner varialbe after the while loop which does not make sense
while(!sc.equals("exit"))
{
System.out.println("Enter file here!\n Type 'exit' to terminate");
Scanner sc = new Scanner(System.in); <-?!!!!!!
change to
System.out.println("Enter file here!\n Type 'exit' to terminate");
Scanner sc = new Scanner(System.in);
while(!sc.equals("exit"))
{
Fourth , you define File variable this way
File file = new File (input,".txt"); <-- totally wrong
change to
File file = new File ("input.txt"); <-- if you use relative path
Fifth there is not need for System.exit(0);at the end of main method
I have the basics of my program finished.
The idea is that the user can specify a shape color width height etc. Upon inputting the data, constructors are called which create output, or there are other options which create output that the user can specify.
My goal is to get all of this output into a text file.
Currently I create a scanner for reading:
static Scanner input = new Scanner(System.in);
Then in my main driver method I create a Formatter:
public static void main(String[] args) {
Formatter output = null;
try{
output = new Formatter("output.txt");
}
catch(SecurityException e1){
System.err.println("You don't have" +
" write accress to this file");
System.exit(1);
}
catch(FileNotFoundException e){
System.err.println("Error opening or" +
" creating file.");
System.exit(1);
}
After each time I expect output I have placed this bit of code:
output.format("%s", input.nextLine());
And finally I close the file with
output.close()
The file is created but it is currently blank. I know I'm on the right track, because I've tried doing this:
output.format("%d", i);
where i is an integer of 0 and the file writes correctly.
However, I cannot seem to get it to work for an entire line, or for the output at all.
Please help!
I am not an expert but why can you not just use "FileWriter"?
Is it because you want to catch those exceptions to display useful information to the user?
Or have I misunderstood the question completely? - If so, sorry and just disregard this.
import java.io.FileWriter;
import java.io.IOException;
try
{
FileWriter fout = new FileWriter("output.txt"); // ("output.txt", true) for appending
fout.write(msg); // Assuming msg is already defined
fout.close();
}
catch (IOException e)
{
e.printStackTrace();
}