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.
Related
I have a little difficulty understanding how the static block works
import java.io.*;
import java.util.*;
public class Solution {
static {
Scanner sc = new Scanner(System.in);
int B = sc.nextInt();
int H = sc.nextInt();
boolean flag= false;
if(B<=0 || H<=0){
flag= false;
System.out.println("java.lang.Exception: Breath and Hieght must be positive");
}
}
public static void main(String[] args){
if(flag){
int area=B*H;
System.out.print(area);
}
}
}
when I try to run it says cannot find symbol flag, B, H. Can anyone explain why?
The scope of the variable is within static block or any block for that matter. You should declare it outside the block and define it inside ur static block.
All the variables in your static block will be detroyed at the end of the execution of the block. To prevent this, you could declare those variables as fields like this
import java.io.*;
import java.util.*;
public class Solution {
private static int B;
private static int H;
private static boolean flag;
static {
Scanner sc = new Scanner(System.in);
B = sc.nextInt();
H = sc.nextInt();
flag = false;
if(B<=0 || H<=0){
flag= false;
System.out.println("java.lang.Exception: Breath and Hieght must be positive");
}
}
public static void main(String[] args){
if(flag){
int area=B*H;
System.out.print(area);
}
}
}
You should declare static variables outside the static code block.
I'm a bit new to java and i recently learned about methods(so cool!). I want to know if its possible to declare a variable in my main method and use it in my other methods.
What i am trying to do is create a calculator using methods(just for practice with this new concept) but i dont want to declare the variable every time in each method.
Here is the skeletal structure of the code:
class GS1{
public static void main (String[]args){
Scanner input = new Scanner(System.in);
System.out.println("Enter the math operation to be completed: ");
String opt = input.nextLine();
int x,y; // I tried declaring variables here
switch(opt){
case "addition" :
// addition method goes here
break;
case "subtraction":
//subtraction method goes here
break;
case "multiplication":
//multiplication method goes here
break;
case "division":
//division method goes here
break;
}
}
static void addition(){
System.out.println("Enter first value for addition");
x=input.nextint(); // i get error stating both "x" and "input" cannot be resolved as a variable
}
static void subtration(){
}
static void Multiplication(){
}
static void Division(){
}
}
You should place the variable outside of all methods but within the class, creating global access.
public class ClassName
{
public int x;
public int y;
public void method1()
{
x = 3;
}
public void method2()
{
y = 1;
}
}
Move the variable at class level, make it a field in the class.
Since you're learning, it will be better to not use static fields nor methods except for the main method.
Organize better your code, make something like the following code:
class Operation {
public double addition(double... value) {
double result = 0;
for (double i : value) {
result += i;
}
return result;
}
public double subtration(.....) {
// .........................
return 0.0;
}
public double multiplication(.....) {
// .........................
return 0.0;
}
public double division(.....) {
// .........................
return 0.0;
}
}
public class GS1 {
public static void main(String[] args) {
Operation operations=new Operation();
//read value code
double result=operations.addition(value);
//print result code
}
}
You need something like this:
class GS1 {
public static int x;
public static Scanner input;
public static void main(String[] args) {
input = new Scanner(System.in);
System.out.println("Enter the math operation to be completed: ");
String opt = input.nextLine();
int x, y; // I tried declaring variables here
switch(opt){
case "addition" :
// addition method goes here
break;
case "subtraction":
//subtraction method goes here
break;
case "multiplication":
//multiplication method goes here
break;
case "division":
//division method goes here
break;
}
}
static void addition() {
System.out.println("Enter first value for addition");
x=input.nextint(); // i get error stating both "x" and "input" cannot
// be resolved as a variable
}
static void subtration() {
}
static void Multiplication() {
}
static void Division() {
}
}
Remember to use "static" modifier in your field declaration (x and input), you cannot make a static reference to a non static field.
A better way would be using objects instead of put all your methods in a single class (GS1). For example, create a Calculator class like Marged suggest in your comments
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();
}
import java.util.*;
public class ValidatePercent {
Scanner k = new Scanner(System.in);
boolean val = false;
int pc;
while (!val)
{
System.out.print("please input a percentage");
pc=k.nextInt();
if (pc>=0 && pc<=100){
val = true;
}
}
}
I get an error at line 6 "illegal start of type // cannot find symbol // symbol: class val // location: class ValidatePercent // expected"
What does it mean? Why doesn't it work?
I have tried changing it to loop while pc is a value and then it doesn't recognise that either.
You need to put these inside a method or a block.
Simply use main()
public class ValidatePercent {
public static void main(String[] args) {
Scanner k = new Scanner(System.in);
boolean val = false;
int pc;
while (!val)
{
System.out.print("please input a percentage");
pc=k.nextInt();
if (pc>=0 && pc<=100){
val = true;
}
}
}
}
You can't use while, System.out.print() and if outside a method or a block
You need to put your code into a method, like main. Main method is the one from which Java starts execution.
Here is the fixed code:
import java.util.*;
public class ValidatePercent {
public static void main(String[] args)
{
Scanner k = new Scanner(System.in);
boolean val = false;
int pc;
while (!val)
{
System.out.print("please input a percentage");
pc=k.nextInt();
if (pc>=0 && pc<=100){
val = true;
}
}
}
}
isnt the ternary operator suppose to work as arg ? true:false ??? so if duration and petroleum are more than the stated amount than field variables, it should return true.. but this returns false instead
public class test12 {
int duration = 260;
int petroleum = 300;
boolean result;
public void checktrain(){
boolean result = duration>=250 && petroleum>=235? true : false;
this.result = result;
}
public void run(){
System.out.print(result);
}
public static void main(String args[]){
test12 tr = new test12();
tr.run();
}
}
Result is false because you have never called the method checktrain and default value of member variable result is false.
You forgot to call checktrain().So as it remains with default value false of boolean.
Try to call that method.
public static void main(String args[]){
test12 tr = new test12();
tr.checktrian();
tr.run();
}
And check train method can be written simply as
public void checktrain(){
this.result= duration>=250 && petroleum>=235;
}
And even you can avoid that boolean by writing
public boolean checktrain(){
return duration>=250 && petroleum>=235;
}