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.
Related
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.
I'm relatively new to Java here, and I'm exploring custom methods. I've coded a program where the user enters a string and it gets reversed. I'm trying to add another method to it to check if it's a palindrome(the same backwards and forwards like racecar). Is it possible to call a custom method on a custom method then run in in the main?
import java.util.Scanner;
public class Done {
public static String palindrome(String pal) {
if (rev.equals(string)) {
System.out.println("This string is a palindrome!");
return string;
}
}
public static String reverse(String string) {
String rev = "";
for (int i = 0; i < string.length(); i++) {
rev = rev + (string.charAt(string.length() - (i + 1)));
}
System.out.println("Reversed String:");
System.out.println(rev);
palindrome(rev);
return rev;
}
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("REVERSATRON 2000");
System.out.println();
System.out.println("Enter string to reverse: ");
reverse(scanner.nextLine());
}
}
Thanks for the help!
Methods can call as many methods as you want, and those methods can call even more methods. In fact, methods can even call themselves. I looked through your code and cleaned up some errors: this should work
import java.util.Scanner;
public class Done {
public static void palindrome(String s, String rev) {
if (rev.equals(s)) {
System.out.println("This string is a palindrome!");
}
}
public static void reverse(String s) {
String rev = "";
for (int i = 0; i < s.length(); i++) {
rev = rev + s.charAt(s.length() - (i + 1));
}
System.out.println("Reversed String:");
System.out.println(rev);
palindrome(s, rev);
}
public static void main(String[] args) {
System.out.println("REVERSATRON 2000");
System.out.println();
System.out.println("Enter string to reverse: ");
Scanner scanner = new Scanner(System.in);
reverse(scanner.nextLine());
}
}
Yes!
Methods are very helpful to break code down into segments. Calling methods within methods is very common as well. Infact, you've probably done it without realizing.
public static void main(String args[]){
...
}
Is a method. So if you call a method within it, you are doing just that.
Additionally, you can use a method within itself (this is called recursion).
I've just started with Java, and so far been only playing around solving problems online, where you're not supposed to write the whole functional of a program, but only adjust a few lines of code to the already organized code.
However, I'm still struggling to organize my code in a compiling program in IntelliJ Idea, getting confused at,e.g. how methods invocations must be properly written.
Here's what I'm getting stuck with: an example from codingbat.com:
- Given a string, return a new string made of every other char starting with the first, so "Hello" yields "Hlo".
I've come up with a solution online, but now I wanna run it in Idea, with main method, with Scanner/BufferedReader input from console etc. Looks like I'm missing something...
import java.util.Scanner;
public class Bat
{
public static void main (String[] args) {
Scanner scanner = new Scanner(System.in);
String str = scanner.nextLine();
printString();
}
public String stringBits(String str) {
String result = "";
for (int i = 0; i<str.length();i += 2) {
result += str.substring(i, i+1);
}
return result;
}
public static void printString () {
System.out.println(result);
}
}
I ask your help to solve it out. What to do to make it:
Read a word from a console;
create a new string;
print it out.
Two alternatives:
make stringBits static
create an instance of the class Bat and invoke the member method
First solution - easy, not much to change
import java.util.Scanner;
public class Bat {
public static void main (String[] args) {
Scanner scanner = new Scanner(System.in);
String str = scanner.nextLine();
printString(stringBits(str));
}
public static String stringBits(String str) {
String result = "";
for (int i = 0; i < str.length();i += 2) {
result += str.substring(i, i + 1);
}
return result;
}
public static void printString (String string) {
System.out.println(string);
}
}
Second solution - a bit more advances
import java.util.Scanner;
public class Bat {
private String string;
public Bat(String string) {
this.string = string;
}
public static void main (String[] args) {
Scanner scanner = new Scanner(System.in);
String str = scanner.nextLine();
Bat bat = new Bat(str);
bat.printStringBits();
}
private String stringBits() {
String result = "";
for (int i = 0; i < string.length(); i += 2) {
result += string.substring(i, i + 1);
}
return result;
}
public void printStringBits() {
System.out.println(stringBits());
}
}
Your result variable is only accessible from within the "stringBits" method. Since the method returns a string you can do the following to print it:
System.out.println(stringBits(string)); //Call in main method in place of printString();
Edited: My code wasn't a working example. Note that stringBits has to be a static method in order to work.
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 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.