If or If-Else Statement Error - java

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.

Related

Does anyone know what's happening with infinite loops and StackOverflow error while using recursive call?

This is a part of a program I'm making for practice, its purpose doesn't really matter.
I have declared the Scanner as a field of the class** (it's not written here sorry).
I want to make a method that returns an answer specified to the users input. And I want to make all the neccesary checks needed so the user can't input a character or symbol, just an integer. When the input data is of the wrong type I want the user to try input again.
public static void Answer() {
System.out.println("\n\t1.It was good! \n\t2.Kinda bad too...");
System.out.println();
if (scanner.hasNextInt()) {
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.println("Oh great!");
break;
case 2:
System.out.println("I see you as well");
break;
default:
System.out.println("Please select a valid answer :");
Answer();
break;
} else {
System.out.println("Please select a number, characters are not acceptable!");
Answer();
}
When I enter an invalid number like 3,4 etc the algorithm triggers the switch block and the recursive call as well, working just fine!
BUT when I enter a character it triggers an infinite recursive call without letting me enter new input form the scanner and ends up in StackOverflow error.
You check if the Scanner has an int. If it does not, then it goes to the else branch.
In the else branch, it calls Answer() again. But here's the catch: your scanner still doesn't have an int. So scanner.hasNextInt() returns false. hasNextInt() does not try to read anything - it merely checks if there is input that can be interpreted as an int.
(Source: Java documentation).
So the program goes again to the else branch, without ever reaching the point where it can try to read input... and there it calls Answer() again. Now, the code still doesn't have an int... so once again, scanner.hasNextInt() returns false, and it goes to the else branch. Once again, it does not get to the part where the scanner consumes input, but instead gets to the part where it calls Answer() again...
And this will continue, until the call stack is full and you get the StackOverflow error.
You'll have to take care of the situation that the user enters something that is not an int. You'll have to consume that input that is not an int.
As an aside, I'd prefer to do this using iteration, rather than recursion.

Don't understand how Java Scanner object is working in this example (hasNextInt, next...?)

In my program I need to take an input from a user, but it must be an integer. If the user doesn't input an integer, I need the program to reprompt them to enter an integer, and keep doing so until they enter one. I found an example while loop code snippet online which works perfectly, but I am having problems understanding why and how it works, and I'd really like to understand better:
Scanner reader = new Scanner(System.in);
int guess=0;
System.out.println("Guess the number");
while (!reader.hasNextInt()) { //I get that this is a "not have" boolean
System.out.println("That's not a number. Please enter a valid number");
reader.next();
}
guess= reader.nextInt();
System.out.println(guess);
My questions are:
Does the !hasNext condition in the while loop actually trigger the scanner object to ask the user for input and then check that input, or does it only check anything that has already been inputted?
Why is it necessary to have the reader.next(); line after the while loop's main statement and what is this doing exactly? I know it's necessary as the program doesn't work when I take it out. But is it prompting for input? If yes what happens to this input?
When guess= reader.nextInt(); runs, why doesn't it re-prompt the user for input at this point?
Sorry that these are probably really basic questions, I'm new to coding and Java and just can't get my head around what's happening internally in this particular example, though have no problem doing other basic stuff with the Scanner.
It's not particularly intuitive, for sure, so don't feel bad for not getting it immediately.
It seems to me that the problem you're having with your understanding is that that methods such as nextInt may or may not prompt for user input, depending if anything is already in the Scanner.
Here's the sequence of events:
All your code executes until you hit !reader.hasNextInt(). There's no input so it "blocks" (waits) until there is some input from the user.
If the user enters 'A', that's not an integer so we enter the body of the while loop. We then print the error message.
Now, hasNextInt doesn't "consume" (process) the user input when it's checking whether or not it's an integer, so we still have that invalid user input of 'A' sitting in our scanner. We call reader.next() to effectively discard that value.
Now we're back to !reader.hasNextInt(). The scanner is empty once again, so we prompt for user input. If they enter another non-integer, that process will simply keep repeating.
Say this time we do have a valid user input - they've entered the number 2. This passes the check so our while loop ends and we continue along.
We've now got some input in our scanner, but we've not consumed it. We're sure it's an integer because of the while loop condition. We can now consume the input with reader.nextInt() and assign it to our variable.
hasNextInt() only checks whether the next input is an integer. It won't consume any input at all. The ! is just negate theu outcome of this function.
As hasNextInt() won't consume, then we need to use next() to consumeo the user input to let hasNextInt() to check with user's next input value. As you won't need it at all, then no need to assign it to any variables.
Scanner won't display the prompt at all. The prompt is printed by System.out.println().
For the line nextInt(), it is used to consume the next user input. Since hasNextInt() must be true when it execute this line, there must be one integer input waiting for consumption, so this method can return immediately with that user input.
Try it :)
public static void main(String[] args) {
int option;
if(args!=null&&args.length>0){
option = Integer.parseInt(args[0]);
}
else{
System.out.println("Enter:\n 1 to run x \n 2 to run y \n");
Scanner keyboard = new Scanner(System.in);
option = keyboard.nextInt();
}
switch (option) {
case 1:
xx
break;
case 2:
yy
break;
default:
break;
}
}

Java "While" Loop -- Counting Matches Algo - Assigning value must occur inside the while loop

I apologize in advance; I couldn't find the answer to this simple question in Search.
I'm a newbie to coding. Currently on Udacity working my way through the Intro to Java Programming course.
There's something that I'm not understanding as it relates certain Algorithms.
Take the "counting matches" algo for example.
The assignment of double input = in.nextDouble(); needs to occur inside the while-loop.
If I place it just above the while-loop, it breaks the program. Why?
It seems to me that Java shouldn't care when the value is stored in the variable.
import java.util.Scanner;
public class CountingMatches
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int counter = 0;
System.out.print("Enter a value, Q to quit: ");
// double input = in.nextDouble(); // remember to place the assignment of this variable inside the while loop.
// I tend to want to place this outside the while loop because I still don't
// understand why it necessarily must occur inside the while loop.
while (in.hasNextDouble())
{
double input = in.nextDouble(); // this assignment is properly located here as opposed to just above the while-loop
if (input < 0)
{
counter++;
}
System.out.print("Enter a value, Q to quit: ");
}
System.out.println("The water line fell on " + counter + " years.");
}
}
Because in.nextDouble() can only be used if Scanner has already confirmed the next token can be parsed as a double. In addition to waiting for user input, this is what hasNextDouble() guarantees for you. If you take it out of the loop, not only are you skipping that hasNextDouble() guarantee (and not giving the user a chance to input anything), you are also only running nextDouble() one time, so you wouldn't have the newest value anyway.
Returns true if the next token in this scanner's input can be interpreted as a double value using the nextDouble() method. The scanner does not advance past any input.
-- https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html#hasNextDouble--
since you can´t do any further input when you move it outside the loop the condition for the loop in.hasNextDouble() will allways be true. Afterwards you will be stuck in an infinite loop, which makes the programm like like it´s brocken, but actually it´s just repetitively looping and printing until you stop the java process by yourself.
You are right that java shouldn't (and doesn't) care when the value is being stored in a variable, but there is more to it.
in.hasNextDouble() doesn't return until the line inside the wrapped input stream has ended.
It does not alter the stream in any way, but it guarantees there is a character sequence waiting in the stream and if true can be parsed as a double. The buffer is not altered until nextDouble() is called.
This is what breaks your code. When you remove the line from the buffer without it being parseable to a double an exception is thrown, because no characters are waiting in System.in

If statement not comparing JInputDialog value

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...

Basic imperial conversion problem

Coding a calculation tool for my android. On of the inputs is distance in Feet and Inches.
I have two inputs (input3 and input4) for feet and inches, respectively. In my calculation I am trying to convert these two inputs to a decimal number to be used in the rest of the equation. Here's the part of my code that does this:
private void doCalculation() {
// Get entered input value
String strValue3 = input3.getText().toString();
String strValue4 = input4.getText().toString();
// Perform a hard-coded calculation
double imperial1 = (Integer.parseInt(strValue3) + (Integer.parseInt(strValue4) / 12));
// Update the UI with the result to test if calc worked
output2.setText("Test: "+ imperial1);
}
My test values are 4 feet, 6 inches. The 4 comes across fine, but the 6 inches defaults to 0 when it is divided by 12. So my result is 4.0 I tried cutting the calculation down to JUST the division operation, and the result was 0.0
What am I doing wrong? (fyi: this is my first time using Java)
Your types are wrong. You're parsing them as ints when they really should be doubles.
Try:
double imperial1 = Double.parseDouble(strValue3) +
(Double.parseDouble(strValue4) / 12.0);
... what Eli said.
I just wanted to ask why your variables are called strValue3 and strValue4. I'm guessing that it's generated, but you should get into the habit of naming things well. I might go with "feet" and "inches" :)
Eli's answer will work fine. I'm just posting an answer to your question (comment) on Eli's answer.
Can you explain what a try-catch block is?
First you have to understand what an exception is. An exception is an event, which occurs during the execution of your program, that disrupts the normal flow of the program's instructions.
There are 3 kinds of exceptions in Java:
Runtime exceptions: An exception is referred to as a runtime exception if its data type is java.lang.RuntimeException or a subclass of it.
Checked exceptions: An exception is referred to as a checked exception if its data type is a child class of java.lang.Exception, but not a child class of RuntimeException.
Errors: An exception is referred to as an error if its data type is a child class of java.lang.Error. An error is associated with problems that arise outside of your application and typically do not attempt to recover from errors.
For a more detailed description on exceptions, read this.
In order to catch and handle these exceptions, you use try-catch blocks. For example, you use Double.parseDouble function. If the parameter in this function is not a valid number, for example if the user supply the string "NotANumber" you try to convert it to double, then a NumberFormatException will be thrown by Double.parseDouble. If you don't handle this error, your program will terminate unexpectedly.
So, you should write something like the following (including the positive numbers feature you want):
double imperial1 = 0.0;
try {
double firstNumber = Double.parseDouble(strValue3);
double secondNumber = Double.parseDouble(strValue4);
if(firstNumber < 0 || secondNumber < 0)
throw new NumberFormatException("numbers must be positive.");
imperial1 = firstNumber + secondNumber / 12.0;
} catch(NumberFormatException ex) {
// Handle the exception maybe by printing a message to the user that his inputs
// weren't valid numbers.
}

Categories

Resources