Error with if expression algorithm - java

I want to pass in the values of x, y and z, and have them go through the algorithm. But I get an error. I think I'm doing something illegal, but I'm not sure.
The error is with this statement:
if((istrue1)||(istrue2&&istrue3)){
;
}
My full code is:
package com.company;
public class Main {
public static void main(int x, int y, int z) {
boolean istrue1, istrue2, istrue3;
if((istrue1=(x >=1 && x<=31)) || (istrue2=(y>=1 && y<=31)) || (istrue3=(z >= 1 && z<=31)));{
if((istrue1)||(istrue2&&istrue3)){
;
}
}
}
}

There are (at least) two problems in the code (but I suspect only the second is part of your issue here.
The first problem is that your outer if statement has a ';' at the end. So although it looks from the indenting that you have nested if statements, you don't really.
The second problem is a bit more subtle, and it's to do with the if statement short-circuiting the evaluation of its condition.
You have
if
(
a = first_condition ||
b = second_condition ||
c = third_condition
)
{
...do stuff
}
This is legal syntax, but if first_condition is true, then the compiler knows that the whole if condition is true, so it doesn't bother evaluating the second two clauses. That means, if first_condition is true, then neither 'b' nor 'c' will be assigned values.
My advice would be to redo the code as
boolean a = first_condition
boolean b = second_condition
boolean c = third_condition
if (a || b || c)
{
//do stuff
}

There is so much wrong with your approach it is pretty much unsalvageable:
And to explain how and why all the problems in detail would be an entire class and is out of scope for StackOverflow because it would be too broad a subject.
That said, you did make an attempt so here is how to actually do part of what you are trying to do. Hopefully this will clarify how to work with boolean logic.
/* This removes the duplication of logic and remediates
the *line noise* looking code that duplication introduced.
*/
public static boolean inRangeInclusive(final int low, final int value, final int hi)
{
return low <= value && value <= hi;
}
public static void main(final String[] args)
{
final int x = Integer.parseInt(args[0]);
final int y = Integer.parseInt(args[1]);
final int z = Integer.parseInt(args[2]);
if ( inRangeInclusive(1,x,31) || inRangeInclusive(1,y,31) || inRangeInclusive(1,z,31)) ;
{
/* whatever you want to happen if any of those things match goes here */
}
}
Take the time to learn how to make all method args final and all local references final it will save your more time than you can ever imagine!
If write something and it looks like line noise or the cat walked across the keyboard then it is probably wrong. Even if it appears to produce the behavior you desire.

Related

Beginner Boolean compiling error

I am very new to Java (doing a beginners university module) so sorry for the probably silly question. I am trying to verify whether a ragged array is a 'tridiagonal matrix'.
It is valid if it is of length 3 at the first level and of length n − 1, n, and n − 1 at the second level. I intended to come up with a code to firstly verify the length is 3, then find the longest length array within it for n, then finally verify each length.
For whatever reason my code won't compile but I'm not seeing an error message, just a red exclamation mark on the class. I assume this means there are multiple errors. If anyone could point them out it would be a massive help.
static boolean isValidTridiagonal ( double [][] m)
{
if (double [][]=new double [3][])
{
int n = 0;
for(int i = 0; i < m.length; i++)
{
if(m[i].length > n)
{
n = m[i].length;
if( (m[0].length = n-1) && (m[1].length = n) &&(m[2].length=n-1))
{
return true
}
else
{
return false
}
}
else
{
return false
}
}
Thanks very much!
I agree with Foolish in the comments that it's helpful to use an IDE that can highlight syntax errors and other problems with the code, it really makes a huge difference. Apart from that, another general strategy is to always code in "baby steps": do only the minimal thing to test if the code works, compile and test often. And if you still have troubles, you can always comment out chunks of your code when searching for the offending bits.
Having said that, the errors that I see in your code are:
if (double [][]=new double[3][])
If you want to test the length of the input, you can do if (m.length == 3)
In
if( (m[0].length = n-1) && (m[1].length = n) &&(m[2].length=n-1))
you're not testing for equality, but rather trying to put the values n-1 etc into m[0].length, which is not going to work. What you probably meant was
if( (m[0].length == n-1) && (m[1].length == n) &&(m[2].length==n-1))
In
return true
you're missing a semicolon. The compiler is whiny about things like that and unless you use an IDE or learn to interpret the compiler error messages, it can be really painful to find such errors.
Finally, of course, the answer by vasste provides a much simpler solution to your actual task, so it's worth looking into that :).
Why do you need all that loops? If all arrays cannot be null, than
static boolean isValidTridiagonal(double[][] m) {
return m.length == 3 && m[0].length == m[1].length - 1 && m[2].length == m[0].length;
}
You're missing a few braces at the end but, judging from your indentation, you just forgot to copy them.
You're missing semicolons from the end of the return lines.
The condition within this if statement if (double [][] = new double [3][]) is not a valid expression. You simply want to evaluate the length, which you can do like if (m.length == 3). You did the same thing later on.
The line including (m[0].length = n-1) && (m[1].length = n) && (m[2].length=n-1) is not valid because you are performing assignment (=) in all three cases. An equality check is the double equals operator ==.
You do not return a value in every case. You can fix this by adding return false; after the closing brace of your first if statement, i.e. the last line of the function.
This is enough to get your code to compile. As mentioned in another answer though, your logic is confusing and without actually tracing it through I would speculate that it will not work as you would expect.
If I have understood your requirements correctly, you can rewrite the entire function as:
static boolean isValidTridiagonal ( double [][] m)
{
return m.length == 3 &&
m[0].length + 1 == m[1].length &&
m[2].length + 1 == m[1].length;
}
A proper IDE - Netbeans, Eclipse, etc. - will give you fairly descriptive error messages to show you where you've gone wrong.
This is basically completely stylistic but I wish someone had pointed this out to me earlier. If you ever find yourself writing code in this form:
if( (m[0].length == n-1) && (m[1].length == n) && (m[2].length == n-1))
{
return true;
}
else
{
return false;
}
know that you can save yourself so many lines without losing any readability by instead writing:
return (m[0].length == n-1) && (m[1].length == n) && (m[2].length == n-1);

How do I make a local variable increase consistently in a recursive function having more than one calls?

In this code, I've used a global variable to increase the value of p whenever control touches the base case. But I want to do it without using a global variable. Is that possible?
public class stairCase {
static int p=0;
public static void main(String[] args) {
// TODO Auto-generated method stub
int n = func(14,0);
System.out.println(n);
}
public static int func(int n, int c){
if(n==c){
p++;
return 1;
}
if(n-c>=1){
func(n,c+1);
}
if(n-c>=2){
func(n,c+2);
}
if(n-c>=3){
func(n,c+3);
}
return p;
}}
Your problem is that you're throwing away a major communication resource: the return value. You recur in three places, but ignore the value. Harness that, and you'll solve your problem.
Consider something like this:
if (n < c) return 0 // Jumping too far gives no solution
else if (n == c) return 1 // Jumping to the top step is 1 solution
else
return func(n, c+1) + // Other jumps: sum the solutions from
func(n, c+2) + // each of the reachable steps.
func(n, c+3)
For future programming, please learn about useful variable names and documentation. I would not have followed this decently, had I not solved this problem yesterday in another posting.
You can do a little better with this problem if you reverse your counting. Note that you never change n as you recur -- in that case, why pass it at all? Start c at 14 and count to step 0 (the top).
Converting the code is left as an exercise for the student. :-)

Error resolving variables and left-side side assignments and figuring ++ tokens

I'm starting to get blind looking at my code and my brain is about to overheat. I'm new when it comes to programming.
public class RecyclingSystem {
public static void main(String[] args) {
System.out.println("Please put in a valid bottle");
Scanner sc = new Scanner(System.in);
while ( sc.nextInt() != -1) {
if (sc.nextInt(char a) = getaBottle);
int bottleAcount++;
} else if { (sc.nextInt(char b) = getbBottle);
int bottleBcount++;
} else if { (sc.nextInt(char c) = getcBottle);
int bottleCcount++;
} else { throw new EmptyStackException();
System.out.println("Bottle not recognized");
}
System.out.println("The total number of bottles is " + totalBottlecount);
System.out.println();
System.out.println("The total amount returned is " + sumOfBottles );
}
sc.close();
}
}}
public class Bottle {
private static final double A_BOTTLE = 1.0;
/**
* #return the aBottle
*/
public static double getaBottle() {
return A_BOTTLE;
}
/**
* #return the bBottle
*/
public static double getbBottle() {
return B_BOTTLE;
}
/**
* #return the cBottle
*/
public static double getcBottle() {
return C_BOTTLE;
}
private static final double B_BOTTLE = 1.5;
private static final double C_BOTTLE = 3.0;
}
public class EmptyStackException extends Exception {
}
public class bottleCount {
int bottleAcount = 0;
int bottleBcount = 0;
int bottleCcount = 0;
int totalBottleCount = bottleAcount + bottleBcount + bottleCcount;
}
I have seperate classes for the getbottle, totalBottlecount and bottlecount variables.
I want to make a user-input based recycling system simulator, if that makes any sense, with 3 different types of bottles, which are assigned different values, a total bottle count and the sum of the values of the 3 bottle types combined.
I get several compiler errors and I have spend HOURS trying to resolve them all, but every time I do, new errors occur and now I get a "coders-block".
I get asked to delete the ++ tokens, the compiler cannot resolve my variables and syntax errors. I would really appreciate some insight, since I'm only ~3weeks into java programming.
UPDATED: Compiler errors exact copy pasta
Multiple markers at this line
- Syntax error, insert ")" to complete Expression
- Duplicate method nextInt(char) in type RecyclingSystem
- Syntax error, insert "}" to complete Block
- Syntax error, insert "AssignmentOperator Expression" to complete Assignment
- Return type for the method is missing
- Syntax error on tokens, delete these tokens
- The left-hand side of an assignment must be a variable
- Syntax error, insert "AssignmentOperator Expression" to complete Expression
- The left-hand side of an assignment must be a variable
- Syntax error, insert ";" to complete BlockStatements
- Syntax error on tokens, delete these tokens
- Syntax error on token ")", { expected after this token
- Syntax error, insert ";" to complete Statement
int bottleAcount++;
In java you need to declare the local variable like
type name = intial value;
then do any operation on that like increament or decrement.
In youe case declar the variable before while loop with zero as intial value like
int bottleAcount = 0;
then inside while increament it by 1, like bottleAcount++;
or
bottleAcount += 1;
So... If this is all the code there are many problems and what can I recommend in the beginning - go back to some basic Java programming course.
Let's look at one of the first lines:
if (sc.nextInt(char a) = getaBottle);
Firstly, it's a condition, and you are assigning the value of a getaBottle to the sc.nextInt(char a).
Secondly, nextInt(char a) looks like method declaring, not like a method call.
Thirdly, getaBottle is never declared before
Fourthly, you have a getaBottle() method in a Bottle class, which you probably want to use instead of getaBottle which is (should) be a variable
...etc., etc.
This code is not even valid Java code. It's hard to help you somehow in that problem, you just need to learn a bit more, which I encourage you to do.
Good luck and in case of any specific question - come and ask!
else if { (sc.nextInt(char b) = getbBottle);
int bottleBcount++;
}
Syntax is totally wrong for if.Also condition is checked using == not = It should be :
else if (sc.nextInt(char b) == getbBottle);
int bottleBcount++;
Also you cant do int bottleBcount++. Its meaningless. Since you already declared bottleBcount in another class, you have to access it using the object of that class. Before that change the declaration in the class from int bottleAcount = 0; to public int bottleAcount = 0; . Do this for all bottles.
Now you can use it as :
public static void main(String[] args) {
System.out.println("Please put in a valid bottle");
bottleCount counter = new bottleCount();
Scanner sc = new Scanner(System.in);
while ( sc.nextInt() != -1) {
if (sc.nextInt(char a) == getaBottle);
counter.bottleAcount++;
} else if (sc.nextInt(char b) == getbBottle);
counter.bottleBcount++;
else if (sc.nextInt(char c) == getcBottle);
counter.bottleCcount++;
else { throw new EmptyStackException();
System.out.println("Bottle not recognized");
}
System.out.println("The total number of bottles is " + totalBottlecount);
System.out.println();
System.out.println("The total amount returned is " + sumOfBottles );
}
sc.close();
}
Also the statement int totalBottleCount = bottleAcount + bottleBcount + bottleCcount; doesnt make sense. It won't work as you wanted it to. You need to write a function to do this addition and then call it. Or if you want this to happen just once ( which I doubt) , you can put it in a constructor.
I suggest you brush up on class and variable declaration concepts before proceeding
You just have problem in this:
else {
throw new EmptyStackException();
System.out.println("Bottle not recognized");
}
Check the proper syntax and error will be resolved.

Error: variable might not have been initialised

I am doing a book exercise regarding the Ackermann function.
I have one question though. If I declare result but do not initialise it, the compiler complains that "variable result might not have been initialised".
int result;
When I set it to default to 0, it does not complain.
int result = 0;
I thought that when one declares a variable with type int it defaults to 0 automatically.
Here's the complete code:
public class Ackermann {
public static int ack(int m, int n) {
int result = 0;
//int result;
if (m == 0)
result = n + 1;
else if(m > 0 && n == 0)
result = ack(m-1, 1);
else if(m > 0 && n > 0)
result = ack(m-1, ack(m, n-1));
return result;
}
public static void main(String[] args) {
System.out.println(ack(3, 3));
}
}
Local variables are not initialized with default values. See the language specs for the ground truth.
it is very bad practice to not initialize variables. There is popular joke that fits to your case: John got 3 apples from his mother and 5 from his father. How many apples has John? If you are not good programmer, your answer will be 8. If you are good programmer, you will answer that we do not know how many apples had had john before obtaining apples from his Mother. Remember: always initialize variables and do not assume that they will be 0.
Fields in classes default to values (null, 0, false, etc.) Local variables however don't, you have to define them explicitly. A lot of people even disagree with not setting fields explicitly, because setting it shows the reader that you've actually thought about setting it to a value rather than just forgotten to set it, therefore potentially causing a bug somewhere down the line.

javac says int (x = 1); is not a statement then says ';' expected. What's wrong with my code?

I'm on a Mac Mini G4 trying to learn Java. When I try to compile "DooBee.java" by typing "javac DooBee.java" at the terminal I get two errors. This is what my terminal looks like:
> nephi-shields-mac-mini:/developer/MyProjects
> nephishields$ javac DooBee.java
> DooBee.java:5: not a statement
> int (x = 1);
> ^ DooBee.java:5: ';' expected
> int (x = 1);
> ^ 2 errors nephi-shields-mac-mini:/developer/MyProjects
> nephishields$
This is what I have typed into my "DooBee.java" file:
public class DooBee {
public static void main (String[] args) {
int (x = 1);
while (x < 3) {
System.out.print ("Doo");
System.out.print ("Bee");
x = x + 1;
}
if (x == 3) {
System.out.print ("Do");
}
}
}
Have I made a mistake? Or is there something wrong with my computer? sorry if this question (or a similar one) has already been asked. I honestly tried to find an answer on my own (google searches, searching Stack Overflow, rewrote my code several times, checked my book "Head First Java" to make sure I was typing things the right way) but came up empty.
The problem is that (x = 1) is an expression, not a declaration, so it can't be used to declare the variable x. Remove the parentheses and you'll have a correct declaration with initializer.
The correct declaration is:
public class DooBee {
public static void main (String[] args) {
int x = 1;
...
}
}
Remember your order of operations in Java. Items inside the parenthesis are evaluated first, so (x=1) is evaluated, which doesn't even really make sense in Java, hence the error.
Generally you'll only wrap parenthesis around casts, the clauses after an if, while, else if, else and for statement, or in situations where you want your boolean logic to be very clear.
int (x = 1);
replace that with
int x = 1;

Categories