Error "else" without "if" [closed] - java

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I have this program set up and i need help with 2 errors that i am getting
import java.util.Scanner;
public class EvenOdd {
public static void main(String[]args) {
Scanner keyboard = new Scanner (System.in);
System.out.print("---EvenOdd--- /n");
System.out.printf("Enter a whole number: ");
c = in.nextInt();
}
public static EvenOdd (int num) {
int c = num;
if (int.class)
(c/2)*2 = c;
System.out.println("is even.");
else (c)
System.out.println("is odd");
return EvenOdd;
}
}
C:\Users\Desktop\EvenOdd.java:28: error: not a statement
else (c)
C:\Users\Desktop\EvenOdd.java:28: error: 'else' without 'if'
else (c)
2 errors

Your else doesn't make sense. First of all, you are not using braces, but also your boolean logic does not make sense. Just adding braces will not make your code compile.
I think this rewrite is the closest to what you have
public static boolean EvenOdd (int num) {
// Here your calculation is done
boolean isEven = (c/2)*2 == c;
if (isEven) {
System.out.println("is even.");
} else if (!isEven) {
// Using 'else if' for a boolean parameter does not make much sense
// but i'll leave it here to explain the syntax
System.out.println("is odd");
}
return isEven;
}
However, the most common way to check for odd or even is using the modulus operator. And if i make the entire code a bit more java-ish, you'd end up with (for example method-naming)
/**
* Check if the given number is even.
* #param num the number to check
* #return whether num is an even number
*/
public static boolean isEven (int num) {
if ((x % 2) == 0) {
System.out.println("is even.");
return true;
} else {
System.out.println("is odd");
return false;
}
}

Here is a solution
public static void main(String[]args)
{
Scanner keyboard = new Scanner(System.in);
try{
System.out.println("---EvenOdd---");
System.out.print("Enter a whole number: ");
int c = keyboard.nextInt();
evenOdd(c);
}finally{
keyboard.close();
}
}
public static void evenOdd(int num)
{
int c = num;
if ((c/2)*2 == c){
System.out.println("is even.");
}else {
System.out.println("is odd");
}
}
Output:
for the input value 5
---EvenOdd---
Enter a whole number: 5
is odd
for the input value 4
---EvenOdd---
Enter a whole number: 4
is even.
Continued Reading
There are several problems with the original code and I will attempt to explain them in line order.
Original code for reference:
public class EvenOdd {
public static void main(String[]args) {
Scanner keyboard = new Scanner (System.in);
System.out.print("---EvenOdd--- /n");
System.out.printf("Enter a whole number: ");
c = in.nextInt();
}
public static EvenOdd (int num) {
int c = num;
if (int.class)
(c/2)*2 = c;
System.out.println("is even.");
else (c)
System.out.println("is odd");
return EvenOdd;
}
}
First we have this line
System.out.print("---EvenOdd--- /n");
use of the .print() method here, while not illegal is unnecessary because java provides us with .println() which automatically creates a new line so we don't have to. (i.e. with "/n")
System.out.printf("Enter a whole number: ");
Next you use the .printf() method, this prints a formatted output and accepts arguments as a parameter. You aren't using any of the exclusive features of this method so we can achieve the same functionality with .print().
c = in.nextInt();
the variable in is not defined in this scope, I presume that you meant to use keyboard.nextInt().
public static EvenOdd (int num) {
when a method has no return type and the same name as the class it resides in (case sensitive) it is a constructor. Constructors do not require a return statement and are invoked with the syntax new ObjectConstructor() usually to assign a value to a variable of the same type as the constructor.
if (int.class)
(c/2)*2 = c;
System.out.println("is even.");
else (c)
System.out.println("is odd");
This if-else block is clearly not even java syntax.
first there is no need to cast your result to an int and the semicolon at the end of your conditional doesn't belong.
removing these errors brings us to:
if (c/2)*2 = c
System.out.println("is even.");
else (c)
System.out.println("is odd");
now we need to wrap our conditional in parentheses '( and )' and rather than use the assignment operator '=' we should use the comparison operator '==' which returns a boolean. Also, the else clause does not require a condition, if you would like to use a condition look into elseif.
these changes get us to this step.
if ((c/2)*2 == c)
System.out.println("is even.");
else
System.out.println("is odd");
Now we add proper brackets and we are good to go.
if ((c/2)*2 == c){
System.out.println("is even.");
}else{
System.out.println("is odd");
}

Related

how can i check if the number is perfect square by not using math.sqrt

i want to make a program which related to this question:
An integer that can be expressed as the square of another integer is called a perfect square, such as 4,9,16,25, etc. Write a progran that checks if a number is a perfect square.
I did built something goes like:
import java.util.Scanner;
class Q3{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int num = 0;
int a = 0;
System.out.println("Type a number to check if it has square");
num = sc.nextInt();
for(a = 1;a<num;a++){ }
if (a*a == num){
System.out.println("Ok");
break;
}
else if (a*a != num){
System.out.println("Not ok");
}
}
}
So it doesn’t give what i want when i run it. What should i change or add ?
I think your for loop interpretation might be wrong, I made up something that might just work. Give this code a try.. You can make the method return a boolean too if you want.
static void perfectSquare(int number) {
for (int i = 1; i < i * number; ++i) {
// 'i' is the divisor, making sure
// it is equal to the quotient
if ((number % i == 0) && (number / i == i)) {
System.out.println(i);
}
}
If you want to brute force every number then you are on the right track but you should only print "Not ok" if all numbers in the loop have failed otherwise you may have a perfect square but "Ok" will be hidden within many "Not ok" lines. Also there is nothing in your for loop so the if statement always checks if 0*0 == num.
This looks like it may be a homework question so I won't give a full answer for you but think about how you can make this more efficient.
If you have found an integer number that matches do you need to keep going?
Do you need to check every number? (a starting point may be following the principles of a binary search)
I ended up like this:
import java.util.Scanner;
class Q3{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int num = 0;
int a = 0;
int b = 0;
System.out.println("Type a number to check if it has square");
num = sc.nextInt();
for(a = 1;a<num;a++){
if (a*a == num){
b = 1;
break;
}
}
if(b==1){
System.out.println("Perfect Square");
}
else {
System.out.println("Not ok");
}
}
}
Thanks for support !

How to get scanner input to not trigger third method?

I'm working on an assignment and I mostly have it finished but I am having an issue with the last method. I'm trying to write a continueGame() method that will ask the user if they want to continue to play, and accept "y" or "n". If answered "y", the program starts again. If answered "n", the program stops and a message is shown. The problem is I need it to trigger the continueGame() method only when userChoice == answer. This is a number guessing game with an object oriented approach.
I've tried to call the continueGame() method inside my else if(userChoice == answer) statement but it doesn't seem to work. Even when my other if/else if statements are triggered, it continues to the continueGame() method.
Here is the main driver for the game
import java.util.Scanner;
public class NumberGame
{
public static void main(String[] args)
{
Scanner input = new Scanner (System.in);
GameOptions opt = new GameOptions(); // Your created class
int userChoice = -1234;
int answer = -1234;
boolean keepPlaying = true;
System.out.println("Guess the Number Game\n");
while (keepPlaying == true) {
answer = (int) (Math.random() * 10)+1;
//Create a getChoice method in your class and make sure it accepts a Scanner argument
userChoice = opt.getChoice(input);
//Create a checkAnswer method in your class. Make sure it accepts two integer arguments and a Scanner argument
opt.checkAnswer(userChoice, answer, input);
// Create a continueGame method in your class and make sure it accepts a Scanner argument
keepPlaying = opt.continueGame(input);
}
System.out.println("Thanks for playing.");
}
}
Here is the class that I am working on for the methods. Note that I can not make any modifications to the main driver file.
import java.util.InputMismatchException;
import java.util.Scanner;
import java.lang.NumberFormatException;
public class GameOptions {
int count = 0;
boolean cont = true;
//getChoice Method for NumberGame
public int getChoice(Scanner scnr) {
System.out.println("Please choose a number between 1 and 10: ");
int userGuess = 0;
String input = scnr.next();
try {
userGuess = Integer.parseInt(input);
if (userGuess < 1 || userGuess > 10) {
throw new IllegalArgumentException("Invalid value. Please enter a number between 1 and 10: ");
}
}
catch(NumberFormatException e) {
System.out.println("Error - Enter Numerical Values Only");
return userGuess;
}
catch (IllegalArgumentException ex) {
System.out.println(ex.getMessage());
}
return Integer.parseInt(input);
}
public void checkAnswer(int userChoice, int answer, Scanner scnr) {
if (userChoice > answer && userChoice < 11) {
System.out.println("Too high. Try again.");
count++;
} else if (userChoice < answer && userChoice > 0) {
System.out.println("Too low. Try again.");
count++;
} else if (userChoice == answer) {
System.out.println("You got it! Number of tries: " + count);
System.out.println("Would you like to play again? (y/n)");
}
}
public static boolean continueGame(Scanner scnr) {
String input = scnr.nextLine();
if (input.toLowerCase().equals("y")){
return true;
} else if (input.toLowerCase().equals("n")){
return false;
} else {
System.out.println("Invalid entry. Please enter either y or n: ");
return continueGame(scnr);
}
}
}
So I should be able to enter a number, and if its lower than the answer it will tell me I am too low, if its higher than the answer it will tell me that its too high, if its equal it will tell me I won and prompt me to press "y" or "n" if I want to continue. Another issue I am running into is that I am getting "Would you like to play again? (y/n)" no matter whether I guess the right number or not and my only option is to hit "y" or "n"
The driver class is calling continueGame() inside the while loop. If you're not allowed to modify that class then presumably asking at every iteration is the intended behaviour.
You should move System.out.println("Would you like to play again? (y/n)"); into the continueGame() method so that it only asks when that method is called.
The way the driver is written (I guess) is coming from your instructor/lecturer/professor, right?
With the driver (as it is), you don't need to call continueGame method from checkAnswer method. The driver is going to call it.
Just run the driver and it will work. If you have a proper IDE (eclipse or Netbeans), trace through and see what the input accepted is (I think there is line-feed in the accepted answer).
Try this (I just changed the loop structure; yours is also valid):
public static boolean continueGame(Scanner scnr) {
while (true) {
String input = scnr.nextLine().trim(); // to remove white spaces and line-feed
if (input.toLowerCase().equals("y")){
return true;
} else if (input.toLowerCase().equals("n")){
return false;
} else {
System.out.println("Invalid entry. Please enter either y or n: ");
}
}
}
Added for checkAnswer method to keep the user guess the answer until he gets correct:
public static checkAnswer(/*three arguments*/) {
boolean correct = false;
while (! correct) {
// accept input
if (answer.equals(input)) {
correct = true;
// print required correct/congrats messages here
} else {
// print required input/try again messages here
}
}
// print would you like to play again with new answer y/n message here.
}
In my opinion, printing "play again with new answer y/n message" should go into continueGame method (from last portion of checkAnswer) method to stick to encapsulation concepts.

.equals() in java doesn't work?

.equals() in java dosent work? There is a problem with my program, for some reason in the while loop part it is always active even if the String a = answer[r]
import java.util.Scanner;
public class security {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
String q1[] = {"mother midd name","Father name","your pit name","First school name"};
String a[] = {"Zakia","Mohamed","Dog","Kaliop"};
AskQ(q1,a);
}
public static void AskQ(String q[],String answers[]) {
int r = (int) (Math.random() * q.length) + 1;
for (int i = 0; i < answers.length; i++) {
int c = 1;
System.out.print("please enter your " + q[r] + "?");
String a = sc.nextLine();
do {
c++;
System.out.print("Wrong! try again:");
a = sc.nextLine();
if(c == 2){
System.out.print("only one attempt lift! enter your pass:");
a = sc.nextLine();
c++;
}
if(c == 3){
System.exit(0);
}
c++;
} while (!a.equals(answers[r]));
System.out.println("you are in");
break;
}
}
}
From what I am seeing, your code first sets c equal to 1 in the for-loop, then asks for an answer to a question, then goes into the do-while loop. Inside of the do-while loop it increments c to 2, then takes in another answer to a question, then checks to see if c is equal to 2. Since c is equal to 2 it asks for an aswer to another question then it increments c to 3. Finally, it checks to see if c is equal to 3 (which it is) and exits the program.
I suggest using a while loop over a do-while loop since it looks like you want to check to see if the user entered in the correct answer BEFORE you do any checking and error-handling. If you use a do-while loop, you are doing the error handling before it ever even checks to see if the user entered in the correct answer.
More over, i'd suggest using your second if-statement as an else-if statement.

Java method won't return answer in my LCM program

So what this program does is take two numbers as input using the Scanner class, and calculates the lowest common multiple of those two numbers. Everything seems to be working, except the lcm method won't return anything. I may have messed something up with my 'break' statements, but I didn't know any other way to get out of the if statement that is nested in a while loop. One more question: Is using a while(True) loop good practice or bad practice? Because I've seen lots of mixed opinions on it. If anyone has any better alternatives to while(True) loops I'd be happy to hear them. Thank you!
// LCM Calculator
// Author: Ethan Houston
// Language: Java
// Date: 2013-12-27
import java.io.*;
import java.util.Scanner;
public class lcm {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("This is a LCM calculator\n");
System.out.println("Enter your first number: ");
int firstNumber = scanner.nextInt();
System.out.println("Enter your second number: ");
int secondNumber = scanner.nextInt();
lcm(firstNumber, secondNumber);
}
public static int lcm(int one, int two) {
int counter = Math.min(one, two);
int initialCounter = counter;
boolean running = true;
while (running) {
if (counter % one == 0 && counter % two == 0) {
break;
} else {
counter += initialCounter;
}
}
return counter;
}
}
You do return something, you're just not printing it. Just try:
System.out.println(lcm(firstNumber, secondNumber));
You are not printing the returned value
System.out.println(lcm(firstNumber, secondNumber));
As you had written,
lcm(firstnumber, secondnumber);
this method will return an int type value, but in your code, you are not obtaining the returned value in any variable.
So, you should write like this :
int variable=lcm(firstnumber, secondnumber);

Why does my java program skip a if statement? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
im only 15 and new to java so i am trying to build a simple calculator, but i cant seem to figure out why this if statement is being ignored. I have check to be sure that all values are being stored and yes they are so i can not see any other problems which would explain this. Any help would be great! Look for the comment in the second class //This if statement
The first class
public class CalculatorOperations {
double fnum, snum,answer;
String operation;
void plus(){
operation="+";
answer = fnum + snum;
}
void subtract(){
operation="-";
answer = fnum - snum;
}
void multiple(){
operation="*";
answer = fnum * snum;
}
void divide(){
operation="/";
answer = fnum / snum;
}
void invalidOperation(){
System.out.println("Invalid operation.");
}
void showAttributes(){
System.out.println(fnum);
System.out.println(snum);
System.out.println(operation);
}
}
The second class
import java.util.Scanner;
public class calculatorApplication {
public static void main(String [] args){
CalculatorOperations Operators = new CalculatorOperations();
Scanner userInput = new Scanner(System.in);
String loop2 = null;
boolean loop;
while (loop = true){
// Getting input and storing it
System.out.print("Please enter first number: ");
Operators.fnum = userInput.nextDouble();
System.out.println("TEST:"+Operators.fnum);
System.out.print("Please enter second number: ");
Operators.snum = userInput.nextDouble();
System.out.println("TEST:"+Operators.snum);
System.out.print("Please enter operation (+, -, * or /): ");
Operators.operation = userInput.next();
System.out.println("TEST:"+Operators.operation);
// this if statement
if (Operators.operation == "+") {
Operators.plus();
} else if (Operators.operation == "-") {
Operators.subtract();
} else if (Operators.operation == "*") {
Operators.multiple();
} else if (Operators.operation == "/") {
Operators.divide();
} else {
Operators.invalidOperation();
}
System.out.println("Answer: " +Operators.answer);
System.out.print("Would you like to do another sum? (yes or no): ");
loop2 = userInput.next();
}
if (loop2.equals("yes") || loop2.equals("Yes")){
loop = true;
System.out.println();
System.out.println();
}else{
loop = false;
// Closes scanner to prevent resource leaks
userInput.close();
System.exit(0);
}
}
}
Comparing Strings with == generally doesn't work the way you'd like it to. It's because Strings are Objects and == compares object references against each other, instead of checking if the Strings contain identical text.
Try String.equals instead:
if (Operators.operation.equals("+")) {
... //and of course the same for the rest of the statements
Good luck with your program!
Use the .equals(String) method, instead of ==. Your if-structure would change to this:
if (Operators.operation.equals("+")) {
Operators.plus();
} else if (Operators.operation.equals("-")) {
Operators.subtract();
} else if (Operators.operation.equals("*")) {
Operators.multiple();
} else if (Operators.operation.equals("/")) {
Operators.divide();
} else {
Operators.invalidOperation();
}
.equals(String) is used for comparing strings, whereas == is used for comparing everything else pretty much. == is comparing the reference to an object and .equals(String) is used to compare String values.
Also, change while (loop = true) to while(loop) or while (loop == true); otherwise you are indicating that you are actually changing the value of loop.
You don't want to compare strings with == because by doing that you're comparing the reference of the string, and not the value of the string. You need to use the .equals method.
if (Operators.operation.equals("+"))
From the javadoc:
boolean equals(Object anObject)
Returns true if and only if the argument is a String object that represents the same sequence of characters as this object.
Also, you need to change
while (loop = true)
to
while (loop)
= is the assignment operator, == is the comparison operator.

Categories