Using for loop increments in a method - java

I am trying to use a method to print a random number multiple times using increments. The problem is I don't seem to understand methods very well. I have no problem doing it otherwise but when I try to do it by calling a method I can't get any return and my console just remains blank. Here is what I have so far:
package WayBack;
import java.util.Random;
public class Review {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
{
method1();
}
public String method1()
{
String rv = "";
for(int i = 0; i <= 4; i++)
{
Random r = new Random();
int number = r.nextInt((100) - 0) * 100;
System.out.println("your number is " + number);
}
return rv;
}
}
Any help would be much appreciated
Thank You

You need to invoke the method1 function in main. But your method1 function is an instance method. So you should new an Instance of the Review class, and then invoke the method1 function.
public static void main(String[] args) {
// TODO Auto-generated method stub
Review instance = new Review();
instance.method1();
}
Or, You can declare the method1 as static so that you can call it directly in the main method.
public static void main(String[] args) {
// TODO Auto-generated method stub
method1();
}
public static String method1()
{
String rv = "";
for(int i = 0; i <= 4; i++)
{
Random r = new Random();
int number = r.nextInt((100) - 0) * 100;
System.out.println("your number is " + number);
}
return rv;
}
An other way, you can invoke the method1 in the constructor of the Review class. And If you create an instance of a class, the methods in the constructor of the class are automatically called. In this way, you don't have necessary to invoke your method in the main.
public static void main(String[] args) {
// TODO Auto-generated method stub
Review instance = new Review(); // it will call the method1 automatically
}
public Review() {
// invoke your method
method1();
}

In your code, you are not calling the method method1. It is not wrapped in Main, instead it is wrapped in a set of floating curly braces.
package WayBack;
import java.util.Random;
public class Review {
public static void main(String[] args) {
method1(); // put it here
}
// This block is not executed
{
method1();
}
public String method1()
{
String rv = "";
for(int i = 0; i <= 4; i++)
{
Random r = new Random();
int number = r.nextInt((100) - 0) * 100;
System.out.println("your number is " + number);
} return rv;
}
}

As everyone is pointing out, you need to include method1() inside your main.
The reason for this is because Java starts all programs in public static void main(String[] args) from here it reads one line at a time inside the block of code. A block of code is defined as what is in the '{' and '}', often called braces.
Because the main method is ALWAYS static, and you cannot reference non-static things inside a static method, you will either need to change your method1 to also be static or create an object that can reference the method. You will learn about this later on.
For now,
public static void main(String[] args) {
method1();
}
public static String method1() {
String rv = "";
Random r = new Random(); //this 'r' object only needs to be created once.
for(int i = 0; i <= 4; i++)
{
int number = r.nextInt(100) * 100; // you were subtracting 0 for no reason?
System.out.println("your number is " + number);
rv = rv + number + ", "; //rv is empty in your example, this will fill it with the 5 numbers generated. (It's not perfect)
}
return rv;
}

Your rv variable return an empty value.
You can create a class(MyClass) where in future you can Add other methods:
For example you can do:
package WayBack;
import java.util.Random;
public class Review {
public static void main(String[] args) {
// TODO Auto-generated method stub
public MyClass work=new MyClass();
work.method1();
}
}
//---create an other file and write this one
Public Class MyClass{
private String rv;
private int number;
private Random r;
//constructor
public MyClass(){
this.number=0;
this.rv="";
this. r= new Random();
}
public String method1() {
for(int i = 0; i <= 4; i++) {
number = r.nextInt((100) - 0) * 100;
System.out.println("your number is "+number);
rv=rv+number+","; }
return rv; }
}//end MyClass

Since 'method1' is called in a block, this will execute at the time when you create the object.
{
method1();
}
You only have to create the object in the main method. No need to make method static.
Try this,
public static void main(String[] args) {
// TODO Auto-generated method stub
Review review = new Review();
}

Related

main method calling no-static method

I have read that a static method can't call a no-static method, but this compile, the main(static) method call maybeNew(no-static) method, can you give me a clue?
public class Mix4 {
int counter = 0;
public static void main(String[] args) {
int count = 0;
Mix4[] m4a = new Mix4[20];
int x = 0;
while (x<9) {
m4a[x] = new Mix4();
m4a[x].counter = m4a[x].counter + 1;
count = count + 1;
count = count + m4a[x].maybeNew(x);
x = x + 1;
}
System.out.println(count + " " + m4a[1].counter);
}
public int maybeNew(int index) {
if (index<5) {
Mix4 m4 = new Mix4();
m4.counter = m4.counter + 1;
return 1;
}
return 0;
}
}
You can not call a non-static method directly from a static method but you can always call a non-static method from a static method using an object of the class.
public class Main {
public static void main(String[] args) {
// sayHello(); // Compilation error as you are calling the non-static method directly from a static method
Main main = new Main();
main.sayHello();// OK as you are calling the non-static method from a static method using the object of the class
}
void sayHello() {
System.out.println("Hello");
}
}

Setters And Getters to different Class

My problem is that, simply I don't know what code to use to get my value from my getX method to my other classses main method.
package hangman;
public class Hangman {
private int triesLimit;
private String word;
public void setTriesLimit(int triesLimit) {
this.triesLimit = triesLimit;
}
public void setWord(String word) {
this.word = word;
}
public int getTriesLimit() {
return this.triesLimit;
}
public String getWord() {
return this.word;
}
#Override
public String toString() {
return ("Enter Secret Word " + this.getWord()
+ ".\nEnter max # of tries (Must be under 7) "
+ this.getTriesLimit());
}
}
Thats from the sub-class and I am trying to store the value of the triesLimit into the main of this classes main method
package hangman;
public class PlayHangman {
public static void main(String[] args) {
Hangman hangman = new Hangman();
Scanner scn = new Scanner(System.in);
int triesCount = 0;
int correctCount = 0;
hangman.toString();
int triesLimit = hangman.getTriesLimit();
String secretWord = hangman.getWord();
StringBuilder b = new StringBuilder(secretWord.length());
for (int i = 0; i < secretWord.length(); i++) {
b.append("*");
}
char[] secrectStrCharArr = secretWord.toCharArray();
int charCnt = secretWord.length();
for (int x = 0; triesCount < triesLimit; triesCount++) {
while (charCnt >= 0) {
System.out.println("Secrect Word :" + b.toString());
System.out.println("Guess a letter :");
char guessChar = scn.next().toCharArray()[0];
for (int i = 0; i < secrectStrCharArr.length; i++) {
if (guessChar == secrectStrCharArr[i]) {
b.setCharAt(i, guessChar);
correctCount++;
} else if (guessChar != secrectStrCharArr[i]) {
triesCount++;
System.out.println("Incorrect: " + triesCount);hangmanImage(triesCount,correctCount);
}
}
}
}
}
I tried looking it up on here but couldn't find setters and getters used in a sub/superclass
You need to create an instance of the class in the main method to access the variables and method available in that class like so
public class PlayHangman {
public static void main(String[] args) {
Hangman hangman = new Hangman();
hangman.setTriesLimit(2)
int value = hangman.getTriesLimit();
}
You can look into static keyword to access the value directly but that requires a bit more understanding of OOP's and JAVA.
This should work fine.
Hope it helps :)
EDITED
ToString method is just to convert everything in your model class to String which you have done correctly,but you have implemented incorrectly.... Change your ToString content so
#Override
public String toString() {
return ("The Secret Word you entered: " + this.getWord()
+ ".\n The max # of tries (Must be under 7): "
+ this.getTriesLimit());
}
You have initialized Scanner which does what you want, to ask the user to enter the values but again you haven't implemented it so add this to your main method
Scanner scn = new Scanner(System.in);
hangman.setTriesLimit(scn.nextInt());
hangman.setWord(scn.next());
hangman.toString()//Will work now
Trial and error is your best friend now :)
and Google some of the issues rather than waiting for an answer :)
Like rohit said, this is as simple as understand the basics of OOP, specific the encapsulation.
If you want to get a little deeper into OOP patterns, you could use the Observer pattern. This allows you to change the status of any class instance, even if they're not related by inheritance, aggregation, etc.
You can scale the solution by making List of Observer
Your observable interface
public interface IObservable {
// Set the observer
public void setObserver(IObserver iObserver);
// Notify the observer the current status
public void notifyObserver();
}
Your observer interface
public interface IObserver {
public void update(boolean status);
}
Your observer implementation
public class PlayHangman implements IObserver {
private boolean status = false;
public void printStatus() {
System.out.println("Status: " + (this.status ? "Win" : "Lose"));
}
#Override
public void update(boolean status) {
// The instance status is updated
this.status = status;
// Print the current status
this.printStatus();
}
}
Your observable implementation
public class Hangman implements IObservable{
private String goalWord = "";
private String currentWord = "";
private int triesLimit = 0;
private int tries = 0;
private IObserver iObserver;
public Hangman(String goalWord, int triesLimit) {
this.goalWord = goalWord;
this.triesLimit = triesLimit;
}
public void setCurrentWord(String currentWord) {
this.currentWord = currentWord;
this.notifyObserver();
}
public void addTry() {
this.tries++;
this.notifyObserver();
}
#Override
public void setObserver(IObserver iObserver) {
this.iObserver = iObserver;
}
#Override
public void notifyObserver() {
// True = win
this.iObserver.update(this.tries < this.triesLimit &&
this.goalWord.equals(this.currentWord));
}
}
Your Main class
public class Main{
public static void main(String[] args) {
// PlayHangman (game status)
PlayHangman playHangman = new PlayHangman();
// Hangman initializes with a goalWord and the triesLimit
Hangman hangman = new Hangman("HangmanJava", 5);
// Set the observer
hangman.setObserver(playHangman);
// During the game you just can set the current word and add a try
// You're not setting the status directly, that's the magic of the Observer pattern
hangman.setCurrentWord("Hang");
hangman.addTry();
hangman.setCurrentWord("HangmanJava");
}
}
Hope this helps and enjoy Java

While loop doesn't quit

i wrote a program in java wich compares tow variables values, X and Y.
when i enter the same number for X and Y in the first attempt of the loop it says Match and terminate. But if it returned "false" in the first loop and then returned "true" in the next it doesn't terminate and goes on as if "b" has a "false" value.
import java.util.Scanner;
public class clads {
//Variables
public static int y;
public static int x;
static boolean b = mymethod() ;
//MainProcess
public static boolean mymethod() {
Scanner myscanner = new Scanner(System.in);
System.out.println("put a number for X");
x = myscanner.nextInt();
System.out.print("put a number for Y");
y = myscanner.nextInt();
if (y==x){
System.out.println("match");
return true;
}else{
System.out.println("Mismatch, Redo");
return false;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
while(b ==false){
mymethod();
}
}
}
But when I added a "Break;" keyword it terminated whenever it returned a "true" value. can i have some explanation please.
public static void main(String[] args) {
// TODO Auto-generated method stub
while(b ==false){
mymethod();
Break;
}
When you initialize b by calling mymethod, it's set to either true or false forever. If it's true, your doesn't execute. If it's false, your loop executes forever.
Your mistake is in setting the value of b when b is declared. You actually don't need b at all. Just put the invocation of mymethod() inside the while condition:
import java.util.Scanner;
public class clads {
//Variables
public static int y;
public static int x;
//MainProcess
public static boolean mymethod() {
Scanner myscanner = new Scanner(System.in);
System.out.println("put a number for X");
x = myscanner.nextInt();
System.out.print("put a number for Y");
y = myscanner.nextInt();
if (y==x){
System.out.println("match");
return true;
}else{
System.out.println("Mismatch, Redo");
return false;
}
}
public static void main(String[] args) {
while(!mymethod());
}
}
You have to check the return value from mymethod() every time it's invoked. Your original code just caught the first value and used it forever.
Because your variable initialize once and then never get updated. try:
public static void main(String[] args) {
while(!b){
b = mymethod();
}
}
you can modify the code as follows below
public static void main(String[] args) {
// TODO Auto-generated method stub
while(b ==false){
if (mymethod()) {
break;
}
}
if the function mymethod() returns true, the while loop will terminate, but when the function returns false, the while will continue.

How to use the the count number somewhere else in java

Is there anyway in which I can place count into a variable. E.g. I have Count to count the number of lines. After that I want to use the number that the count has provided, and then add this number in a variable that can be used somewhere else, e.g. to add with another number, or find an percentage or to create a pie chart using the number.
public void TotalCount12() throws FileNotFoundException {
Scanner file = new Scanner(new File("read.txt"));
int count = 0;
while(file.hasNext()){
count++;
file.nextLine();
}
System.out.println(count);
file.close();
I want to use the number that I will get in count, and use it somewhere else (e.g another method), but I have no idea how to do that.
Thank you.
Firstly I recommend that you should complete this javatutorial if you new to programming.
If you define it in class as a global variable(as an attribute of class) out of method, you can use it in every method in your class.
But if your question about to using it in everywhere of the project within different class, you can use singleton design pattern;
public class ClassicSingleton {
private static ClassicSingleton instance = null;
protected ClassicSingleton() {
// Exists only to defeat instantiation.
}
public static ClassicSingleton getInstance() {
if(instance == null)
{
instance = new ClassicSingleton();
}
return instance;
}
}
EDIT
Make a getter method for count variable.
E.g.
public class Test {
private int count = 0;
public void method1(){
while(file.hasNext()){
count++;
file.nextLine();
}
System.out.println(count);
}
public void method2(){
System.out.println(count);
}
public int getCount(){
return count;
}
}
Just return the value in the method you created:
public class Test {
public int TotalCount12() throws FileNotFoundException {
Scanner file = new Scanner(new File("read.txt"));
int count = 0;
while(file.hasNext()) {
count++;
file.nextLine();
}
System.out.println(count);
file.close();
return count;
}
public static void main(String[] args) {
Test t = new Test();
int testCount = TotalCount12();
}
}

Java 'this' keyword

I'm just beginning in programming and I'd like to make exercise from a book, but I can't. That's my problem:
public class increment {
int increment() {
return this + 1; // aka this++
}
public static void main(String[] args) {
int a = 0;
System.out.println(a.increment());
}
}
As you for sure guessed already, that it doesn't works, I want to ask you how to get outputed integer a incremented by one, but using keyword 'this'.
Regards and sorry for stupid questions.
It is strange to name a class like a method.
I guess you wanted this:
public class Counter {
int val;
public Counter (int start) {
val = start;
}
public void increment() {
val ++;
}
public String toString () {
return Integer.toString (val);
}
public static void main(String[] args) {
Counter counter = new Counter (0);
counter.increment ();
System.out.println(counter.toString ());
}
}
this is an object (the current object). You cannot "increment" it.
A way to do it is:
public class Increment {
int a = 0;
int increment() {
return a + 1;
// or: return this.a + 1;
// or: a++; return a; if you want a to be incremented from now on
}
public static void main(String[] args) {
Increment inc = new Increment();
System.out.println(inc.increment());
}
}
The this keyword in Java refers to the current scope's object instance. I don't think it's what you're looking for in this case.
In your example, a isn't an object of the class increment, it is a primitive int. In order to use the .increment() function you defined, it would have to be an object of type increment.
One option that may be what you're looking for would be the following.
public class Increment { //Java likes capitalized class names
private int myInt;
public Increment(int a) { //constructor
myInt = a;
}
public int increment() {
return ++myInt;
}
public static void main(String[] args) {
Increment a = new Increment(0);
System.out.println(a.increment());
}
}
In this example, we make a new class of type increment, which internally contains an integer. Its increment method increments that internal integer, and then returns the number.
you are using operator + for your current object (this). Operator overloading is not supported in java.
Something like this will work:
class MyInteger {
private int internal;
public MyInteger( int value ){
this.internal = value;
}
public int incerment(){
return ++this.internal;
}
}
public class Increment {
public static void main(String[] args) {
MyInteger a = new MyInteger(0);
System.out.println(a.increment());
}
}
You see, you can only implement methods for your own classes, not for existing classes, or for primitives like int.
i don't think you can use this to return the value, except if you're making a new class like this:
class Increment1
{
private int a;
public int increment2(int a)
{
this.a=a;
return this.a + 1;
}
}
public class Increment
{
static Increment1 b = new Increment1();
public static void main(String[] args)
{
int a = 0;
System.out.println(b.increment2(a));
}
}
You cannot increment a class like this.
You have to use a member variable that you can increment.
public class Test {
private int var;
public Test(int i) {
this.var = i;
}
int increment() {
this.var++;
}
}
public static void main(String[] args) {
Test t = new Test(0);
System.out.println(t.increment());
}
This refers to the current instance of the class, not a particular member.
You want to increment a property (I'm guessing of type long or int), and not the instance of your increment class (should be Increment, by the way).
Something like this would work:
public class increment {
private int innerValue = 0;
int increment() {
innerValue+=1
return innerValue; // aka this++
}
public static void main(String[] args) {
increment a = new increment()
System.out.println(a.increment());
}
}

Categories

Resources