error :not a statement - java

So i started in September my university and i have a class that is introduction to programming and i have to do a program that recognize 3 numbers and tell how many are equal for example: 30 30 2 "2 numbers are equal" but i get error :not a statement on "else ( n1!=n2 && n2!=n3 && n3!=n1 ); {
import java.util.Scanner;
public class Equal {
public static void main(String[] args) {
Scanner in = new Scanner( System.in );
int n1, n2, n3;
int a = 3;
int b = 2;
int c = 0;
System.out.println("choose tree numbers:");
n1 = in.nextInt();
n2 = in.nextInt();
n3 = in.nextInt();
if ((n1==n2 && n1==n3 || n2==n1 && n2==n3 || n3==n1 && n3==n2)) {
//Then the tree numbers are equal;
System.out.println( "There are: " + a + " equal numbers" );
}
if ((n1!=n3 && n1==n2 || n2!=n1 && n2==n3 || n3!=n2 && n3==n1 )) {
//Then only two numbers ill be the same;
System.out.println( "There are: " + b + " equal numbers" );
}
else ((n1!=n2 && n2!=n3 && n3!=n1)); {
//All the numbers are not equal;
System.out.println( "There are: " + c + " equal numbers" );
}
}
}

change
else ( n1!=n2 && n2!=n3 && n3!=n1 ); {
to
else if ( n1!=n2 && n2!=n3 && n3!=n1 ) {

if (condition1) { do_something; }
else if (condition2) { do_something_else; }
else { do_a_different_thing; }
A bare else-clause, by definition, does not take a condition - it fires if the preceding if/else-if clauses don't fire. I guess you could think of it as an implicit condition: if (!condition && !condition2).
(But note that, in general, you are not required to follow the if/else-if/else pattern. You could have multiple ifs in a row with no else-ifs or else-clause, or you could have an if/else with no else-ifs, etc. It all depends on the exact logic of the situation.)
A couple of suggestions.
It's really good that you're thinking about all of the possible cases. But here, you have three numbers, and if you've already determined that it is NOT the case that all three of them match, and it is NOT the case that two of them match, then the only possibility left is that none of them do. So you don't have to test for that case explicitly.
Similarly, in your first condition, checking for a three-way match, you don't have to explicitly test every combination either. If n1==n2 && n1==n3, then by transitivity n2==n3 and all three match. The order doesn't matter.
Have fun!

Related

Logical operators in 'else if' statement

I am trying to learn "if else" statements and I am having trouble with the middle 'if else' part of the script.
package practice;
import java.util.Scanner;
public class Practice {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
System.out.println("enter a number between 1 and 10 ");
if (!in.hasNextDouble()) {
String word = in.next();
System.err.println(word + " is not a number");
} else if (!(in.nextDouble() > 0) || !(in.nextDouble() <= 10)) {
Double wrongnumber = in.nextDouble();
System.err.println(wrongnumber + " is not between 1 and 10");
} else {
System.out.println("It works!");
}
return;
}
}
There are no errors but in the 'else if' block I can't get it to print the err "..... not between 1 and 10", whether or not I put a number between 1 and 10 or higher. It also wont print the "it works!" line anymore when I add the 'else if' block.
any suggestions would be much appreciated.
You are caling in.nextDouble() several times in your if else block, so you get something else every time.
if (!(in.nextDouble() > 0) || !(in.nextDouble() <= 10)) {
Double wrongnumber = in.nextDouble();
System.err.println(wrongnumber + " is not between 1 and 10");
}
convert it to something like
double next = in.nextDouble();
if (!(next > 0) || !(next <= 10)) {
Double wrongnumber = next;
System.err.println(wrongnumber + " is not between 1 and 10");
}
To be logically correct you might switch to Integer instead of Double values.
You call in.hasNextDouble() several times. Each time it scans new number from input so it may cause your issue. You should also consider how you write conditions. I am aware you may just try what's happening there but this kind of condition is hard to read. You can use
(number <= 1) || (number > 10) (remove negations by inverting operators) for example.
else if (!(in.nextDouble() > 0) || !(in.nextDouble() <= 10)) {
Double wrongnumber = in.nextDouble();
I'm not sure but here you operate on 3 different numbers. Before condition, write it to a variable.
Don't compare int with double
#RevCarl, According what i understand by your code and the description provided, what you want to do is to check whether the input is a number and whether its between 1 to 10. Also you have not clearly said the type of the input you are expecting. I assume it as integer, and the code below will do the task.
import java.util.Scanner;
public class Demo {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a No between 1 to 10");
String next = input.next();
Integer i = Integer.parseInt(next);
if (null == i) {
System.out.println("Input is not a number");
} else {
if (i > 0 && i < 10) {
System.out.println("It works");
} else {
System.out.println("Not Between 1 to 10");
}
}
}
}
Otherwise u can replace the statement String next = input.next(); with Integer i = input.nextInt(); which takes the integer numbers input from the console.

determining logic error that causes a misprint

So, I am pretty new to java and I wanted to try my hand at debugging in command line, namely using jdb on a code that has a couple errors. I was tinkering with this code:
import java.util.Scanner;
import java.io.File;
class LetterHome{
static final int MAX_CODE = 5;
public static void main(String[] args) throws Exception{
Scanner in = new Scanner(new File(args[0]));
String phrase;
int sentenceCode, modifierCode;
System.out.println("Dear Mom and Dad:\n");
while( in.hasNext() ){
sentenceCode = in.nextInt();
modifierCode = in.nextInt();
if( (sentenceCode < 1) || (sentenceCode >= MAX_CODE) ) {
System.out.println(sentenceCode + " is not a valid sentence code");
continue;
}
if( sentenceCode == 1 ){
if( modifierCode == 1 ){
phrase = "great";
}else if( modifierCode == 2 ){
phrase = "ok";
}else{
phrase = "ERROR";
}
System.out.println("My classes are going " + phrase + ".");
}else if( sentenceCode == 2 ){
phrase = weatherModifier(modifierCode);
System.out.println("The weather here has been " + phrase + ".");
}else if( sentenceCode == 3 ){
if( modifierCode == 1 ){
phrase = "after the quarter ends";
}else if( modifierCode == 2 ){
phrase = "in a few weeks";
}else if( modifierCode == 3 ){
phrase = "next weekend";
}else{
phrase = "ERROR";
}
System.out.println("I plan to come home for a visit " + phrase + ".");
}else if( sentenceCode == 4 ){
System.out.println("Do you think you could send me $" + modifierCode + "?");
System.out.println("I have to buy another book for one of my classes.");
}else if( sentenceCode == 5 ){
if( modifierCode == 1 ){
phrase = "cookies";
}else if( modifierCode == 2 ){
phrase = "stuff";
}else; if( modifierCode == 3 ){
phrase = "money";
}else{
phrase = "ERROR";
}
System.out.println("Thanks for the " + phrase + " you sent.");
}
}
}
static String weatherModifier(int m) {
String word=null;
if(m == 1)
word = "great";
if(m == 2)
word = "foggy";
if(m == 3)
word = "hot";
if(m == 4)
word = "cold";
if(m == 5)
word = "variable";
if( m<1 && m>5)
word = "ERROR";
return word;
}
}
And I've already found a ";" that was out of place. I know that something is off with the values assigned to the terms in the end (I think), because when I compile the program, I get this output:
Dear Mom and Dad:
//
// 5 is not a valid sentence code
// My classes are going great.
// The weather here has been foggy.
// I plan to come home for a visit in a few weeks.
Instead of classes going "great", I get "foggy", which I noticed when I ran jdb. I ran the code with this data file:
5 2
1 1
2 1
3 2
The code itself prints a template with possible options outlined in the data file, which you may have already noticed. Here's the full list of possibilities:
// 1. My classes are going _____.
// 1. great
// 2. ok
// 2. The weather here has been _____.
// 1. great
// 2. foggy
// 3. hot
// 4. cold
// 5. variable
// 3. I plan to come home for a visit _____.
// 1. after the quarter ends
// 2. in a few weeks
// 3. next weekend
// 4. Do you think you could send me $_____?
// I have to buy another book for one of my classes.
// 5. Thanks for the _____ you sent.
// 1. cookies
// 2. stuff
// 3. money
However, I'm not sure what's off about the logic in the code. Any tips? Please let me know if I need to make some clarification. Thanks.
You added an extra ;at the end of if (m==2); in your weatherModifier function. Remove it!
I figured out the issue, actually:
It was in " if( (sentenceCode < 1) || (sentenceCode >= MAX_CODE) )"
I had to change ">=" to ">"

While loop JOptionPane issues

Ok - I know that I am fairly close to the solution but need a nudge in the right direction. I need the user to hit YES and the program to begin asking the question again.
After execution, I get the following errors
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: 1 at java.lang.String.charAt(Unknown
Source) at Vowel3.main(Vowel3.java:49)
// java class for Panel I/O
import javax.swing.JOptionPane;
// declaration of the class
public class Vowel33
{
// declaration of main program
public static void main(String[] args)
{
// objects used to store data
String input_string = null;
int a_count = 0;
int e_count = 0;
int i_count = 0;
int o_count = 0;
int u_count = 0;
int i = 0;
int yes = 0;
// 1. display a descriptive message
String display_message = "This program asks the user for a sentence,\n"
+ "searches the sentence for all vowels,\n"
+ "and displays the number of times each"
+ "vowel appears in the sentence";
JOptionPane.showMessageDialog(null, display_message, "Lab 3 Description", JOptionPane.INFORMATION_MESSAGE);
// 4. visit each String posotion
do{
// 3. input the character string
input_string = JOptionPane.showInputDialog("Enter the sentence to search");
// 5. if position i of String is a vowel
// 6. increase the appropriate vowel counter
if (input_string.charAt(i) == 'a' || input_string.charAt(i) == 'A')
a_count++;
else if (input_string.charAt(i) == 'e' || input_string.charAt(i) == 'E')
e_count++;
else if (input_string.charAt(i) == 'i' || input_string.charAt(i) == 'I')
i_count++;
else if (input_string.charAt(i) == 'o' || input_string.charAt(i) == 'O')
o_count++;
else if (input_string.charAt(i) == 'u' || input_string.charAt(i) == 'U')
u_count++;
i++;
String display_message1 = input_string // 7. display the String
+ "\n\n" + "has " + input_string.length() + " characters.\n\n" // 8. display the number of characters
+ "There are \n"
+ a_count + " a's,\n" // 9. disaply the number of each vowel
+ e_count + " e's,\n"
+ i_count + " i's,\n"
+ o_count + " o's, and\n"
+ u_count + " u's.\n\n";
JOptionPane.showMessageDialog(null, display_message1, "Lab 3 Description", JOptionPane.INFORMATION_MESSAGE);
yes = JOptionPane.showConfirmDialog(null, "Would you like to enter another string?\n\n", "Extra Credit", JOptionPane.YES_NO_OPTION);
} while (i < input_string.length());
if (i == input_string.length())
{
yes = JOptionPane.showConfirmDialog(null, "Would you like to enter another string?\n\n", "Extra Credit", JOptionPane.YES_NO_OPTION);
if (yes == 1)
{
input_string = JOptionPane.showInputDialog("Enter the sentence to search");
}
}
} // end of main
} // end of the class
In your code you have a condition where the loop can still be executed if yes is 0. Since yes is never redefined from what I can see, you basically have an infinite loop and your code will error out when i exits the bounds of your string's length.
Also not sure why you have two JOptionPanes at the bottom of the loop (which would execute x times where x = input_string.length())
Consider something like:
if(i == input_string.length()) {
//ask the user if they want to enter another string
if(the user selected yes){
yes = 1;
//instantiate again with new input_string
}
}
Another note: Assuming you want to show a message asking if the user wants to enter another string once you've finished iterating through their first entry, it seems moot to have the yes variable and condition.

Cannot accurately asses Strings

I wrote some code that is supposed to ask for input from the user and assign it to the String skillAssign. When I try to asses skillAssign, it returns false no matter what. Here is my code:
import java.util.*;
public class CharacterCustomization
{
public CharacterCustomization()
{
}
public static void Customization()
{
Scanner keyboard = new Scanner(System.in);
int skillPoints = 100;
String skillAssign = "";
int newMaxHealth = 0;
int newMaxMagic = 0;
int newMaxStamina = 0;
int assignmentValue = 0;
boolean isDone = false;
System.out.println("Welcome to character customization, you have 100 points to allocate to your skills.");
System.out.println("To allocate points, type name of skill, followed by the points you want to assign (blank for positive, - for negative, ex. -5)");
System.out.println("Put Skill on one line, and press enter, then the value on the next line");
System.out.println("Type \"stats\" to view full stats at any time");
System.out.println("Type \"done\" to finish");
while (true)
{
while (isDone == false)
{
skillAssign = keyboard.nextLine();
if (skillPoints == 0)
{
System.out.println("Max Health: " + newMaxHealth);
System.out.println("Max Magic: " + newMaxMagic);
System.out.println("Max Stamina: " + newMaxStamina);
System.out.println("Skill points left: " + skillPoints);
System.out.println("Type \"done\"to finish");
}
if ((!(skillAssign.equals("stats"))) || (!(skillAssign.equals("done"))))
{
assignmentValue = keyboard.nextInt();
if (((skillAssign.equals("health")) || (skillAssign.equals("Health"))) && (skillPoints - assignmentValue >=0))
{
skillPoints = (skillPoints - assignmentValue);
newMaxHealth = (assignmentValue + newMaxHealth);
}
else if (((skillAssign.equals("magic")) || (skillAssign.equals("Magic"))) && (skillPoints - assignmentValue >=0))
{
skillPoints = (skillPoints - assignmentValue);
newMaxMagic = (assignmentValue + newMaxMagic);
}
else if (((skillAssign.equals("stamina")) || (skillAssign.equals("Stamina"))) && (skillPoints - assignmentValue >=0))
{
skillPoints = (skillPoints - assignmentValue);
newMaxStamina = (assignmentValue + newMaxStamina);
}
else
{
//System.out.println("Sorry, I could not read that!");
System.out.println(skillAssign == "stats");
}
}
else if (skillAssign.equals("stats"))
{
System.out.println("Max Health: " + newMaxHealth);
System.out.println("Max Magic: " + newMaxMagic);
System.out.println("Max Stamina: " + newMaxStamina);
System.out.println("Skill points left: " + skillPoints);
}
else if ((skillAssign.equals("done")) || (skillAssign.equals("Done")))
{
isDone = true;
continue;
}
else
{
System.out.println("Sorry, I could not read that!");
}
}
System.out.println("Are you sure this is the setup you want? [y] [n]");
System.out.println("Max Health: " + newMaxHealth);
System.out.println("Max Magic: " + newMaxMagic);
System.out.println("Max Stamina: " + newMaxStamina);
System.out.println("Skill points left: " + skillPoints);
//skillAssign = keyboard.nextLine();
if (((keyboard.nextLine()).equals("y")) || ((keyboard.nextLine()).equals("Y")) || ((keyboard.nextLine()).equals("yes")) || ((keyboard.nextLine()).equals("Yes")))
{
Player player = new Player(newMaxHealth, newMaxMagic, newMaxStamina);
}
else
{
isDone = false;
}
}
}
}
Its not complete, but Im inputting stats when prompted and all evaluations of it are false
Is there a way I can get it to read the variable properly?
You will always get in inside this condition scope if ((!(skillAssign.equals("stats"))) || (!(skillAssign.equals("done"))))
It because that when one word failed to pass it, the other condition will let it pass, because they are different completely.
e.g:
let's take "stats", this will results with if (false || true) => true.
let's take "done", this will results with if (true || false) => true.
let's take "sTats", this will results with if (true || true) => true.
You can't escape it, you need to check it like that:
if (!(skillAssign.equals("stats") || skillAssign.equals("done")))
this way we're checking if either of the logical expression are true, then we change it to "not" and then checking if the whole condition is true.
P.S
A. You can use "abc".equalsIgnoreCase("AbC") instead what you're using now.
B. Don't add for every logical expression parenthesis it's making the code more complex and unclear for the first glance.
The problem was that I was using || instead of && in the if ((!(skillAssign.equals("stats"))) || (!(skillAssign.equals("done"))))
What ever Orel said is pretty much it. Just wanna add if you are using System.out.println(skillAssign == "stats") to asses your skillAssign it will always return false, even if they have the same value.
Because == compare the reference of Strings not their values.
you must use equals() method.

Having an issueif else and if else statements.

I'm really new to java (third week of class), but I've been trying to work on this code for hours and I just can't seem to find an answer to what I'm doing. javac tells me I only have three errors, but I'm wondering if there's more than that.
Here's my code, and I know my average section still needs work but i just cant figure out what's going on with the middle section of if and else statements. Sorry if this is really dumb, and im sure my syntax is all over the place:
import java.util.Scanner;
public class Program1
{
static public void main( String args [ ] )
{
int grade;
int A,B,C,D,F;
A = 0;
B = 0;
C = 0;
D = 0;
F = 0;
System.out.println( "*************** Grade Computer *************");
// ********************** //
Scanner kbd = new Scanner (System.in);
System.out.println("Enter Students First Name: ");
String fname = kbd.next( );
System.out.println("Enter Students Middle Initial: ");
String mi = kbd.next( );
System.out.println("Enter Students Last Name: ");
String lname = kbd.next( );
System.out.println("Enter First Exam Grade: ");
int firstexam = kbd.nextInt( );
System.out.println("Enter Second Exam Grade: ");
int secondexam = kbd.nextInt( );
System.out.println("Enter Third Exam Grade: ");
int thirdexam = kbd.nextInt( );
System.out.println("Was the bonus done? [yes/no] : ");
boolean b = kbd.nextBoolean( );
boolean yes = true;
boolean no = false;
// *********************** //
if(true)
{
{
if((firstexam >= (secondexam * 0.60 ) ) & (firstexam >= (thirdexam * 0.80 )));
{
System.out.println(firstexam);
}
else if((secondexam * 0.60) >= (thirdexam * 0.80));
{
System.out.println(secondexam * 0.60);
}
else {
System.out.println(thirdexam * 0.80);
}
}
if(true)
{
if((secondexam >= firstexam) & ((thirdexam * 0.80) >= secondexam));
{
if(secondexam >= (thirdexam * 0.80));
{
System.out.println(secondexam);
}
}
else {
System.out.println(thirdexam * 0.80);
}
}
else {
System.out.println(firstexam);
System.out.println(secondexam);
System.out.println(thirdexam);
}
}
// ********************** //
System.out.println(" **********Grade Summary********** ");
double average = calcAverage(firstexam, secondexam, thirdexam);
System.out.println("Grade Report For: " + fname);
if (true)
{
System.out.println("Bonus was done so grades are adjusted if appropriate.");
}
else
{
System.out.println("Bonus was not done.");
}
System.out.println("Exam 1: " + firstexam);
System.out.println("Exam 2: " + secondexam);
System.out.println("Exam 3: " + thirdexam);
System.out.println("The average is: " + average);
determineGrade(average);
}
public static double calcAverage(int firstexam, int secondexam, int thirdexam)
{
double average = (firstexam + secondexam + thirdexam) / 3.0;
return average;
}
public static void determineGrade(double average)
{
if (average>90)
{
System.out.println("Grade: A");
}
else if (average>=80)
{
System.out.println("Grade: B");
}
else if (average>=70)
{
System.out.println("Grade: C");
}
else if (average>=60)
{
System.out.println("Grade: D");
}
else if (average<60)
{
System.out.println("Grade: F");
}
}
// ************** //
}
Your if statements having ; in the end
if((firstexam >= (secondexam * 0.60 ) ) & (firstexam >= (thirdexam * 0.80 )));
They are considering as statements and proceeding further.
Remove all of them in the end of each statement.
if((firstexam >= (secondexam * 0.60 ) ) & (firstexam >= (thirdexam * 0.80 ))) (;)
The ; shouldn't be here.
Difference between & and && :
& <-- verifies both operands
&& <-- stops evaluating if the first operand evaluates to false since the result will be false
(x != 0) & (1/x > 1) <-- this means evaluate (x != 0) then evaluate (1/x > 1) then do the &. the problem is that for x=0 this will throw an exception.
(x != 0) && (1/x > 1) <-- this means evaluate (x != 0) and only if this is true then evaluate (1/x > 1) so if you have x=0 then this is perfectly safe and won't throw any exception if (x != 0) evaluates to false the whole thing directly evaluates to false without evaluating the (1/x > 1).
An other thing :
if(true)
{
{
This should be deleted because it just adds more code , it will be executed every time so no need to add it.
Besides the colon the end of the if statement you also should keep in mind that if you use
if(true){
}else{
}
The else statement will never execute cos the if will always be true, so you should be using the yes/no variables as flags for your if statement instead of the "true" itself.
If your statements inside the if should always be executed then you don't need the conditions at all.

Categories