So I have an If Statement. It's set to compare a value taken fron user input using JOptionPane.showInputDialog. But if the values are the same, it doesn't do anything...
Example: The user has to enter the value 4. When the Input Dialog appears, the user types 4.
Then, it's supposed to win, because if userInput = 4 {win}. But even if the userInput is 4, nothing will happen...
I thik I'm not explaining very well...
EDIT: Ok, I found the problem... I'm stupid... The problem was I declared another int for the num inside the method, so it wasn't reachable outside the method...
It's important to remember that the input dialog takes strings so the number that you enter will actually be stored in memory as a String object.
int intInput = Integer.parseInt(stringInput);
That will parse the user's input and store as an integer. It's probably best to check that it's possible to parse the input before actually parsing so that the program doesn't crash/bug out.
EDIT: You could also do this:
if(userInput.equals("4")) {
JOptionPane.showMessageDialog(null, "win");
}
Ok, I found the problem... I'm stupid... The problem was I declared another int for the num inside the method, so it wasn't reachable outside the method...
Related
this is my click event. The code is supposed to extract entries from text controls and use it to make calculations. At this stage I m trying to make sure that the user enters all of the values that are required, that is: marks for assignments 1, 2, 3 and the exam mark. I realize that I had not entered the "!" to indicate that the controls should not be empty
I believe you wanted to do something like this:
Double assign1;
String stringAssign1 = mark1.getText().toString();
if (!stringAssign1.isEmpty()){
assign1 = Double.parseDouble(stringAssign1);
}
Firstly, you should check if string is empty (also as mentioned before isEmpty() is string function), then if not, parse it to double.
Next time please use codeblock instead of screenshot of code :)
to summarise it give me any idea or solution on how I could fix it.
I tried what is given in the code below.
System.out.print("Want to continue Shopping or end your shopping spree and want the bill for your shopping (answer in Y or N)");
String end = sc.next();
if(end =="Y")
System.out.println("hello");
I expect the output hello in the above code, but the actual results are nothing the program just ends.
First of all, I have no idea what your question is about exactly. I can't see any information on which programming language you are using (I suppose Java) or on which operating system you are working.
But I've got an idea what the problem might be: As you are using stdout, I suppose the program happens on a Console or Terminal. And in some environments, the cmd window will close after there program terminated (when working with an IDE like VS Community, which I don't know if you do or not, given no context). If this is the case, "hello" will be printed but you won't see it because the window closes immediately. Try to add some kind of getline at the end and try again.
Supposing sc is a Scanner object.
String comparison must be done with the equal method instead of using == because by doing that you'll compare the object's referer in the memory instead of the String content, try this:
System.out.print("Want to continue Shopping or end your shopping spree and want the bill for your shopping (answer in Y or N)");
String end = sc.next();
if(end.equals("Y")) {
System.out.println("hello");
}
So basically this code is supposed to keep asking "Please insert a valid number" until an integer is introduced through the keyboard. It works just fine, I'm just curious as to how it actually does what it does.
Scanner input = new Scanner(System.in);
System.out.println("Please insert the number of lives.");
while (!input.hasNextInt()) {
input.next();
System.out.println("Please insert a valid number.");
}
numberOfLives = input.nextInt();
In my head it would make more sense to put the numberOfLives = input.nextInt(); line inside of the while loop. This is basically what I'm understanding from this snippet once it reaches the while loop:
Check condition in while, if input scanner variable doesn't have an int value, do the following
Discard what is in the input scanner variable
Print out the valid number message
Obviously this isn't how it goes, else this snippet wouldn't work. I'm thinking maybe each time it checks the condition, the actual !input.hasNextInt() opens up the buffer again for input and THEN checks what's inside, but I have no clue.
Sorry if I'm not using the terms correctly, pretty now to all of this stuff.
Thanks!
Like an iterator, scanner will always point to the element before the stream starts. i.e. if the list starts with position 0, scanner will point to -1st position. next() will advance the scanner and return the element present at location.
In this code, we are checking if the next element is integer. If it is not, why to advance the scanner?
New programmer here, having some problems with some code about what I would think is recursion.
public static int sum (int a) {
int input = goodInput(); //get input from below method without having to put its code in this one
if (input==-1)//so user has the ability to exit at any time
return a; //when user has finally entered -1, the final sum is sent out
else; //for scenarios before last input
int b = a + input; //adding the newest input to the sum
int c = sum(b); //throw the total into the method again until -1 is read
return c; //once -1 is read, a in that iteration is sent up through every iteration of the method until the original method gets its return
}
public static int goodInput () { //code to get input of correct type
Scanner input = new Scanner (System.in);
while (!input.hasNextInt()) { //if I put in integer input, the loop should not be entered, but this isn't happening
System.out.println("Integers only please");
input.next();
}
int finalInput = input.nextInt(); //Finally set good input
input.close(); //close scanner
return finalInput;
}
First method here is clearly just a way to get a sum. I know there are multitudes of other ways to just sum some numbers together, I've done a few myself, but when my class had its lesson on methods and wrote it up having something like the code I listed was the first thing I could think of as a solution, rather than what the teacher ended up recommending. Thought it would be a good learning exercise, in any case.
This code doesn't show any errors in eclipse, so I am stumped as to why it refuses to work. Indeed, it produces results I am really curious of; it naturally asks input at the beginning of the program, but when I enter 0, 1, or any other int, despite the scanner actually having an integer, "Integers only please" is printed, followed by Java announcing exceptions at the end of the while loop, at goodInput's calling in sum, at the return of c, and at the execution of sum in the main method, as well as at java.util.NoSuchElementException, java.util.Scanner.throwFor, and at java.util.Scanner.next.
I have very little idea what is happening here; my best guess would be memory issues, but bugs start occuring at the very first occasion! And the code in goodInput works perfectly well when just used as the main method; not sure why it being called by sum would cause problems.
Again, I don't just want some sum method. I just want to know why the code is behaving in this manner, and how an implementation of sum with my approach would actually work.
Not recursion is the problem here, but your Scanner. I have to admit that I am not too familiar with the Scanner class, but it seems that if you call input.close() and then reenter goodInput later, your System.in is closed. At least, stepping through with the debugger, I found that the line "Integers only please", is printed in the second invocation of goodInput. Deleting the line input.close(); did the trick for me, and your method worked as intended.
I'd suggest you initialize your scanner in the main method, pass it as an argument, and close it in the main method afterwards.
Edit:
The close method of the Scanner states the following:
If this
scanner has not yet been closed then if its underlying
java.lang.Readable readable also implements the java.io.Closeable
interface then the readable's close method will be invoked.
So, the underlying reader, i.e., System.in, was closed when you called close on the Scanner.
I am trying to write an If or If-Else Statement that protects the program when an integer value is not entered when prompted. I keep getting the error message: '.class' expected.
System.out.println("Type the name of your destination: ");
destination = keyboard.nextLine();
System.out.print(destination + " is how many miles away?");
miles = keyboard.nextInt();
if (miles != int);
{
System.out.println(miles + " is not valid. I will use 100 for the number of miles.");
}
This can not compile:
if (miles != int);
You are comparing a variable with int,which is a type. The compiler suggest you to add .class, so you can obtain the class object, but it is not correct either.
You want to know if an integer value is not entered, but in that case what would happen is that nexInt() would throw a InputMismatchException. What you should do is to check with hasNextInt() if the user is inputing an integer.
int is a keyword and cannot participate in conditional expressions.
There is also a spurious semicolon after your if statement, which acts as the controlled statement, so the following block is unconditional.
The syntax error that you are getting is because int is a keyword. You cannot use it as an identifier.
If you would like to check if a Scanner has an int ready for reading, use keyboard.hasNextInt() in your condition:
int miles;
while (!keyboard.hasNextInt()) {
System.out.println(keyboard.nextLine() + " is not valid. Please enter a different number.");
}
int miles = keyboard.nextInt();
you have a ; after the if statement.
You also have it checking what the user inputs to an int which is not a number. might want to fix that with a number and it should work... from what i can remember from class.
if (miles != int);
You can't test if a number is an int like that. You also have a semi colon at the end of this line (which should be removed). However, there's actually no reason to have that line at all. Because you wrote:
miles = keyboard.nextInt();
miles has to be an int. Otherwise an exception will be thrown by Scanner.
I'm going to start this by saying that you need to do a Java Tutorial. Your code is full of basic mistakes.
(Assuming that keyboard is an instance of Scanner ...)
Mistake 1 - You cannot use a type name or keyword (e.g. int) as a value.
Mistake 2 - You can only use == to compare integer values (like the value of miles) with other numbers.
Mistake 3 - You shouldn't put a semicolon after if (condition). What you have written will compile, but it actually means "if the condition is true, then execute the empty statement". Then you've followed that with a block ... that will be executed unconditionally.
Mistake 4 - In fact, if keyboard.nextInt() encounters something that isn't a valid integer, it will throw an exception; e.g. InputMismatchException. If you want to print out an error message, you need to catch that exception.
Mistake 5 - Obviously you didn't check the javadoc for the nextInt() method ...
To recap ... you are making so many mistakes because you haven't done the tutorial ... or you've been skipping lectures or something.