Initialization outside of conditionals - java

I was a newbie, so sorry for my silly question.
Here's the error:
Test.java:19: error: variable y might not have been initialized
Just wondering how I can retain the value of 'y' without changing everything else outside the conditional block. I know (but not really) why this is erroring, because 'y' isn't defined outside the else block.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
int x, y;
System.out.print("enter value: ");
x = kb.nextInt();
if (x != 5) {
System.out.println("invalid value");
System.exit(0);
}
else {
y = 10;
}
System.out.println("y = " + y);
}
}

Either initialize it, or put the System.out.println inside the else statement where you initialize y.
else
{
y = 10;
System.out.println("y = " + y);
}

System.out.print("enter value: ");
int x = kb.nextInt();
int y =0;

As local variables are not initialized automatically you will have to initialize them before using

int x, y = 0;
Do what the error message says and initialise y

Related

Is there any way of making this method run more than twice

I was asked to write a simple calculator that could run many times as long as the user inputs 'yes' when asked "would you like to perform another operation".
so I did it using a separate method that would be used in a loop in the main method, the problem is it wont run more than twice if the answer is yes
import java.util.Scanner;
public class Calc2 {
// method to be called
static String calcmethod() {
#SuppressWarnings("resource")
Scanner Operation = new Scanner(System.in);
System.out.println("choose operation to perform");
float x, y, sum, sub, mul, div;
String g;
g = Operation.nextLine();
if (g.equals("addition")) {
System.out.println("input the first number ");
x = Operation.nextFloat();
System.out.println("input the second number ");
y = Operation.nextFloat();
sum = x + y;
System.out.print(sum + "\n");
} else if (g.equals("subtraction")) {
System.out.println("input the first number ");
x = Operation.nextFloat();
System.out.println("input the second number ");
y = Operation.nextFloat();
sub = x - y;
System.out.print(sub);
} else if (g.equals("multiplication")) {
System.out.println("input the first number ");
x = Operation.nextFloat();
System.out.println("input the second number ");
y = Operation.nextFloat();
mul = x * y;
System.out.print(mul);
} else if (g.equals("division")) {
System.out.println("input the first number ");
x = Operation.nextFloat();
System.out.println("input the second number ");
y = Operation.nextFloat();
div = x / y;
System.out.print(div);
} else {
System.out.println("invalid input \n");
}
System.out.println("would you like to peform another operation \n");
Scanner Flow = new Scanner(System.in);
String w;
w = Flow.nextLine();
return w;
}
public static void main(String[] args) {
String z = calcmethod();
if (z.equals("yes")) {
calcmethod();
} else {
System.out.println("end of program");
}
}
}
Use do-while loop as shown in below example:
public static void main(String[] args) {
String z = "";
do {
z = calcmethod();
} while(z.equals("yes"));
System.out.println("end of program");
}

I have one variable but Java considers them as two

I have initiated the variable 'answer' in the near header of the class.
Later on when, a random number within an entered range has been generated, that same variable gets a new different value (due to the random generator). But as you can see, the variable 'answer' is indicated in two different colors (blue vs light brown), and as you expect, the routines that I have made are therefore not working. Somehow answer is not equal to answer. What did I do wrongly???? (unfortunately here you don't see the difference in colors).
In eclipse the color of 'answer' at the very top static int answer = 0; is BLUE.
But the one int answer = ThreadLocalRandom.current().nextInt(1, userinput); is GREY
Here's my code:
package Package1;
import java.util.concurrent.ThreadLocalRandom;
import java.util.Scanner;
public class test6KOPIE
{
static int numberofattempts = 0;
static int maxnummerofattemptsallowed = 5;
static int answer = 0;
public static void main(String[] args)
{
if (answer == 0)
{
Scanner maxinput = new Scanner(System.in);
System.out.println("Under which number do you want to guess");
int userinput = maxinput.nextInt();
int answer = ThreadLocalRandom.current().nextInt(1, userinput);
System.out.println(answer);
main(args);
}
else if (numberofattempts < maxnummerofattemptsallowed)
{
Scanner higherlower = new Scanner(System.in);
System.out.println("Higher or Lower");
int digit = higherlower.nextInt();
if (answer == digit)
{
System.out.println("very well");
}
else {
if (answer > digit )
{
++numberofattempts;
System.out.println("Higher, you have " +(maxnummerofattemptsallowed - numberofattempts)+" attempt(s) left)");
System.out.println(numberofattempts);
main(args);
}
else
{
++numberofattempts;
System.out.println("Lower, you have " +(maxnummerofattemptsallowed - numberofattempts)+" attempt(s) left)");
main(args);
}
}
higherlower.close();
}
else {
System.out.println("Maximum number of attempts used, the answer was" +answer);
}
}
This is because you are re-initializing your answer variable by retyping int before it. If you simply want to reassign the value, the line should be:
answer=ThreadLocalRandom.current().nextInt(1, userinput);

java runtime error (NZEC)

So i am working on this ATM problem on codechef and my program runs on my compiler and meets all the problem's requirement however codechef's compiler keeps giving me this NZEC runtime error and i cant figure out why. Here is the code: How can i fix it?
import java.util.Scanner;
public class ATM {
public static final double charge = 0.50;
public static void main(String args[]) {
int x,y;
Scanner keyboard = new Scanner(System.in);
while (keyboard.hasNext()) {
x = keyboard.nextInt();
y = keyboard.nextInt();
if( y > x + charge && x % 5 == 0) {
double balance = y - x - charge;
System.out.println(balance + "0");
} else {
System.out.println(y);
}
}
}
}
You can't use the scanner object in CodeChef. Use BufferedReader instead.
First of all, you did not choose proper data types for your input. Your second input, i.e, y should be of double type, not int type. Then you are not printing your answer in the proper format required by Codechef. Codechef strictly follows the format in which it accepts the answer. Here, your answer must display an output of double/float data type with exactly two decimal places.
Here, I have rectified your mistakes:
import java.util.Scanner;
class ATM {
public static final double charge = 0.50;
public static void main(String args[]) {
int x;
double y;
Scanner keyboard = new Scanner(System.in);
while (keyboard.hasNext()) {
x = keyboard.nextInt();
y = keyboard.nextDouble();
if( y > x + charge && x % 5 == 0) {
double balance = y - x - charge;
System.out.printf("%.2f",balance);
} else {
System.out.printf("%.2f",y);
}
}
}
}
Keep coding :)

How can I test multiple inputs to detect negative numbers, simultaneously recording which input(s) were negative?

I'm writing a short program to prompt the user for numeric inputs, which I will then test to see if they are negative and report back which ones pass this test. I'm looking for a method that avoids duplicating logic for each expected input.
Here's what I have so far:
import java.util.Scanner;
public class Negative
{
public static void main(String[] arg)
{
Scanner scan = new Scanner(System.in);
System.out.println("Insert three integers, USER.");
int x = scan.nextInt();
int y = scan.nextInt();
int z = scan.nextInt();
if (x < 0 || y < 0 || z < 0)
{
System.out.println("A number is negative.");
}
}
}
I know I can do each of these individually but I'd like to condense the code somehow.
You could always create a method that takes the variable name and value and then print it. Something like,
private static void display(String name, int val) {
if (val >= 0) {
System.out.printf("%s (%d) is NOT negative%n", name, val);
} else {
System.out.printf("%s (%d) is negative%n", name, val);
}
}
Then you can call display(),
public static void main(String[] arg) {
Scanner scan = new Scanner(System.in);
System.out.println("Insert three integers, USER.");
display("x", scan.nextInt());
display("y", scan.nextInt());
display("z", scan.nextInt());
}
Now it doesn't actually store x, y or z. If you need them later, then you really do need
public static void main(String[] arg) {
Scanner scan = new Scanner(System.in);
System.out.println("Insert three integers, USER.");
int x = scan.nextInt();
int y = scan.nextInt();
int z = scan.nextInt();
display("x", x);
display("y", y);
display("z", z);
// do something else with x,y or z
}
You can do it by simply applying loop until user inputs positive number :-
int x = scan.nextInt();
int y = scan.nextInt();
int z = scan.nextInt();
while(x<0||y<0||z<0)
{
x = scan.nextInt();
y = scan.nextInt();
z = scan.nextInt();
}
You could also use Google guava preconditions statements to make it cleaner.
For example the above code can be changed..
import com.google.common.base.Preconditions.*;
public class Negative
{
public static void main(String[] arg)
{
Scanner scan = new Scanner(System.in);
System.out.println("Insert three integers, USER.");
int x = scan.nextInt();
int y = scan.nextInt();
int z = scan.nextInt();
Preconditions.checkArgument(x < 0 || y < 0 || z < 0 ,"Negative number entered");
}
}
If the argument fails, an IllegalArgumentExceptionwould be thrown.
More documentation here
Hope this helps..

Java class doesn't have main method

I need to run a method code for GCD. My java file is called "GCD.java" and the public class is called "GCD." Yet I keep getting the message "Class GCD does not have a main method" even though I have no red explanation point circles in any of my lines. I can run the code without the method code (i.e. public static void main(String[] args)), but I need to run the code with a method. Thanks.
==========================
import java.util.Scanner;
public class GCD
{
public static int getDivisor(int x, int y)
{
System.out.println("Greatest Common Divisor Finder");
System.out.println();
String choice = "y";
Scanner sc = new Scanner(System.in);
while (choice.equalsIgnoreCase("y"))
{
System.out.print("Enter first number: ");
x = sc.nextInt();
System.out.print("Enter second number: ");
y = sc.nextInt();
int secondNumber = 0;
int firstNumber = 0;
int Greatestcommondivisionfinder = 0;
// x = first, y = second
if (x > y)
{
do
{
x -= y;
}
while (x > y);
do
{
y -= x;
}
while (y > 0);
System.out.println("Greatest Common Divisor: " + x);
}
else if (y > x)
{
do
{
y -= x;
}
while(y > x);
do
{
x -= y;
}
while (x > 0);
System.out.println("Greatest Common Divisor: " + y);
}
else
{
int subtract;
do
{
subtract = (int)y - (int)x;
}
while(y > x);
int gcd;
gcd = (int)x - subtract;
}
System.out.println();
System.out.print("Continue? (y/n): ");
choice = sc.next();
System.out.println();
}
return 0;
}
}
It's entirely valid for a class not to have a main method - or for it to have a main method which isn't declared as public static void main(String[] args).
However, in order to treat a class as the entry point for a Java application, it needs that method, with that signature (although the parameter name can vary).
So basically, you've got a class which is fine in itself, but you can't launch on its own. You could create a separate class, e.g.
public class GcdLauncher {
public static void main(String[] args) {
GCD.getDivisor(0, 0); // Parameters are ignored anyway...
}
}
Then after compilation you could run:
java GcdLauncher
Or you could add a public static void main(String[] args) method to your GCD class.
I would strongly advise you to change your getDivisor method not to have parameters though - you're not actually using them anyway...
Yes, as your Eclipse correctly says, you don't have main method in your GCD.java file. In-order run this class independently, you need to have main method. Otherwise you can only create Object of this class and call from other class.
If your class is to be used as a main program, it has to implement an
public static void main(String[] args))
Method from where you can call your GCD method.

Categories