Number.isInteger method cannot be found [duplicate] - java

This question already has answers here:
How to test if a double is an integer
(18 answers)
Closed 1 year ago.
I am a Java newbie and I am facing this error here. Any help would be appreciated. Thank you!
The error is:
symbol: method isInteger(double)
location: class number
Program:
int num = Integer.parseInt(num1.getText());
double square = Math.sqrt(num);
if (Number.isInteger(square))
outputlbl.setText("Number is a perfect square");
else
outputlbl.setText("Number is not a perfect square");

I think you are confusing the Java method with Javascript Number.isInteger().
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger
Unfortunately, we don't have this in java directly.
However, you can use the below code to check if double is an integer or not.
double d = 5;
if( (d % 1) == 0 ) {
System.out.println("Yes");
}
else{
System.out.println("No");
}
PS: This is one of the ways to check if double is an integer or not . If you dig more in java, you will certainly find more ways to do the same.

The Java class Number doesnt have this function. (it exists in javascript though)
Alternatively you can write an easy helper function to solve this problem:
private boolean isInteger(double num)
{
if (num==(long)num)
return true;
return false;
}
The code should be pretty self explanatory.

Related

Getting a nullpointer exception in variable initializer [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I am relatively new to Java and ML but have been trying to learn, so forgive any noob mistakes. I have been following an article about ML in python have been trying to kind of translate it to Java to train the language and learn about the subject in the process, I have been getting a NullPointerException at the line of the variable loss and when I try to initialize the method in the main class, I can`t seem to find the problem.
I have tried running the method in a non static way and just rewriting everything, but it doesn`t seem to work.
public static double calcLoss() {
for (int i = 0; i < y_true.length; i++) {
double a = (1 / y_true.length) * Math.pow(y_true[i] - y_pred[i], 2);
loss = a;
}
return loss;
}
I know it says not to do it but here is a pastr with the full code, maybe this helps. https://pastr.io/view/bSacVk
This is the error
>Exception in thread "main" java.lang.NullPointerException
>at Net.Neuron.calcLoss(Neuron.java:40)
>at Net.Main.main(Main.java:28)
I have been getting a NullPointerException at the line of the variable
loss and when I try to initialize the method in the main class, I
can`t seem to find the problem.
That's because one of y_true or y_pred is likely null. You can easily handle this case by adding a if statement like this,
public static double calcLoss() {
if (null != y_true && null != y_pred && y_pred.length == y_true.length) {
for (int i = 0; i < y_true.length; i++) {
double a = (1d / y_true.length) * Math.pow(y_true[i] - y_pred[i], 2);
// This is just re-assigning loss. Are you sure this is what you intended here?
loss = a;
}
return loss;
}
// y_true is NULL.
return -1;
}
Also, I'm not sure what is the original intent here but, you are just reassigning loss in every iteration of the loop.

Someone have a look at my source code for a number guessing game that seems to keep failing [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
Hello please may someone run my code and assist me in debugging it. I'm having a lot of troubles trying to figure it out and i have not a lot of guidance when it comes to coding.
the problem with my code right now is that it runs certain parts twice. please annotate the issue and any
reccomendations to fix it. Thanks in advance
a brief of what i'm trying to do:
number guessing game
the idea is that the computer will generate a random number and will ask the user if they know the number
if the user gets the answer correct they will get a congrats message and then the game will end but if the user
enters a wrong number they get a try again message and then they will try again
import javax.swing.*;
import java.lang.*;
public class Main {
public static void main(String[] args) {
/*
number guessing game
the idea is that the computer will generate a random number and will ask the user if they know the number
if the user gets the answer correct they will get a congrats message and then the game will end but if the user
enters a wrong number they get a try again message and then they will try again
the problem with my code right now is that it runs certain parts twice. please annotate the issue and any
recomendations to fix it. Thanks in advance
*/
enterScreen();
if (enterScreen() == 0){
number();
userIn();
answer();
}
}
public static int enterScreen (){
String[] options = {"Ofcourse", "Not today"};
int front = JOptionPane.showOptionDialog(null,
"I'm thinking of a number between 0 and 100, can you guess what is is?",
"Welcome",
JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE,
null, options, "Yes" );
if(front == 0){
JOptionPane.showMessageDialog(null, "Goodluck then, you might need it. :D");
}
else {
JOptionPane.showMessageDialog(null, "okay i dont mind");
}
return front;
}
private static int number(){
double numD;
numD = (Math.random() * Math.random()) * 100;
int numI = (int) numD;
System.out.println(numD);
return numI;
}
private static int userIn(){
String userStr = JOptionPane.showInputDialog("What number do you think im thinking of?");
int user = Integer.parseInt(userStr);
return 0;
}
private static void answer(){
// here is the problem
if(userIn() == number()){
JOptionPane.showMessageDialog(null, "Well done! You must be a genius.");
}
else {
JOptionPane.showMessageDialog(null, "Shame, TRY AGAIN!");
userIn();
}
}
}
Your problem is this part:
enterScreen();
if (enterScreen() == 0) {
number();
userIn();
answer();
}
You can leave out the first enterScreen(). Because you call it again in the if statement. If you look at the return type of the method: public static int, it returns and int. This makes it so that the outcome of the method is directly available in the if statement. The fist enterScreen is basicly useless, because you dont use the result.
You could do this:
int num = enterscreen();
if (num == 0) {
number();
userIn();
answer();
}
Which is basicly the same as:
if (enterScreen() == 0) {
number();
userIn();
answer();
}
You call enterScreen() twice. Just call it once, and compare the value returned only once.
Also, StackOverflow typically is not for "Here's my code, fix it" kind of not questions.
https://stackoverflow.com/help/how-to-ask
You call enterScreen() and userIn() functions twice or more. Please Computer Science and coding. Hint: Computer's execute intructions from top to bottom.

Java class to calculate shortest and longest side of a triangle

I've been working on my assignment all day and am stuck at just one part. I am pretty good at searching the internet and finding answers and have checked here as well. I still can't seem to figure out what is going on.
For the assignment we need to write a class with methods that will test a triangle. I am struggling with understanding classes, but have been able to get most of the code to work. The only issue I have now is with the is_equilibrium(); method. When running with the program provided with the assignment, the equilibrium method will return true every time.
problem code:
public boolean is_equilateral()
{
if(longest == shortest)
{
return true;
}
else
{
return false;
}
}
When I change it to:
public boolean is_equilateral()
{
if(side1 == side2 && side2 == side3&& side3 == side1)
{
return true;
}
else
{
return false;
}
}
I the code works fine and will return the true or false values.
I hope I am asking everything right, I am still trying to learn java so please bear with me! Any help is greatly appreciated!

Creating a coin flip class [duplicate]

This question already has answers here:
How do I generate random integers within a specific range in Java?
(72 answers)
Closed 6 years ago.
I have recently begun programming at university and I am a little stumped with one of my tutorial problems.
I basically need to create a method within a class which uses the Random.nextInt()
method to flip a coin, assigning and saving the value once the process has been run.
MY current attempts include this:
public void Flip() {
int flipResult;
flipResult = mRandNumGen.nextInt(1);
if(flipResult == 0)
{
mFace = 'H';
}
else
{
mFace = 'T'
}
}
mFace and mRandNumGen are variables which have been declared already outside the specific method. What exactly is going wrong here? I can't for the life of me get this to work :/
Simple way to do this:
if (mRandNumGen.nextBoolean()) {
mFace = 'H';
} else {
mFace = 'T';
}
The first argument in Random.nextInt is an exclusive upper bound, not inclusive.
So with n=1 it will always return 0. for n=2 it will return either 0 or 1 which is what you're looking for.

Python Program converted into Java

Sooo I started taking my second computer science class ever! For my first class we used python and for this class we're using Java. Our first assignment (pretty much just practice) is to convert this craps program from Python to Java and I'm just having a hell of a time.
Could someone please help with what I've done and umm give me some advice? Maybe a good site for a beginner.... Someone that kinda knows Python (only from a first CS course perspective).
1) In python
def winCraps():
roll = rollDice()
if roll == 7 or roll == 11:
return True
elif roll == 2 or roll == 3 or roll == 12:
return False
else:
return rollForPoint(roll)
This is my attempt at the conversion of it over to java
public int winCraps{
roll = rollDice();
if (roll = 7 && 11){
return (true);
}
else (roll =2 && 3 && 12){
return(false);
}
else{
return rollforPoint(roll);
}
}
2) Python
def rollDice():
raw_input("Press <Enter> to roll...")
die1 = randrange(1,7)
die2 = randrange(1,7)
sum = die1 + die2
print "You rolled", die1, "+", die2, "=", sum
return sum
This one confused the hell out of me. What would randrange be in Java??
Java
static int rollDice(){
System.out.print("Press <Enter> to roll...");
double die1 = Math.random();
double die2 = Math.random();
die1 = (int) die1*6+1;
die2 = (int) die2*6+1;
int sum = (int)die1 + (int)die2;
System.out.println("You rolled "+die1+ " + "+die2+ " = "+sum+".");
return sum;
}
*please bear in mind that I'm just learning this stuff lol
You need to fix your if statements the "==" operator checks for equality, and you must put the variable you are checking against in each section of the statement.
public int winCraps{
roll = rollDice();
if (roll == 7 || roll == 11) {
return true;
}
else if(roll == 2 || roll == 3 || roll == 12) {
return false;
}
else{
return rollforPoint(roll);
}
}
In you rollDice() method, the way you assign values to each die is incorrect. I recommend reading up on random numbers (since this is homework, I'll leave that to you).
Also, remember in java you must always end each statement with a semicolon
What would randrange be in Java?
You can get a random integer in a specific range from Java's Random class by calling the nextInt(int n) method. For example,
Random rand = new Random();
int a = rand.nextInt(7);
will give you a random integer >= 0 and < 7. This isn't exactly the same as randrange in Python, but you could use it as the index to an array of objects, or as the value of a roll of a single die.
Randrange can be replaced by methods in java.util.Random. Like Python, Java has an extensive standard library which you should reference.
1) In Java "OR" operator is "||" not "&&" and comparison operator is "==" as in Python
So
if roll == 7 or roll == 11:
Should be
if( roll == 7 || roll == 11 ) {
and not
if( roll = 7 && 11 ){
2) randrange is : random generator from there you can search: Random in Java
Which will lead you to something like: Random.nextInt()
Use this algorithm ( a) search Internet for Python function, b) understand what it does c) search it in java ) for the next assignment you have and you're done.
You can always ask here again, that's what this site is all about after all
I'd recommend that you look up the docs on randrange(). Once you know exactly what it does, google for the those keywords, plus the word Java.
One thing you'll quickly discover in working with languages is that the APIs can be very different. There might not be an equivalent of randrange in Java, but you might be able to find two or three functions that you can combine to do the same thing.
System.out.print isn't going to cause the system to wait for someone to hit the enter key. For that, you need to do something with System.in, most likely System.in.read(), as it blocks while waiting for input.
Also, in Java, a program starts executing with the main method. To be exact, an executable class starts something like this:
// You'll need the Random class, as per other answers
import java.util.Random;
// assuming WinCraps is the class name
public class WinCraps {
// args in this example is a string array of command-line arguments
public static void main(String[] args) {
// This is where your main method (that calls winCraps?) would be
}
// Other methods
}
Also, any method in this class called directly from main must also be static.
Write out in English what the Python program does. Go through it line by line and explain to yourself what computations are evoked, in other words...what is happening?
Afterwards, write the Java program from that description.
Never ever try to convert the text of a program from one language to another. You'll run into a LOT of problems that way because every language is different, no matter how similar they look.
One major error in your first program that you have in the Java conversion is the conditionals.
Something like (roll =2 && 3 && 12) assigns 2 to roll and then applies AND operators. You also forgot the if. You have elseif in Python.
You want something like:
else if(roll==2 || roll==3 || roll==12)
As for random numbers, there is a function for that in Java.

Categories