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.
Related
I have three classes. An abstract class, a derived class and a main class. I am trying to print the method in the derived class in the main class.
public abstract class newsPaperSub {
public String name;
public abstract void address();
public double rate;
}
Derived class:
import java.util.Scanner;
public class PhysicalNewspaperSubscription extends newsPaperSub {
#Override
public void address () {
String subAddress = " ";
Scanner input = new Scanner(System.in);
int i;
int digitCount = 0;
for (i = 0; i < subAddress.length(); i++) {
char c = subAddress.charAt(i);
if (Character.isDigit(c)) {
digitCount++;
System.out.println("Pease enter an address: ");
subAddress = input.nextLine();
if (digitCount <= 1) {
rate = 15;
System.out.println("Your subscrption price is: " + rate);
}
}
}
}
}
Main class: I havent been able to figure out what to exactly put in the main class in order to print the function in the derived class. I have tried a couple things with no luck. Any help would be greatly appreciated.
public class demo {
public static void main (String [] args) {
}
}
Just put inside of the main method
PhysicalNewspaperSubscription subscription= new PhysicalNewspaperSubscription()
and then call your method
subscription.address()
in the main method as well.
Simply put:
public class demo {
public static void main (String [] args) {
PhysicalNewspaperSubscription pns = new PhysicalNewspaperSubscription();
pns.address();
}
}
... but your code will not do anything.
The reason being because though you have a Scanner to read in something from the console, it'll never run that piece of code because the following loop structure never runs:
for (i = 0; i < subAddress.length(); i++) {
...
}
The reason it does not run is because when you declare subAddress you set it to an empty String (String subAddress = " ";), so when the loop checks the condition (i < subAddress.length()) it'll evaluate FALSE, because 0 < 0 is FALSE and hence not run the loop.
import java.util.Arrays;
import java.util.*;
import java.util.stream.Collectors;
// double the first even number greater than 3
public class FirstDouble {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1,2,3,5,6,7,8,9);
/* int result = 0;
for(int e : numbers)
{
if(e>3 && e%2==0)
{
result = e*2;
break;
}
}
System.out.println(result);
*/
System.out.println(
numbers.stream()
.filter(Sample::isGT3)
.filter(Sample::isEven)
.map(Sample::doubleIt)
.findFirst());
}
public boolean isGt3(int number) {
return number > 3;
}
public boolean isEven(int number) {
return number % 2 == 0;
}
public int doubleIt(int number) {
return number * 2;
}
}
Three modifications are needed to make the code compile:
Rename Sample to FirstDouble in order to properly reference the class
Rename the method isGt3 to isGT3
As the methods are referenced statically, add the static modifier to isGT3, isEven and doubleIt
After that, it prints out Optional[12]. If only the number should be printed, add a get after findFirst.
I'm in a beginning programming class, and a lot of this had made sense to me up until this point, where we've started working with methods and I'm not entirely sure I understand the "static," "void," and "return" statements.
For this assignment in particular, I thought I had it all figured out, but it says it "can not find symbol histogram" on the line in the main method, although I'm clearly returning it from another method. Anyone able to help me out?
Assignment: "You see that you may need histograms often in writing your programs so you decide for this program to use your program 310a2 Histograms. You may add to this program or use it as a class. You will also write a class (or method) that will generate random number in various ranges. You may want to have the asterisks represent different values (1, 100, or 1000 units). You may also wish to use a character other than the asterisk such as the $ to represent the units of your graph. Run the program sufficient number of times to illustrate the programs various abilities.
Statements Required: output, loop control, decision making, class (optional), methods.
Sample Output:
Sales for October
Day Daily Sales Graph
2 37081 *************************************
3 28355 ****************************
4 39158 ***************************************
5 24904 ************************
6 28879 ****************************
7 13348 *************
"
Here's what I have:
import java.util.Random;
public class prog310t
{
public static int randInt(int randomNum) //determines the random value for the day
{
Random rand = new Random();
randomNum = rand.nextInt((40000 - 1000) + 1) + 10000;
return randomNum;
}
public String histogram (int randomNum) //creates the histogram string
{
String histogram = "";
int roundedRandom = (randomNum/1000);
int ceiling = roundedRandom;
for (int k = 1; k < ceiling; k++)
{
histogram = histogram + "*";
}
return histogram;
}
public void main(String[] Args)
{
System.out.println("Sales for October\n");
System.out.println("Day Daily Sales Graph");
for (int k = 2; k < 31; k++)
{
if (k == 8 || k == 15 || k == 22 || k == 29)
{
k++;
}
System.out.print(k + " ");
int randomNum = 0;
randInt(randomNum);
System.out.print(randomNum + " ");
histogram (randomNum);
System.out.print(histogram + "\n");
}
}
}
Edit: Thanks to you guys, now I've figured out what static means. Now I have a new problem; the program runs, but histogram is returning as empty. Can someone help me understand why? New Code:
import java.util.Random;
public class prog310t
{
public static int randInt(int randomNum) //determines the random value for the day
{
Random rand = new Random();
randomNum = rand.nextInt((40000 - 1000) + 1) + 10000;
return randomNum;
}
public static String histogram (int marketValue) //creates the histogram string
{
String histogram = "";
int roundedRandom = (marketValue/1000);
int ceiling = roundedRandom;
for (int k = 1; k < ceiling; k++)
{
histogram = histogram + "*";
}
return histogram;
}
public static void main(String[] Args)
{
System.out.println("Sales for October\n");
System.out.println("Day Daily Sales Graph");
for (int k = 2; k < 31; k++)
{
if (k == 8 || k == 15 || k == 22 || k == 29)
{
k++;
}
System.out.print(k + " ");
int randomNum = 0;
int marketValue = randInt(randomNum);
System.out.print(marketValue + " ");
String newHistogram = histogram (randomNum);
System.out.print(newHistogram + "\n");
}
}
}
You're correct that your issues are rooted in not understanding static. There are many resources on this, but suffice to say here that something static belongs to a Class whereas something that isn't static belogns to a specific instance. That means that
public class A{
public static int b;
public int x;
public int doStuff(){
return x;
}
public static void main(String[] args){
System.out.println(b); //Valid. Who's b? A (the class we are in)'s b.
System.out.println(x); //Error. Who's x? no instance provided, so we don't know.
doStuff(); //Error. Who are we calling doStuff() on? Which instance?
A a = new A();
System.out.println(a.x); //Valid. Who's x? a (an instance of A)'s x.
}
}
So related to that your method histogram isn't static, so you need an instance to call it. You shouldn't need an instance though; just make the method static:
Change public String histogram(int randomNum) to public static String histogram(int randomNum).
With that done, the line histogram(randomNum); becomes valid. However, you'll still get an error on System.out.print(histogram + "\n");, because histogram as defined here is a function, not a variable. This is related to the return statement. When something says return x (for any value of x), it is saying to terminate the current method call and yield the value x to whoever called the method.
For example, consider the expression 2 + 3. If you were to say int x = 2 + 3, you would expect x to have value 5 afterwards. Now consider a method:
public static int plus(int a, int b){
return a + b;
}
And the statement: int x = plus(2, 3);. Same here, we would expect x to have value 5 afterwards. The computation is done, and whoever is waiting on that value (of type int) receives and uses the value however a single value of that type would be used in place of it. For example:
int x = plus(plus(1,2),plus(3,plus(4,1)); -> x has value 11.
Back to your example: you need to assign a variable to the String value returned from histogram(randomNum);, as such:
Change histogram(randomNum) to String s = histogram(randomNum).
This will make it all compile, but you'll hit one final roadblock: The thing won't run! This is because a runnable main method needs to be static. So change your main method to have the signature:
public static void main(String[] args){...}
Then hit the green button!
For starters your main method should be static:
public static void main(String[] Args)
Instance methods can not be called without an instance of the class they belong to where static methods can be called without an instance. So if you want to call your other methods inside the main method they must also be static unless you create an object of type prog310t then use the object to call the methods example:
public static void main(String[] Args)
{
prog310t test = new prog310t();
test.histogram(1);
}
But in your case you probably want to do:
public static String histogram (int randomNum)
public static void main(String[] Args)
{
histogram(1);
}
Also you are not catching the return of histogram() method in your main method you should do like this:
System.out.print(histogram(randomNum) + "\n");
Or
String test = histogram(randomNum);
System.out.print(test + "\n");
Static methods are part of a class and can be called without an instance but instance methods can only be called from an instance example:
public class Test
{
public static void main(String[] args)
{
getNothingStatic();// this is ok
getNothing(); // THIS IS NOT OK IT WON'T WORK NEEDS AN INSTANCE
Test test = new Test();
test.getNothing(); // this is ok
getString(); // this is ok but you are not capturing the return value
String myString = getString(); // now the return string is stored in myString for later use
}
public void getNothing()
{
}
public static void getNothingStatic()
{
}
public static String getString()
{
return "hello";
}
}
Void means the method is not returning anything it is just doing some processing. You can return primitive or Object types in place of void but in your method you must specify a return if you don't use void.
Before calling histogrom (randomNum) you need to either make histogram static or declare the object that has histogram as a method
e.g
prog310t myClass = new prog310t();
myClass.histogram()
I would like to make a Number class that has a static set of prime numbers.
I want the numbers to be stored in a static set for the class but I want to add the numbers to the set as the class is asked to find prime numbers. As in I only want to add numbers to this set when a separate method for testing a prime number is called and a prime number is found.
For some reason the static final set erases itself when another class uses this class (Number).
Here is some of my code for the Number class.
public class Number {
private int number;
static final HashSet<Integer> pSet = new HashSet<>();
static {
pSet.add(2);
}
public Number(int n) {
number = n;
}
public boolean isPrime() {
boolean out = true;
if (number == 1) { return true; }
if (pSet.contains(number)) { return true; }
for (int i : pSet) {
if (number%i == 0) {
out = false;
break;
}
}
if (out) { pSet.add(number); }
return out;
}
}
How can I make this set not override itself but not be statically defined?
I'm a bit confused. In the code that you have posted up, the Set should not be erased, because you have defined it as static. Are you saying that when you make it not static, then it gets erased when you call the class?
I'm assuming that the class works as you have posted it, but you want to make the Set non-static, but that when you do that, it gets erased.
So the first thing to do is:
private final HashSet<Integer> pSet = new HashSet<>(); // Changed to private
The problem, then, is that your calling code has to say
Number n = new Number(15); // Or whatever number you're calling it with
so every time you call it, it gets a fresh copy of Number and your Set is gone.
So instead, make your calling code only create one Number(), but have a new method in Number that looks like:
public void setNumber(int n){
number = n;
}
Then every time you want to call number, you can call
number.setNumber(5);
number.isBoolean();
the original post, contained some misunderstandings.. here is a suggested fix:
public class Number
{
public static HashSet<Integer> pSet;
static
{
pSet = new HashSet<>();
pSet.add(2);
}
public static boolean isPrime(int n)
{
boolean out = true;
if (n == 1) { return true; }
if (pSet.contains(n)) { return true; }
for (int i = 2; i < n; i++)
{
if (n % i == 0) {
out = false;
break;
}
}
if (out) { pSet.add(n); }
return out;
}
}
in my opinion 'isPrime' method should be static.. there is no point to create an instance of a class just to run a test over a number
the role of pSet (as declared by the submitter) is to hold a cache of previously tested prime numbers (so every number tested once)
I have a quick question out of curiosity...if I declare an integer in one method, for example: i = 1, is it possible for me to take that i and use its value in my main class (or another method)? The following code may be helpful in understanding what I'm asking...of course, the code might not be correct depending on what the answer is.
public class main {
public main() {
int n = 1;
System.out.print(n + i);
}
public number(){
i = 1;
}
}
No you cannot! Not unless you make it an instance variable!
Or actually send it to the function as an argument!
First, let's start simple. All methods that are not constructors require a return type. In other words,
public void number(){
i = 1;
}
would be more proper.
Second: the main method traditionally has a signature of public static void main(String[] args).
Now, on to your question at hand. Let's consider a few cases. I will be breaking a few common coding conventions to get my point across.
Case 1
public void number(){
i = 1;
}
As your code stands now, you will have a compile-time error because i is not ever declared. You could solve this by declaring this somewhere in the class. To access this variable, you will need an object of type Main, which would make your class look like this:
public class Main {
int i;
public static void main(String[] args) {
Main myMain = new Main();
myMain.number();
System.out.print(myMain.i);
}
public void number(){
i = 1;
}
}
Case 2
Let's say you don't want to make i a class variable. You just want it to be a value returned by the function. Your code would then look like this:
public class Main {
public static void main(String[] args) {
Main myMain = new Main();
System.out.print(myMain.number());
}
public int number(){ //the int here means we are returning an int
i = 1;
return i;
}
}
Case 3
Both of the previous cases will print out 1 as their output. But let's try something different.
public class Main {
int i = 0;
public static void main(String[] args) {
Main myMain = new Main();
myMain.number();
System.out.print(myMain.i);
}
public void number(){
int i = 1;
}
}
What do you think the output would be in this case? It's not 1! In this case, our output is 0. Why?
The statement int i = 1; in number(), it creates a new variable, also referred to as i, in the scope of number(). As soon as number() finishes, that variable is wiped out. The original i, declared right under public class Main has not changed. Thus, when we print out myMain.i, its value is 0.
Case 4
One more case, just for fun:
public class Main {
int i = 0;
public static void main(String[] args) {
Main myMain = new Main();
System.out.print(myMain.number());
System.out.print(myMain.i);
}
public int number(){
int i = 1;
return i;
}
}
What will the output of this be? It's 10. Why you ask? Because the i returned by number() is the i in the scope of number() and has a value of 1. myMain's i, however, remains unchanged as in Case 3.
You may use a class-scope field to store you variable in a class object or you can return it from one method or pass it as a parameter to the other. Mind that you will need to call your methods in the right order, which is not the best design possible.
public class main {
int n;
int i;
public main() {
n = 1;
System.out.print(n + i);
}
public number(){
i = 1;
}
}
Yes, create a classmember:
public class Main
{
private int i;
public main() {
int n = 1;
System.out.print(n + i);
number();
System.out.print(n + i);
}
public number(){
i = 1;
}
}
void method(){
int i = 0; //has only method scope and cannot be used outside it
}
void method1(){
i = 1; //cannot do this
}
This is because the scope of i is limited to the method it is declared in.