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.
}
}
Related
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.
I'm writing a really basic program, but I've run into a problem. The following is a slice of my code (it is a really silly program, don't try to guess what I'm using it for.)
System.out.println("Please press the Return button a 1000 times.");
for(int i = 1;i < 25;i++) {
input.nextLine();
}
System.out.println("Stop! Stop! Jeez, that was a joke! Do you think I'd make you press that button a 1000 times?");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {}
System.out.println("Let's move on.");
What would happen here is that the program asks the user to press the Return button a 1000 times, which the user would eventually start spamming. The main problem is that after I declare that it was a joke and he only needed to press it 25 times, I'd like to disable the user input, as it's likely that the user will press the button multiple times before realizing that I was just joking. But when the thread.sleep is running, the user input is still active, which leads to multiple problems.
So, is there any way to disable the user input while the program is sleeping?
You can control what to read from the console via application.. But to disable input entirely will be dependent on type of environment application is running on ... For E.g. in cmd line it should not allow you to type in after 25 enters... Whereas in IDE like eclipse, you can type in on console but it will not be read by application after 25 lines.
I believe that it is enough to add 1 line to your code (james large suggestion):
System.out.println("Let's move on.");
System.in.read(new byte[System.in.available()]);//read and ignore
Have a look at this:
public class Main {
private static final String QUIT = "quit";
private static final int COUNT = 1000;
public static void main(String[] args) throws InterruptedException {
new Main(new BufferedReader(new InputStreamReader(System.in))).main();
}
private final BufferedReader in;
private final BlockingQueue<String> lines = new ArrayBlockingQueue<>(1);
private volatile boolean ignore;
public Main(BufferedReader in) {this.in = in;}
private void main() throws InterruptedException {
Thread inputReader = new Thread(this::read, "input-reader");
inputReader.setDaemon(true);
System.out.println("Please press the Return button a "+COUNT+" times.");
inputReader.start();
String line = "";
for(int i = 1;i <= 25;i++) {
line = lines.take();
System.out.println("Good! You entered '"+line+"'. Only "+(COUNT-i)+" left.");
}
System.out.println("Stop! Stop! Jeez, that was a joke! Do you think I'd make you press that button a "+COUNT+" times?");
ignore = true;
Thread.sleep(3000);
ignore = false;
String optionalLine = lines.poll();
if(optionalLine!=null) {
line = optionalLine; System.out.println("Ignored:" + line);
}
System.out.println("Let's move on. Type "+QUIT+" when you're tired.");
while(!QUIT.equalsIgnoreCase(line)){
line = lines.take();
System.out.println(">"+line);
}
System.out.println("Bye.");
}
private void read(){
try {
String line = in.readLine();
while(line!=null){
if (ignore) {
boolean inserted = lines.offer(line);
if (!inserted)
System.out.println("Ignored:" + line);
} else {lines.put(line);}
line = in.readLine();
}
} catch (IOException|InterruptedException e) {e.printStackTrace();}
}
}
When I run the program if I type something other than "true" or "false" it throws a InputMismatchException.
do {
System.out.print("Do passengers have an individual tv screen?"
+ "(true OR false): ");
hasVideo = keyboard.nextBoolean();
bus.setIndividualVideo(hasVideo);
} while (!(hasVideo == true) && !(hasVideo == false));
Catch the error and treat it as a invalid response...
try {
System.out.print("Do passengers have an individual tv screen?"
+ "(true OR false): ");
hasVideo = keyboard.nextBoolean();
} catch (InputMismatchException exp) {
System.err.println("Please, enter only true or false");
}
Take a look at The try Block for more details
Aha, time to learn about Exception handling! Any of the Exception types that you see when java crashes can in fact be caught inside the program with a try-catch block.
try {
// code that might throw exceptions 1
// code that might throw exceptions 2
} catch (Exception e) {
// do something to fix the error
}
If any code in the try{ } part does throw an Exception then it will immediately skip to the catch( ) { } part, skipping any other statements in the try{ }.
Your code with a try-catch would look like:
boolean loopAgain = false;
do {
try {
System.out.print("Do passengers have an individual tv screen?"
+ "(true OR false): ");
hasVideo = keyboard.nextBoolean();
bus.setIndividualVideo(hasVideo);
loopAgain = false;
} catch (InputMismatchException e) {
System.err.println("Please, enter only true or false");
loopAgain = true;
}
} while (loopAgain);
Edit: I borrowed the println("Please, enter only true or false"); from #MadProgrammer's answer.
You have to prompt the user to enter a Boolean value. Because nextBoolean() can throw an exception, the best thing to do is to put that code inside a try/catch. The catch block code is only executed if anything other than true or false is entered. You can add a while() or do/while() loop to keep telling the user to try again. However, the most important thing to do in the catch block is to flush the input stream. Remember, even though there was an exception, the stream still contains stuff in it. It has to be properly consumed before using again. The code below should do exactly what you are looking for:
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
Boolean answer = null;
do
{
System.out.println("Enter either true or false");
try
{
answer = input.nextBoolean();
}
catch(InputMismatchException e)
{
System.out.println("ERROR: The input provided is not a valid boolean value. Try again...");
input.next(); // flush the stream
}
} while(answer == null);
input.close();
}
I am building an optimization into a JPEG-Encoder written in Java. To do my benchmark i want to extract the orginal code and the optimized code into separated jars. Each jar has to take two arguments. The first on for the file name and the secound for the repeat of the compression of the jpeg.
public static void main(String[] args) {
String filepath = args[0];
try {
int times = Integer.getInteger(args[1]);
runBenchmark(filepath, times);
} catch(IOException | NumberFormatException ioe) {
System.out.println("Your arguments are Wrong! Use the follow order!");
System.out.println("1. Argument must be the filename of the image.");
System.out.println("2. Argument must be a number to repeat the compression.");
}
}
This is my main, witch handle my args. I cant run the arguments on IntellJ . Even if I compile it the a jar, i cant pass my arg2.
I passed two arguments via configuration in intellj and i get a NullPointerException. So i tried to figure out if my java can take two arguments. I wrote a simple main in vim and compiled ran it with two args and worked. I repeated this in a new Project in intellj.
This is working. But why?
You have to check if the parameter is a int or not.
Use Integer.parseInt() and a try-catch block to inform the user if a failure happen.
int times = 0;
try {
times = Integer.parseInt(args[1]);
} catch (Exception e) {
System.out.println("failure with a parameter");
}
I changed the method to Integer.parseInt(string) and now it works. It was the Integer.getInt() it . I thought i had now 2. arg because I get the NullPointerException.
Now it work with this code.
public static void main(String[] args) {
try {
String filepath = args[0];
int times = Integer.parseInt(args[1]);
runBenchmark(filepath, times);
} catch (NumberFormatException nfe) {
System.out.println("2. Arg must be an number");
} catch (IOException ioe) {
System.out.println("File not found.");
} catch(Exception e) {
System.out.println("Your arguments are Wrong! Use the follow order!");
System.out.println("1. Argument must be the filename of the image.");
System.out.println("2. Argument must be a number to repeat the compression.");
}
}
I have a very simple loop that waits for a number (int) and as long as that number is not exitOption it does not leave the loop, however I get an unexpected error, and I don't know what's causing it.
Edit
Adding another snippet so you can compile
public static void main(String[] args) throws FileNotFoundException,
SecurityException,
IOException,
ClassNotFoundException {
while (controller.selectOptionMM());
/Edit
public boolean selectOptionMM() throws SecurityException,
FileNotFoundException,
IOException {
int cmd = ui.getExitOption();
ui.mainMenu();
cmd = utils.readInteger(">>> "); // this is my problem, right here
// code in next snippet
while (cmd <1 || cmd > ui.getExitOption()) {
System.out.println("Invalid command!");
cmd = utils.readInteger(">>> ");
}
switch (cmd) {
case 1:
case 2:
case 3:
case 4: this.repository.close();
return true;
case 5: return false;
}
return false;
}
Here is what fails:
public int readInteger(String cmdPrompt) {
int cmd = 0;
Scanner input = new Scanner(System.in);
System.out.printf(cmdPrompt);
try {
if (input.hasNextInt())
cmd = input.nextInt(); // first time it works
// Second time it does not allow me to input anything
// catches InputMissmatchException, does not print message
// for said catch
// infinitely prints "Invalid command" from previous snippet
} catch (InputMismatchException ime) {
System.out.println("InputMismatchException: " + ime);
} catch (NoSuchElementException nsee) {
System.out.println("NoSuchElementException: " + nsee);
} catch (IllegalStateException ise) {
} finally {
input.close(); // not sure if I should test with if (input != null) THEN close
}
return cmd;
}
First time I pass trough, it reads the number no problem. Now if the number is not 5 (in this case exitOption), it passes again trough readInteger(String cmdPrompt) except this time it jumps to catch (InputMismatchException ime) (debug) except it does not print that message and just jumps to Error, input must be number and Invalid command.
Is something stuck in my input buffer, can I flush it, why is it (input buffer) stuck (with random data)???
I'll try debugging again and see what's stuck in my input buffer, if I can figure out how to see that.
The problem is in the call to input.close() - this causes the underlying input stream to be closed. When the input stream being closed is System.in, bad things happen (namely, you can't read from stdin any more). You should be OK just eliminating this line.
input.hasNextInt()
This line throws the exception if there is no Integer, so instead of it going to else block it forward to catch block. It will never go to else block if exception get caught.