nested if statedments, what am i doing wrong - java

homework question is-----Write code that tests the variable x to determine whether it is greater than 0. If x is greater than 0, the code should test the variable y to determine whether it is less than 20. If y is less than 20, the code should assign 1 to the variable z. If y is not less than 20, the code should assign 0 to the variable z.
What i have at the moment is
import javax.swing.JOptionPane;
public class jjjd {
public static void main(String[] args) {
int x=0;
String input;
input=JOptionPane.showInputDialog("Enter a number for x");
x=Integer.parseInt(input);
if (x>0)
if (y<20)
{ (z==1);
}
else
{
z==0;
}
}
}
}
-------------------------------------------- EDIT
import javax.swing.JOptionPane;
public class jjjd {
public static void main(String[] args) {
int x=0;
String input;
input=JOptionPane.showInputDialog("Enter a number for x");
x=Integer.parseInt(input);
if (x>0) {
if (y<20)
{(z=1);}
}
else
{
z=0;
}
}
}
thats my new code!
the error im getting is the (z=0) under the else is "not a statement"

You have misused your braces ({}). You need to make sure that you close all braces after opening them or the java compiler will return an error.
Also make sure to use '=' for assignment and '==' for checking variables.
Hope this helps!
import javax.swing.JOptionPane;
public class jjjd {
public static void main(String[] args) {
int x=0;
int y=0;
int z=0;
String input;
input=JOptionPane.showInputDialog("Enter a number for x");
x=Integer.parseInt(input);
if (x>0) {
if (y<20) {
z=1;
}
} else {
z=0;
}
}
}
EDIT - OP you haven't created the variable 'z' or even 'y'. Make sure to use 'int z=0;' and 'int y=0;' at the top of your code with the 'int x=0;' I have updated my code to show this

To assign a value to a variable you use = not ==

Related

Calling a boolean method from a class

i just made a problem which should return if a number "isHappy" or not. A number is happy if it meets some criteria:
A happy number is a number defined by the following process:
-Starting with any positive integer, replace the number by the sum of the squares of its digits.
-Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.
-Those numbers for which this process ends in 1 are happy.
`
import java.util.HashSet;
import java.util.Set;
class Solution{
public int getNext(int n){
int totalSum = 0;
while(n > 0){
int last = n % 10;
n = n / 10;
totalSum += last * last;
}
return totalSum;
}
public boolean isHappy(int n){
Set<Integer> seen = new HashSet<>();
while( n!=1 && !seen.contains(n)){
seen.add(n);
n = getNext(n);
}
return n==1;
}
}
class Main {
public static void main(String[] args){
isHappy(23); //this doesnt work.
}
}
`
I don't know how to call this function, tried different methods like int number = 23 for ex and then isHappy(number) sout(isHappy(number)); , number.isHappy() although this makes no sense, intellij is telling me to make a method inside main but i dont think i must do this, think there s another way.
There are a couple of problems here. When you run a Java application it looks for the main method in the class you run. Your class has no main method, instead it has an inner class that has a main method.
class Solution {
// existing methods
// no 'Main' class wrapping method
public static void main(String[] argv) {
}
}
The second problem is that main is a 'static' method but isHappy is an 'instance' method. To call it you need an instance of the class
// inside the `main` function
var sol = new Solution();
if (sol.isHappy(23)) {
System.out.println("23 is happy");
} else {
System.out.println("23 is not happy");
}
You have completely solved the problem. You only have to decide what to do with the result of your calculations. You can simply print a string depending on the result.
Please note, that the methods in your Solution class are not static. So, you need to create an instance of the class and call the methods on that instance.
import java.util.HashSet;
import java.util.Set;
class Solution {
public int sumOfDigitsSquares(int n) {
int totalSum = 0;
while (n > 0) {
int last = n % 10;
n = n / 10;
totalSum += last * last;
}
return totalSum;
}
public boolean isHappy(int n) {
Set<Integer> seen = new HashSet<>();
while (n != 1 && !seen.contains(n)) {
seen.add(n);
n = sumOfDigitsSquares(n);
}
return n == 1;
}
}
class Main {
public static void main(String[] args) {
var solution = new Solution();
String answer = solution.isHappy(23) ? "Is happy" : "Not happy at all";
System.out.println(answer);
}
}
Here is one possible way to check all numbers from 1 to 100 for happiness and print the result for each number.
IntStream.rangeClosed(1, 100)
.mapToObj(i -> "" + i + " " + (solution.isHappy(i) ? "is happy" : "not happy"))
.forEach(System.out::println);
To call non-static methods of a class, you need an instance:
public static void main (String [] args) {
Solution foo = new Solution ();
boolean bar = foo.isHappy (49);
// do something with bar
}
To use a static method, you don't use an instance:
class Solution{
public static int getNext(int n){ ... etc ...
}
public static boolean isHappy(int n){ ... etc ...
}
public static void main (String [] args) {
boolean foo = isHappy (1024);
// do something with foo
}
Another problem is you are throwing away the result of isHappy (23).
System.out.println (isHappy(23));
System.out.println ("is 23 happy?" + (isHappy(23) ? "Yes" : "No");
are two possibilities.

Java: Printing triangles and spaces by calling methods

I'm stuck on this question:
Printing stars and spaces
Define a method called printSpaces(int number) that produces the
number of spaces specified by number. The method does not print the
line break.
You will also have to either copy the printStars method your previous
answer or reimplement it in this exercise template. Printing a
right-leaning triangle
Create a method called printTriangle(int size) that uses printSpaces
and printStars to print the correct triangle. So the method call
printTriangle(4) should print the following: Sample output
> *
> **
> ***
> ****
I cannot get the spaces thing to work on the first question, and I'm totally lost on making the recursive triangle. I see that lots of answers are using for loops, however the class I'm working in wants them done as methods. I can't comprehend how to properly translate that. I got the triangle the other way around with this:
public class Test072 {
public static void main(String[] args) {
printTriangle(4);
}
public static void printTriangle(int size) {
int numSize = 0;
while (numSize < size) {
printStars(numSize);
numSize++;
}
}
public static void printStars(int number) {
int numStar = 0;
while (numStar <= number) {
System.out.print("*");
numStar++;
}
System.out.println();
}
}
Once we started adding spaces in, I totally got lost and have no idea how to call what and when. I don't know how to properly call the space method into the triangle method as they are asking.
This should do the job.
public static void printTriangle(int size) {
int numSize = 0;
while (numSize < size) {
printSpaces(size - numSize - 1);
printStars(numSize);
numSize++;
}
}
public static void printSpaces(int number) {
int numSpaces = 0;
while (numSpaces < number) {
System.out.print(" ");
numSpaces++;
}
}
public static void printStars(int number) {
int numStar = 0;
while (numStar <= number) {
System.out.print("*");
numStar++;
}
System.out.println();
}
}
//printStars is printing "number" numbers of stars on one line with a line break
public static void printStars(int number) {
for(int i=1;i<=number;i++){
System.out.print("*");
}
System.out.println();
}
//printSpaces print "number" number of spaces on one line
public static void printSpaces(int number) {
for(int i=1;i<=number;i++){
System.out.print(" ");
}
}
public static void printTriangle(int size) {
for(int i=1;i<=size;i++){
printSpaces(size-i);
printStars(i);
}
}

Sum of Numbers Recursion

I want to display every number leading up to the variable 'number'.
Example, if the number is 5, I would want the result to be 1 2 3 4 5. I have an error for returning a value, I'm not sure why. How do I return the results using recursion?
public class SumOfNumbers {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Number?");
int number = keyboard.nextInt();
System.out.println(recursion(number));
}
public static int recursion(int number)
{
for (int i=0;i>number;i++)
{
return recursion(i);
}
else {
return number ;
}
}
}
You are mixing recursion and iteration. The for loop is unnecessary in your recursive solution.
Think of your recursive solution as if it already exists: what would you do if a program "print numbers up to n-1" was given to you, and you were asked to write a program that prints numbers up to n? The solution would be pretty clear - you would write it like this:
void myRecursiveProgram(int n) {
if (n == 0) {
return; // do nothing
}
printNumbersUpToN(n-1); // Go up to n-1 using the "magic solution"
System.out.println(n); // Complete the task by printing the last number
}
Now observe that myRecursiveProgram is your printNumbersUpToN program, so all you need to do is renaming it:
void printNumbersUpToN(int n) {
if (n == 0) {
return; // do nothing
}
printNumbersUpToN(n-1);
System.out.println(n);
}
Note the if (n == 0) step: it's very important, because it prevents your recursion from going non-stop into negative territory. This is called the base case of recursion - i.e. the case when you do a fixed amount of work, or no work at all.
Your code doesn't compile, you have an else without if.
What you are trying to do is something like:
import java.util.Scanner;
public class SumOfNumbers {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Number?");
int number = keyboard.nextInt();
recursion(number);
}
public static void recursion(int number)
{
if (number>1)
{
recursion(number-1);
System.out.print(number);
}
else {
System.out.print(number);
}
}
}
This short code will also print the numbers right.
public void recursion(int number){
if (number>1)
recursion(number-1);
System.out.println(number);
}

I'm having trouble writing static methods

I'm not very experienced in making static methods...I wanted some practice and I'm having some problems. I'm trying to make a program where you input a number and it prints out all the squares less than b. For example, if you put in 100, it returns 0, 1, 4, 9, 16, 25, 36, 49, 64, 81.
I'm getting errors, though.
Illegal modifier for parameter getSquares; only final is permitted. This is on the line public static double getSquares(double b)
-The method getSquares(int) is undefined for the type Squares when I try to do Squares.getSquares(100);...I'm guessing this is because of my first problem. Please help me, I know static methods are important but I don't know how to make them.
package Testers;
import java.util.Scanner;
public class Squares
{
public static void main(String[] args)
{
Squares.getSquares(100);
public static double getSquares(double b)
{
double sqrtNum=Math.sqrt(b);
int i=0;
while(i<sqrtNum)
{
sqrtNum=Math.pow(i,2);
System.out.print(sqrtNum+" ");
i++;
}
}
}
}
You can't declare a method inside a method - format your code and it is clearer to see. Example:
package Testers;
import java.util.Scanner;
public class Squares {
public static void main(String[] args) {
Squares.getSquares(100);
}
public static double getSquares(double b) {
double sqrtNum = Math.sqrt(b);
int i = 0;
while(i < sqrtNum) {
sqrtNum = Math.pow(i, 2);
System.out.print(sqrtNum + " ");
i++;
}
}
}
Also, there is no returned value in getSquares() - it looks like you intended to make it void.
Finally, this while loop:
int i = 0;
while(i < sqrtNum) {
// code
i++;
}
can be simplified to this for loop:
for (int i = 0; i < sqrtNum; i++) {
// code
}
Your static method should not be in main() if you want it to be a method of the Squares class. it should be in Squares and not in main, like:
public class Squares
{
public static void main(..) {...}
public static double getSquares(...) {...}
}
You're declaring your method in another method, which doesn't work. Put it outside and it should be good.
package Testers;
import java.util.Scanner;
public class Squares
{
public static void main(String[] args)
{
Squares.getSquares(100);
}
public static double getSquares(double b)
{
double sqrtNum=Math.sqrt(b);
int i=0;
while(i<sqrtNum)
{
sqrtNum=Math.pow(i,2);
System.out.print(sqrtNum+" ");
i++;
}
}
}
In your getSquares method you need a return statement.

Setting values to parameters in a constructor in Java

I just wanted to ask basically what the title says. Here's my example and I want x to be the new set random. I also am doing this off a phone switch doesn't support an equal sign so - means equal. Also the bracket is (. So when I do
Constructor a - new Constructor(x)
public class Opponent (
public static x - 0;
public Opponent (int value) (
value - 5;
)
public static void main (String() args) (
Opponent character1 - new Opponent(x)
System.out.println(x);
)
)
Basically I want x to become 5. The game I am developing concerns randomization then the values should give them to the parameter to the newly created character.
Problem I am having is that its not working which means it probably can't do this.
Is there anyway I can do this.
I apologize if it is a dumb question though but anyways thanks.
public class Opponent {
public static int x = 0;
public Opponent (int value) {
x = value;
}
public static void main (String[] args) {
int y = 5; // random number I chose to be 5
Opponent character1 = new Opponent(y);
System.out.println(character1.x + ""); // will display 5 (which was int y)
}
}
List of Problems:
• To open/close a method/class, don't use ( and ); you have to use { and }
• public static void main (String() args) needs to be public static void main (String[] args)
• To initialize something, use =, not -.
• You need to give x a type, such as int.
• When you defined Opponent character1 - new Opponent(x), you need to have a semi-colon at the end.
• You passed x as a parameter in the line Opponent character1 = new Opponent(y);, even though you were trying to define x with the parameter. Give it a different value.
One note: why would you define an instance of the class in the class? Instead of using this:
Opponent character1 = new Opponent(y);
System.out.println(character1.x + "");
You could just write this:
System.out.println(Opponent.x + "");
However, you could create character1 if you were accessing class Opponent from a different class.
I honestly don't know what your question is, but try running this:
public class Opponent {
public int x;
public Opponent (int value) {
x = value;
}
public static void main (String[] args) {
Opponent character1 = new Opponent(5);
System.out.println(character1.x); // this will output: 5
}
}
A few problems with your question:
you are trying to initialize a static variable thinking its an instance variable?
x is not initialized in main()
value is not defined as a field in Opponent
maybe something like this. i leave the random number generation up to you:
public class Opponent
{
private int score;
public Opponent()
{
// you probbaly want to override this with
// a random number generator
this.score = 0;
}
public Opponent(int value)
{
this.score = value;
}
public int getScore()
{
return this.score;
}
public void setScore(int score)
{
this.score = score;
}
public static void main(String[] args)
{
Opponent character1 = new Opponent();
Opponent character2 = new Opponent(5);
int result = character1.getScore() - character2.getScore();
System.out.println(result);
}
}

Categories

Resources