The user should enter the values to x and y, and if x is greater than 5 and and when y= 0 , then z should be equivalent to x+y. However, when I compile it gives me an error saying that z might not have been initialized.
import java.util.Scanner;
public class add {
public static void main(String[] args ){
Scanner input = new Scanner (System.in);
System.out.print("Enter a value for x");
int x = input.nextInt();
System.out.print("\nEnter a value for y ");
int y = input.nextInt();
int z;
if (x > 5){
if (y == 0)
z = x + y;
System.out.println("The answer is " + z);
}
else
System.out.println("The answer is only" + x);
}
}
There is an execution path where z doesn't get initialized, but you attempt to print it. If x is greater than 5, but y isn't 0, then z is not initialized, but you refer to z when printing it.
Use braces to create an inner block for your inner if statement, so z is only referenced if it's initialized:
if (x > 5){
if (y == 0) {
z = x + y;
System.out.println("The answer is " + z);
}
}
Also, proper indenting helps to identify visually what's part of a block and what's not.
Your 'if' statement is misleading:
if (y == 0)
z = x + y;
What if y != 0? In that case, z is not initialized.
The next line
System.out.println("The answer is " + z);
doesn't apply to the y==0 statement, as you don't have braces {}.
You probably meant to write something like:
if (x > 5) {
if (y == 0) {
z = x + y;
System.out.println("The answer is " + z);
}
}
Note the "{" after the if statement.
As you are not using braces for if condition, your z will not initialized.
To solve such kind problems always keep in mind that if you are calculating something with integer variable do initialize them with some value (here, 0 is the best).
Then you can access that variable anywhere in the code without any initialization error.
To rid of this problem, you have two ways
One way:
just simply initialize your z variable like:
int z=0;
Second way:
Try to put braces for if condition like:
if (y == 0){
z = x + y;
System.out.println("The answer is " + z);
}
You need to assure the compiler that z will get a value no matter what.
You may want to assign it a default value when declaring it.
Something along these lines:
int z = 0; // just an example
int z has no value, try the code at the bottom then give it a 0 or input.nextInt();
int z = 0;
or
int z = input.nextInt();
Related
Can someone explain how the if method works because I don't understand this code? I understand the if statement part but not the z+=0, z+=1 part because this is not my code.
int x,y,z = 0;
System.out.println("Input two numbers: ");
x=sc.nextInt();
y =sc.nextInt();
if (x>y) {
z+=0;
}else if (y>x) {
z+=1;
}
switch(z) {
case 0: System.out.print(x + " is greater than " + y +".");
break;
case 1: System.out.print(y + " is greater than " + x +".");
break;
default: System.out.print("Both are equal.");
}
}
z += 1 is the same thing as z = z + 1
z += 0 is the same thing as z = z + 0
so if x > y then z will have the value 0
and if x < y then z will have the value 1
In this code, z is simply a count of the number of times y was larger than x. The z+=1; is just an increment - it's a shorthand notation for z = z + 1, so all it does is take z and increase its value by 1 (this increment is so common that many languages have included the += shorthand notation for it). The z+=0; things is superfluous, it simply leaves z unchanged.
z += x;
can also be written as:
z = z + x;
Assuming that int z = 3;
z += 0;
is pointless and will result in z = 3
z += 1;
will result in z = 4
The following code is designed to factorize a number typed into the variable x.
public class testMod{
public static void main(String[]args){
double x = 11868681080091051216000;
StringBuilder output = new StringBuilder("1 * ");
for(double y = 2; y <= x; y++){
while (x % y == 0) {
System.out.print("Calculating... \n");
String printNumber = y + " * ";
x = x / y;
output.append(printNumber);
System.out.print(output.substring(0, output.length() - 2) + "\n");
}
}
}
}
The problem is that the compiler treats 11868681080091051216000 as an int, regardless of the attempt to assign it to a double. As such, it's out of range.
To specify a double literal, you can simply append D to the end – but do note that you'll lose precision this way:
double x = 11868681080091051216000D;
System.out.println(x); // prints 186868108009105E22
If you need the full precision, you can use a BigInteger instead, but you'll still need to specify that number in expressions that Java can handle, such as a product of its factors.
Ok so i need to Create a method in the LogicalOp class, which will receive two number parameters. The method must check which of the two numbers is larger, and execute an increasing count from the smallest to the largest. (Eg: if x is the first parameter and int y is the second, if x is greater than y, then the count is from y to x).
I have tried different methods but they either did not do anything or go for an infinite loop. I don't know how to stop a loop from x to y if the x is smaller then y and from x the count starts to y and then stop there to the biggest number i imputed in console.
public void getForthExercise() {
System.out.println("Give the x parameter and y ");
Scanner in = new Scanner(System.in);
int x = in.nextInt();
int y = in.nextInt();
if (x > y) {
for (int i = x; i >= y; i++)
System.out.println(i);
} else if (x < y) {
for (int i = y; i >= x;i++ )
System.out.println(i);
So if i imput x=25 and y=5 || y
Let's give you a hint how to simplify the problem: you do not need to care about x < y, or y > x for looping.
You only care: about the smaller number of that pair, and the larger number!
In other words: you simply have to loop from min(x, y) to max(x, y).
Think about it: for what needs to be printed, does it really matter whether x is 5 or 25, or whether y is 25 or 5? No, the only thing that matters is: you got 5, and 25. Which one came in first, and which one second, that doesn't change anything about the expected output!
Have a look at this:
int min = Math.min(x, y);
int max = Math.max(x, y);
for(int i = min; i < max; i++) {
System.out.println(i);
}
I need to ask the user how many times he want to put his notes, then do a loop
how many times he need to put his note and finally calculate the moyenne, but im putting that double a = a+n; means that it calculate the notes number, and finally in s.o.p, im putting to divide the notes number on how much he asked first.
java is giving me error, any help?
Here is my code:
package minmax;
import java.util.Scanner;
public class MinMax {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int x, y, z;
System.out.println("Combien de notes vous avez? ");
x = in .nextInt();
for (y = 0; y < x; y++) {
do {
System.out.println("Mettez votre note :");
z = in .nextInt();
}
while (z < 20 || z > 0); {
double a = a + n;
}
}
System.out.println("Votre moyenne est : " + (a / x));
}
}
Fixes and suggestions:
Variables have to be initialized first (strictly without referring themselves), "updates" (referring themselves, the a=a+something, a++, a+=something kind of things) can happen only afterwards
In Java you usually bring variable declaration and usage close to each other, and remember that you can declare and initialize a variable in a single statement.
In the case of using a do-while loop, do not bracket+indent lines following the while(...);, such following lines are on the same level as the do-while loop itself
Whitespace preceding . looks strange, unless you break an expression into several lines
Put them together:
package minmax;
import java.util.Scanner;
public class MinMax {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Combien de notes vous avez? ");
int x = in.nextInt();
double a = 0;
for (int y = 0; y < x; y++) {
int z;
do {
System.out.println("Mettez votre note :");
z = in.nextInt();
}
while (z < 0 || z > 20);
a = a + z;
}
System.out.println("Votre moyenne est : " + (a / x));
}
}
(Plus a=a+n became a=a+z for the obvious reason of z containing the number from the user, and the comparison directions had to be swapped - assuming that you want numbers between 0...20)
Simple:
double a = a + n;
You can't define a variable and initialize it with itself.
Meaning: it is not possible to declare a, but also assign a value to a that requires a.
In other words: the code you wrote really makes no sense. Maybe you should simply put: double a = 0 somewhere above that statement, and then only do: a = a + n further down.
And of course: also use real names. a, n, those names mean nothing. Use something that tells the human reader about the intent of these variables.
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.