java runtime error (NZEC) - java

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 :)

Related

Java: Calling variables of user input from one method to another

I'm currently modifying a previous Java program that computes quadratic formula type math problems by breaking parts of my code down into methods and calling those methods to complete the same task. Currently I'm stuck on creating a method to calculate the discriminant in the numerator. As assigned, I'm supposed to have one method that receives user input for the a,b, and c values, but I'm not sure how to get those values from one method into the next that is supposed to use those values in calculations.
My instructor wants us to have the a b and c variables input into an array and I know the way it is now is a pretty manual way of putting values into an array, but should still work for this purpose.
Here is what I have thus far and thanks for reading.
EDIT: I've started again from scratch, I can't figure out how to properly return information from my methods so that the next can use it. I keep getting method argument not applicable errors. Any ideas?
import java.util.*;
public class QuadraticMethods {
public static void main(String[] args){
getValues();
calcDisc(userInput);
}
public static double[] getValues() {
double[] userInput;
userInput = new double[3];
Scanner kbd = new Scanner(System.in);
System.out.println("Fourth Assignment by MyNameHere");
System.out.println("Welcome to the quadratic formula computation tool.");
System.out.println("This tool will solve problems in the form of: a^x + bx + c.");
System.out.println("Please enter the values you would like for a, b, and c.");
for (int i = 0; i < userInput.length; i++) {
userInput[i] = kbd.nextDouble(); }
double aValue = userInput[0];
double bValue = userInput[1];
double cValue = userInput[2];
/*
System.out.println(aValue);
System.out.println(bValue);
System.out.println(cValue);
*/
return userInput;
}
public static double calcDisc(double[] userInput) {
double aValue = userInput[0];
double bValue = userInput[1];
double cValue = userInput[2];
double radicalValue = (Math.pow(bValue, 2) - (4*aValue*cValue));
System.out.println(radicalValue);
return radicalValue;
}
}
To get your current code to work, only a small change is required:
public static void main(String[] args) {
double[] userInput = getValues();
calcDisc(userInput);
}
Further these assignments are not actually used.
public static double[] getValues() {
// ...
double aValue = userInput[0];
double bValue = userInput[1];
double cValue = userInput[2];
// ...
}
Some other improvements could be:
The result should not be printed by the method that calculates it. You already declared the method the right way by returning the value. Now you should use the returned value and print the result in the calling method.
public static void main(String[] args) {
double[] userInput = getValues();
double radicalValue = calcDisc(userInput);
System.out.println(radicalValue);
}
// ...
public static double calcDisc(double[] userInput) {
double aValue = userInput[0];
double bValue = userInput[1];
double cValue = userInput[2];
double radicalValue = (Math.pow(bValue, 2) - (4 * aValue * cValue));
return radicalValue;
}
Printing the banner should probably not be mixed with requesting the user input. Imagine, you would want to repeat the read/evaluate/print cycle:
public static void main(String[] args) {
while (true) {
double[] userInput = getValues();
double radicalValue = calcDisc(userInput);
System.out.println(radicalValue);
}
}
would print the banner text every time. Isolating the responsibilities enables you to alter behaviour without affecting unrelated code.
public static void main(String[] args) {
printBanner();
while (true) {
double[] userInput = getValues();
double radicalValue = calcDisc(userInput);
System.out.println(radicalValue);
}
}
private static void printBanner() {
System.out.println("Fourth Assignment by MyNameHere");
System.out.println("Welcome to the quadratic formula computation tool.");
System.out.println("This tool will solve problems in the form of: a^x + bx + c.");
}
Scanner should be closed after use. Java 7 try with resources will do that for you.
public static double[] getValues() {
double[] userInput;
userInput = new double[3];
try (Scanner kbd = new Scanner(System.in)) {
System.out.println("Please enter the values you would like for a, b, and c.");
for (int i = 0; i < userInput.length; i++) {
userInput[i] = kbd.nextDouble();
}
}
return userInput;
}

Newtonian Square Root Java Program

I wrote this program to show the Newtonian method of finding the square root and then to run the math function to find that square root and print both of them out. The math part is working well but the loop I created isn't coming up with the right square root for the newtonian method. Any ideas? Thanks in advance.
package newton_sqrt;
import java.util.Scanner;
public class Newton_sqrt {
public static void main(String[] args) {
double guess, new_guess, last_guess, accuracy, n, x, absolutex;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter in N for Newton: ");
n = keyboard.nextDouble();
last_guess = n / 2;
do {
new_guess = ((n/last_guess) + last_guess)/2;
x = new_guess - last_guess;
if(x>=0)
absolutex=x;
else
absolutex=-x;
} while(absolutex < .000001);
System.out.println("Newton = " +new_guess);
double mth = Math.sqrt(n);
System.out.println("Math.sqrt = " +mth);
}
}
Invert the loop condition. You want to loop while absolutex is bigger than epsilon, not while it's smaller. You want to stop when it is small enough.
do {
} while(absolutex > .000001);
looks like math part need little tweaks, so does with loop condition. here try it, it works
package newton_sqrt;
import java.util.Scanner;
public class Newton_sqrt {
public static void main(String[] args) {
// TODO code application logic here
double guess, new_guess = 0, last_guess, accuracy, n, x, absolutex;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter in N for Newton: ");
n = keyboard.nextDouble();
last_guess = n / 2;
do {
new_guess = last_guess - (last_guess*last_guess-n) / (2*last_guess);
x = Math.abs(last_guess - new_guess);
if (x < .000001) {
break ;
} else {
last_guess = new_guess;
}
} while (n >= .00);
System.out.println("Newton = " + new_guess);
double mth = Math.sqrt(n);
System.out.println("Math.sqrt = " + mth);
}
}

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..

Output error resulting from logic error when determining percentage based on incremental while loop

I have created a simple class which calculates the win/loss percentage and returns the amount of necessary consecutive wins to obtain the desired win/loss percentage of the given input from the user, based on the given values of wins, loss, and desired win/loss. However, whilst running the program, I notice the output gives an exceedingly large number in the place of what should be a relatively small number (the number of wins needed). I am not certain what error I have made that created this, but I'm certain it's relative to the while loop located in my howManyToWinLoss() method, or perhaps some error I've made in the tester class's output. At any rate, they are both located below, and I appreciate the assistance:
public class WinLossCalculator
{
private int win;
private int loss;
private int totalGames;
private double desiredWinLoss;
private double winLoss;
private int gamesToDWL;
public WinLossCalculator(int w, int l, double dwl)
{
win = w;
loss = l;
totalGames = w + l;
desiredWinLoss = dwl;
}
public double winPercent()
{
return winLoss = (double)win/(double)totalGames;
}
public double lossPercent()
{
return (double)loss/(double)totalGames;
}
public int howManyToWinloss()
{
int x = 0;
while(winLoss < desiredWinLoss)
{
winLoss = (win+x)/(win+x+loss);
if(winLoss < desiredWinLoss)
{
x++;
}
}
return gamesToDWL = x;
}
}
and
import java.util.*;
public class WinLossTester
{
public static void main(String []args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter the amount of matches you've won: ");
int wins = in.nextInt();
System.out.print("\nEnter the amount of matches you've lost: ");
int losses = in.nextInt();
System.out.print("\nEnter your desired match win percentage (eg. 75.4): ");
double desiredWLP = in.nextDouble();
System.out.println();
WinLossCalculator one = new WinLossCalculator(wins, losses, (desiredWLP / 100));
one.winPercent();
one.howManyToWinloss();
System.out.printf("Win percentage: %6.1f", (one.winPercent()*100));
System.out.print("%");
System.out.printf("\nLoss percentage: %5.1f", (one.lossPercent()*100));
System.out.print("%");
System.out.println("\nVictories required to reach desired W/L percent (without loss): " + one.howManyToWinloss());
}
}
Additionally--I feel as though my tester class's output section is a little ugly, might anyone have any suggestions concerning formatting or cleaning up the code in the output section?
Ok, apparently it has to do with me not casting the first line in my for loop to double like this winLoss = (double)(win+x)/(double)(win+x+loss); I don't know why that broke it, but, that's why it was broken.

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