Can you please help me understand where i m doing the mistake.
I cam across this question while doing the beginner java material.
Ques: - Show how this sequence can be rewritten using the ? operator
if(x < 0) y = 10; else y = 20;
Ans: - x < 0 ? y =10 : y =20;
But when i tried performing the same i am getting an error
public class Ternary {
public static void main(String[] args) {
int result, x, y;
result = x < 0 ? y =10 : y =20;
System.out.println(result);
}
}
Error at result:- Multiple markers at this line
- Incompatible conditional operand types int and
boolean
- Syntax error on token "=", != expected
When you use a ternary operator you're assigning the left most variable to the result of the condition. In other words you only need two variables (I'll use result and x).
So the code should be:
result = x < 0 ? 10 : 20;
This will set result = 10 if x < 0 else result will be 20!
Replace the code like this. It will work.
public static void main(String[] args) {
int result, y;
int x = -1;
// Next try with int x = 1;
result = x < 0 ? (y = 10) : (y = 20);
System.out.println(result);
}
Related
Say I have the following variables:
int x = 1;
int y = 2;
//some calculations follow(x and y stay the same init values) that somehow require you to interchange the values of y and x
how can I set y = 1 and x = 2 in one line of code??
Not sure why that's necessary, but you can do it like:
int x = 2, y = 1;
Try using bitwise XOR(^) operator.
x = x ^ y ^ (y = x);
Your completed code may look like,
class Main
{
public static void main (String[] args)
{
int x = 1, y = 2;
x = x ^ y ^ (y = x);
System.out.println("x after swapping:\nx="+x+"\ny after swapping,\ny="+y);
}
}
I have been struggling with an exercise in the Java Headfirst book( CH5: p121 for reference). It's a loop inside another loop which adds/substracts some values from instance variables.
Input:
x = x + 3
Outputs:
x= 54 y = 6
public class MixFor5 {
public static void main(String[] args) {
int x = 0;
int y = 30;
for (int outer = 0; outer < 3; outer++) {
for (int inner = 4; inner > 1; inner--) {
x = x + 3;
y = y - 2;
if (x == 6) {
break;
}
x = x + 3;
}
y = y - 2;
}
System.out.println(x + " " + y);
}
}
My result is when doing it by myself with a notepad is x=42 y = 8 because then both loop conditions are met. What am i doing wrong? where did I go wrong in my thoughtprocess?
these are my notes -> pastebin note
I have not tried debugging first because I want to figure this by myself first so that I don't make the same mistakes in the future.
Thanks in advance,
tvanderv
if(x == 6) will never get true. The reason behind this is,
When inner = 4
x = x + 3 executes two times i.e. means x = 6.
then, inner = 3
now first x = x + 3 (before if(x == 3) condition) will give output x = 9. So x > 6 it will not break loop.
You did this step wrong in your notes.
My friend wrote this code for an assignment in his programming class:
public class test {
public static void main(String args[]) {
double x = 0.9;
double y = 0.1;
boolean truth = x < 1 && x > 0 && y < 1 && y > 0;
System.out.println(truth);
}
}
I'm wondering (for myself) if there's a way to simplify the conditional operators in this line specifically:
boolean truth = x < 1 && x > 0 && y < 1 && y > 0;
Your only option for a one-liner is to use parenthesis. Personally, I prefer multiple statements to make things much clearer:
boolean isXInRange = x > 0 && x < 1;
boolean isYInRange = y > 0 && y < 1;
boolean truth = isXInRange && isYInRange;
No, but it might be made clearer (opinion):
boolean truth = (0 < x && x < 1 && 0 < y && y < 1);
The flipping of the zero check makes it easy to read as 0 < x < 1. Is that clearer? A very little bit.
The parenthesis is a style choice. Since boolean expressions are always parenthesized in if statements and while loops, I find it clearer to always parenthesize boolean operators.
My suggestion for Java:
public boolean betweenExclusive(double start, double end, double val) {
return val > start && val < end;
}
and then:
boolean truth = betweenExclusive(0, 1, x) && betweenExclusive(0, 1, y);
or a little bit fancier ;)
boolean truth = Stream.of(x, y).allMatch(x => betweenExclusive(0, 1, x));
I am simply combining two answers (#Andreas and #Justin Niessner) here, so real credit goes to them.
boolean isXInRange = 0 < x && x < 1;
boolean isYInRange = 0 < y && y < 1;
boolean truth = isXInRange && isYInRange;
Hope this helps!
The statement says:
Write a list of multiples of 7 between 98 and 266, both
including
I put this code:
import java.util.*;
public class Multiples7 {
public static void main (String[] args) {
Scanner entrada;
int x;
entrada = new Scanner(System.in);
while (x >= 98 && x <= 266) {
if (x % 7 == 0){
System.out.println(x);
}
}
}
}
and I get this error that I don't understand:
variable x might not have been initialized
Why x not start?
To solve the question asked: you simply need to initialize x, which is currently uninitialized. To initialize a variable, you have to assign it a value. For example x = 0;.
However, that still is not going to cause your program to print the correct result.
One way to accomplish what you actually want to do is iterate the numbers between 98 and 266 print them when they are divisible by 7.
for(int y = 98; y <= 266; ++y) if (y % 7 == 0) System.out.println(y);
alternately, you can start at 98 (14 * 7) and then increment it by 7, printing as you go.
int y = 98;
while(y <= 266) {
System.out.println(y);
y+=7
}
You need to read the value of x or initialize it yourself. This error is shown because there is a chance that the program might get over without x being initialized.
Just initialize it :
int x = 0;
or read from scanner
x = entrada.nextInt();
Alternatively, you could use a for loop, which includes initialization.
for (int x = 98; x <= 266; x++) {
if (x % 7 == 0) {
System.out.println(x);
}
}
You have only declared x but did not initialize it. Insted of int x do int x = 0;. Replace 0 with the desired value.
You need to give X a starting value or it might as well not exist.
For example if X should start at 0 then use:
int x = 0;
you need to initialize x so it has a starting value and is not empty when your programm starts(int x = 98;). Also you should increment x inside your while loop (x++; or you will have an infinity loop always printing the same line.
int x = 98;
entrada = new Scanner (System.in);
while ( x >= 98 && x <= 266) {
if (x % 7 == 0){
System.out.println(x);
}
x++;
}
It could be a single for loop. Initialize x at 98, increment by 7 and stop when x is greater then 266. Something like,
for (int x = 98; x <= 266; x += 7)
System.out.printf("%d = 7 * %d%n", x, x / 7);
I wish to recurse over two parameters simultaneously in a generic way. Here some explanation:
This is how the function calls should look like Func(int a, int b):
Call 0: Func(0, 0)
Call 1: Func(0, 1)
Call 1: Func(1, 0)
Call 1: Func(0, -1)
Call 1: Func(-1, 0)
How would I implement this in code, ensuring the following statements:
All possible combinations of a INRANGE (-INF, INF) and b INRANGE (-INF, INF) are considered.
There is no overhead, with that I mean that the same function is not used several times in the recursion.
I later want to expand it to do the same thing over 7 parameters.
Regards.
Here's my take on the spiral approach:
// this is your function
static void func(int x, int y)
{
System.out.println("x = "+x+", y = "+y);
}
// this calls func for all possible combinations of signs of the variables in arr
static void allPossibleSigns(int pos, Integer... arr)
{
if (pos == arr.length)
{
func(arr[0], arr[1]); // not really generic
}
else
{
allPossibleSigns(pos+1, arr);
arr[pos] = -arr[pos];
if (arr[pos] != 0)
allPossibleSigns(pos+1, arr);
}
}
static void caller()
{
for (int t = 0; t < MAX; t++)
for (int x = 0; x <= t; x++)
{
int y = (t-x);
allPossibleSigns(0, x, y);
}
}
If you want something more generic than func(arr[0], arr[1]);, you can replace it with:
Method[] methods = NewMain.class.getMethods();
for (Method m: methods)
{
if (m.getName().equals("func"))
m.invoke(null, arr);
}
and add some error checking. I used Integer... instead of int... in printAllPossibleSigns because of this approach (the above doesn't work for int...). This assumes you only have one function called func. If this is not the case, you'll have to add some additional checks.
For MAX = 4, it prints:
x = 0, y = 0
x = 0, y = 1
x = 0, y = -1
x = 1, y = 0
x = -1, y = 0
x = 0, y = 2
x = 0, y = -2
x = 1, y = 1
x = 1, y = -1
x = -1, y = -1
x = -1, y = 1
x = 2, y = 0
x = -2, y = 0
x = 0, y = 3
x = 0, y = -3
x = 1, y = 2
x = 1, y = -2
x = -1, y = -2
x = -1, y = 2
x = 2, y = 1
x = 2, y = -1
x = -2, y = -1
x = -2, y = 1
x = 3, y = 0
x = -3, y = 0
How this will be extended to 3 variable may not entirely be clear, so here's caller for 3 variables:
static void caller()
{
for (int t = 0; t < MAX; t++)
for (int x = 0; x <= t; x++)
for (int y = 0; y <= (t-x); y++)
{
int z = (t-x-y);
printAllPossibleSigns(0, x, y, z);
}
}
And that's about all you have to change, along with your function, obviously, and func(arr[0], arr[1]); if you didn't choose the generic approach.
I propose a spiral, non-recursively easiest.
For ease of reading the move is selected again in every step.
int x = 0;
int y = 0;
for (int t = 0; t < 100; ++t) {
func(x, y);
if (x <= 0 && y == 0) { // Widen spiral.
--x;
++y; // So next condition takes next.
} else if (x < 0 && y >= 0) { // Left, upper quadrant.
++x;
++y;
} else if (x >= 0 && y > 0) { // Right, upper.
++x;
--y;
} else if (x >= 0 && y <= 0) { // Right, lower.
--x;
--y;
} else if (x < 0 && y < 0) { // Left, lower.
--x;
++y;
} else {
throw new IllegalStateException("x = " + x + ", y = " + y);
}
}
I did not try the code! Check the conditions.
Maybe some knowledge of combinatorics would help here. To me this looks like you have a set of elements from -N to to +N. Now you want to call a function with for each variation of length == 7 those elements.
Such a range may be really big. Depending on the cost of the operation you want to call this might take longer than you live.
I would write an Iterator which delivers a new variation of the elements (which are your function parameters) on each call of next().
The implementation of such an iterator could you BigInteger, if you need big numbers. You could use an Array or List and change it's elements on each iteration. If you search for combinatorial algorithms or permutation / variation algorithms you might find details and maybe even implementations.
Another (similar) way (with more overhead, I think) would be to use just one number (e.g. a BigInteger) to mark the current variation. On each iteration you add 1 to this variation index number.
To get your parameters from this number you must perform a base transformation on this variation index. The base will be the number of elements in your elements set. The resulting number's digits each have the range of 0 to the number of elements -1. From this you can use each digit to get the parameters for your function call from the list of elements.
I did than some time ago and it works fine. Can't promise than I can find it.
For n dimensions:
Below I use positive numbers for coordinates. For every positive (greater 0) coordinate in a solution making the coordinate negative also is a solution (almost factor 2^n solutions more). (Using positive numbers simplifies the reading of a solution.)
This is a solutions for a coordinate vector of dimension n. The coordinates are chosen with ever growing "radius" = sum of coordinates.
static void func(int[] x) {
System.out.printf("%s%n", Arrays.toString(x));
}
/**
* Call many funcs with several coordinates.
* #param x n-dimensional coordinates.
* #param fromI starting index for variable coordinates.
* #param r radius, equal to the sum of x[>= fromIndex].
* #param t downward counter limiting the number of calls.
* #return new value of t.
*/
static int callFuncsForRadius(int[] x, int fromIndex, int r, int t) {
if (t <= 0) {
return t;
}
if (fromIndex >= x.length) { // Nothing more to vary.
if (r == 0) { // Read radius sum.
func(x);
--t;
}
return t;
}
for (int rNext = r; rNext >= 0; --rNext) {
x[fromIndex] = rNext;
t = callFuncsForRadius(x, fromIndex + 1, r - rNext, t);
if (t <= 0) {
break;
}
}
return t;
}
static int callFuncs(int[] x, int t) {
int r = 0;
while (t > 0) {
t = callFuncsForRadius(x, 0, r, t);
++r;
}
return t;
}
public static void main(String[] args) {
int n = 3;
int[] x = new int[n];
int t = 10; // N^n, where N = 2^31.
callFuncs(x, t);
}