I am trying to write a Java function based off of the following question:
Write a program called CheckPassFail which prints "PASS" if the int variable "mark" is more than or equal to 50; or prints "FAIL" otherwise. The program shall always print “DONE” before exiting.
This is what I have so far:
import java.util.*;
import java.lang.*;
import java.io.*;
class CheckPassFail(){
int m;
public void GetGrade(int mark){
m = mark;
}
public void GradeCheck(int mark){
if(mark >= 50){
system.out.println("Pass");
}
else{
system.out.println("Fail");
}
public static void main(String[] args){
CheckPassFail grade = new GetGrade(66);
grade.GradeCheck(66);
}
}
I believe my issue has to do with the GetGrade class? I feel as if setting m = mark is unnecessary for this program. Please let me know if you see any other errors. Thank you.
Critical problems (these are preventing your program from compiling):
Your code is missing the closing brace } in the GradeCheck method.
There must not be parenthesis in class declarations, as in class CheckPassFail {
Java is case-sensitive. You must use System, not system, as in System.out.println();
Technical explanation: System refers to the builtin class java.lang.System. All java.lang classes are automatically available without you needing to import them.
GradeCheck is a method, not a class. You cannot create a new instance of it, or use the new operator with it, as you did with new GetGrade(66);
Non-critical (but nevertheless important) problems:
You seem to think that GetGrade is a constructor. It is not. That is not how constructors work. That is not how classes work. That is not how Java works.
The variable m is declared and assigned to, but never used.
Your program does not print "DONE" after executing, which was a requirement.
All of your imports are unused. You should not import extraneous packages.
The class CheckPassFail should be public. Most Java classes should be public.
Your indentation is inconsistent and makes your code less readable.
Cleaned-up version of your code:
public class CheckPassFail {
public int mark;
public CheckPassFail(int mark) {
this.mark = mark;
}
public void checkGrade() {
if(mark >= 50) {
System.out.println("PASS");
} else {
System.out.println("FAIL");
}
}
public static void main(String[] args) {
CheckPassFail checker = new CheckPassFail(66);
checker.checkGrade();
System.out.println("DONE");
}
}
GetGrade is not a class, it's a function. Therefore, it should be called without the 'new' keyword.
Class declaration syntax is wrong, there shouldn't be any parenthesis.
Considering what GradeCheck function is doing, GetGrade function is useless (unless you need it somewhere else).
'system' should be 'System' (in-built class from java.lang package).
Class names should start with upper-case letters and function names should start with lower-case letters (standard).
class CheckPassFail {
public void gradeCheck(int mark) {
if(mark >= 50) {
System.out.println("Pass");
}
else {
System.out.println("Fail");
}
}
public static void main(String[] args) {
CheckPassFail check = new CheckPassFail();
check.gradeCheck(66);
}
}
class CheckPassFail
{
int m;
CheckPassFail(int mark){
m = mark;
}
public void gradeCheck(int mark){
if(mark >= 50){
System.out.println("Pass");
}
else{
System.out.println("Fail");
}}
public static void main(String[] args) {
CheckPassFail grade = new CheckPassFail(66);
grade.gradeCheck(66);
}}
class CheckPassFail {
public void gradeCheck(int mark) {
if(mark >= 50) {
System.out.println("Pass");
}
else {
System.out.println("Fail");
}
}
public static void main(String[] args) {
CheckPassFail grade = new CheckPassFail();
grade.gradeCheck(66);
}
}
Related
I am new to coding and I am trying to figure out how to call a method from a separate class and use it in my main class. I know that it is easier to do it in the main class but I was asked to do it in a separate class. The random number that is printed to range from 1 to 3 but using this method I just get 0.
here's the main class:
package example;
public class Example {
public static int number;
public static void main(String[] args) {
otherClass a = new otherClass();
a.assignNumber();
System.out.println(number);
}
}
and my separate class:
package example;
import java.util.Random;
public class otherClass {
public int assignNumber(){
Random num = new Random();
int number = num.nextInt(4) + 1;
return number;
}
}
Default value of number variable is 0 since its type is int. You need to assign the return value of function to number variable.
package example;
public class Example {
public static void main(String[] args) {
otherClass a = new otherClass();
int number = a.assignNumber();
System.out.println(number);
// Or
System.out.println(a.assignNumber());
}
}
The number variable in 'Example' class differs from the number in 'otherClass'.
The easiest way to fix your code is to fix the assignment part:
number = a.assignNumber();
But you should probably check your code again: It is better to use local int variable instead of static field.
package example;
public class Example {
public static void main(String[] args) {
otherClass a = new otherClass();
int number = a.assignNumber();
System.out.println(number);
}
}
There is no real use for the number variable.
It can all be condensed to
package example;
public class Example {
public static void main(String[] args) {
System.out.println(new otherClass().assignNumber());
}
}
I was trying to develop some code using TDD, but stumbled on a weird behavior: setUp and tearDown doesn't seem to be "cleaning up" after each test is executed. I expected each test (marked with #Test annotation) to be executed at a random order, one after the other, without influencing each other. With that in mind, I don't understand what is happening as it seems like one specific test (testaSomarMao) is influencing another specific test (testaSplit). The testaSplit test is failling on the first assert: I expected value 6, but I'm getting 9. Anybody can explain me what is going on?
JogadorTest.java
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class JogadorTest{
private static Jogador p1;
public JogadorTest(){
}
#Before
public void setUp(){
p1 = new Jogador();
}
#After
public void tearDown(){
p1 = null;
}
#Test
public void testaGetNome(){
assertEquals(null, p1.getNome());
}
#Test
public void testaGetPontos(){
assertEquals(0, p1.getPontos());
}
#Test
public void testaSetNome(){
p1.setNome("Lucas");
assertEquals("Lucas", p1.getNome());
}
#Test
public void testaSomarMao(){
p1.comprarCarta(1);
assertEquals(3, p1.somarMao(1));
}
#Test
public void testaSplit(){
p1.comprarCarta(1);
p1.comprarCarta(1);
assertEquals(6, p1.somarMao(1));
p1.split();
assertEquals(p1.somarMao(1), p1.somarMao(2));
}
}
Jogador.java
public class Jogador {
private static String nome;
private int pontos;
private static int mao[] = new int[13];
private static int mao2[] = new int[13];
public void parar() {
}
public void setNome(String novoNome){
nome = novoNome;
}
public static int getPontos() {
return 0;
}
public static void split() {
//Usamos mao2 para garantir que soh ocorra um split.
if(mao[0] == mao[1] && mao2[0] == 0){
mao2[0] = mao[1];
mao[1] = 0;
}
}
public void fecharJogo() {
}
public String getNome() {
return nome;
}
public static int somarMao(int maoEscolhida){
int soma = 0;
int cartasNaMao[];
if(maoEscolhida == 2)
cartasNaMao = mao2;
else
cartasNaMao = mao;
for(int i = 0; i < cartasNaMao.length; i++)
soma += cartasNaMao[i];
return soma;
}
public static void comprarCarta(int maoEscolhida){
int carta = 3; // random futuramente
int cartasNaMao[];
if(maoEscolhida == 2)
cartasNaMao = mao2;
else
cartasNaMao = mao;
for(int i = 0; i < cartasNaMao.length; i++){
if(cartasNaMao[i] == 0) {
cartasNaMao[i] = carta;
break;
}
}
}
}
The underlying reason for your problem is, as pointed out by Thevenin, the use of static variables for mao[] and mao2[]
You will also need to remove static from methods comprarCarta and somarMao. You will not need it after all variables referenced inside are not static anymore. From the test it is obvious you are not using them in the way static methods are invoked usually, i.e Jogador.comprarCarta(1) instead of p1.comprarCarta(1).
My guess is you created those methods static and compiler then complained that your variables are not static and cannot be accessed, so you changed the variables as well.
Actually the use of static will cause you issues with other parts of your program as well - you better change nome variable to not be static. Same applies for getPontos() method - if you try to return pontos there instead of 0 you will get a compiler error that pontos is not static.
As you are confusing the use static in general take a look at this great explanation of what is static, when you have the time :)
Static variables - what are they?
In comprarCarta() you are modifying mao or mao2 which are static arrays. Any changes you make to these arrays will persist across all instances of Jogador.
Since this is not what you expect I suspect that you may not want these to be static.
I am just trying to create an example program to help me remember how to operate for loops, when I ran it through the compiler. The Compiler said missing return statement. Where do I add it?
Here is the code:
public class LoopExample {
public String bam() {
for (int i = 0; i < 8; i++) {
System.out.println(i);
}
}
}
EDIT
I received an answer, but now the main says 'cannot find symbol'... here is the code for the main:
public class LoopExampleTestDrive {
public static void main(String[] args) {
bam looper = new bam();
System.out.println(looper);
}
}
I would advise you to try to understand how Object Oriented languages work first.
That being said, the main reason why your code doesn't work, is because you try to make an object of the class bam with new bam(). This class unfortunately doesn't exist as it is only a method in a class. My solution would look like:
public class LoopExample {
public void bam() {
for (int i = 0; i < 8; i++) {
System.out.println(i);
}
}
public static void main(String[] args) {
new LoopExample().bam();
}
}
As I said: try to understand object oriented programming first, before trying to continue programming in Java. It is too essential to be able to write working code.
PS: just to be complete, the best way to write what you want to do, would look as follows.
public class LoopExample {
public static void main(String[] args) {
for(int i = 0; i < 8; i++) {
System.out.println(i);
}
}
}
Change the signature of your method. Replace public String bam() with public void bam(). voidmeans that you return nothing instead of a String as before.
For further information see http://www.tutorialspoint.com/java/java_methods.htm
I have a main class called Main.java and the other class called Movements.java
I tried calling upon a method from the Movements.java into the Main.java but it was not what I expected.
Main.java:
package game;
public class Main {
Movements shift = new Movements();
public void main String(String[] args) {
while (true){
//body here//
}
}
public static void startProgram {
//body here//
}
public static int variableName {
//body here//
}
public static boolean isInputValid {
//body here//
}
public Chess(){
shift.analyzeInput();
shift.makeTurn();
}
}
Movements.java:
package game;
public class Movements {
public static void analyzeInput(String info){
StringTokenizer token = null;
EasyWriter show = new EasyWriter();
int tally = 0;
info = info.toLowerCase();
info = info.trim();
String[] array = new String[100];
token = new StringTokenizer(info);
while (token.hasMoreTokens()) {
array[tally] = token.nextToken();
tally++;
}
if (tally > 0 && tally < 4){
if (tally == 1){
if (array[0].equals("resign")){
if (Main.timeForWhitePlayer){
show.println("Black wins");
System.exit(1);
}else{
show.println("White wins");
System.exit(1);
}
}else if (array[0].equals("draw")){
if (Main.drawRequest == true){
show.println("It's a draw");
System.exit(1);
}else{
show.println("You must ask the opponent if they are willing to call the game a draw first.");
}
}else{
show.println("Invalid input. Please try again. ");
}
}else if (tally == 2) {
Main.presentPosition = array[0];
Main.nextPosition = array[1];
if (Main.presentPosition.length() == 2 && Main.nextPosition.length() == 2 ){
makeTurn();
}else{
show.println("Invalid input. Please try again.");
}
}
Main.presentPosition = null;
Main.nextPosition = null;
Main.thirdArgument = null;
}
public static void makeTurn() {
//body in here//
}
}
I'm using Eclipse IDE and it states that Syntax error on token "makeTurn", Identifier expected after this token. Have I done something wrong?
You don't need to create an instance since the method is static. You can simply call Movements.makeTurn(). And also I guess you meant to change Movements mv = new Move(); to Movements mv = new Movements(); if you do not have a Move class. If you do, then it must extend the type Movements
My guess, you're calling shift.makeTurn(); outside of any method or constructor, naked in the class. If so, you can't do that as you must make method calls that don't initialize a variable within a method or constructor or some similar block (static initializer block for instance).
For instance, to simplify, assuming you have a Movements class like so:
public class Movements {
// looks like this should not be static
public void makeTurn() {
}
}
and a Main class like so:
public class Main {
Movements shift = new Movements();
shift.makeTurn(); // you can't call this here!
public Main() {
shift.makeTurn(); // but you can do it here!
}
public static void main(String[] args) {
Movements shift = new Movements();
shift.makeTurn(); // or you can do it here!
}
}
Edit: my assumption was correct -- you're making method calls outside of any method or constructor and the solution is simple: don't do that. Put those calls in whatever method or constructor they belong.
Other issues:
Your code has static overload -- overuse of the static modifier, making it a non-OOP program.
You're making way too many direct references of one class's fields in another, and this leads to code with lots of connections (called highly coupled code). This can lead to very hard to debug errors.
Don't name your class Main. It's confusing. main is what we call the method we use as the program entry point.
shift.makeTurn() is not within any method, constructor, or initialiser so you need to move it. You also need to decide if makeTurn() needs access to any properties that will be different in different instances of Movements (you called one shift). If so you can't make it static.
If you want to call using
shift.makeTurn();
then turn this:
public static void makeTurn() {
into this:
public void makeTurn() {
Otherwise do what #TameHog told you to do.
A static method isn't bound to an instance like shift. It's bound to a class like Movements. It's all about what makeTurn() needs access to. Though non static is considered more flexable. If you understand that you should be able to decide which to do on your own.
You cannot call methods within the class definition. Instead you must call the method within a method or initializer.
Using a method
package game;
public class Main {
public void main String(String[] args) {
shift.makeTurn();
while (true){
//body here//
}
}
public static void startProgram {
//body here//
}
public static int variableName {
//body here//
}
public static boolean isInputValid {
//body here//
}
Movements shift = new Movements();
}
Or, with the instantiation in the function,
package game;
public class Main {
public void main String(String[] args) {
Movements shift = new Movements();
shift.makeTurn();
while (true){
//body here//
}
}
public static void startProgram {
//body here//
}
public static int variableName {
//body here//
}
public static boolean isInputValid {
//body here//
}
}
Or with an initialiser
package game;
public class Main {
public void main String(String[] args) {
while (true){
//body here//
}
}
public static void startProgram {
//body here//
}
public static int variableName {
//body here//
}
public static boolean isInputValid {
//body here//
}
Movements shift = new Movements();
{ shift.makeTurn();}
}
I have problem writing a testcase to this method below: EvenNum(double)
public class OddEven {
/**
* #param args
*/
public boolean evenNum(double num)
{
if(num%2 == 0)
{
System.out.print(true);
return true;
}
else
{
System.out.print(false);
return false;
}
}
This is the testcase I wrote but I think I have an inheritance problem or a logical problem in this test case. Should be a very simple one but can't figure out. Here is the code I wrote:
import static org.junit.Assert.*;
import org.junit.Test;
public class OddEvenTest {
#Test
public void testEvenNum() {
boolean ans = true;
boolean val;
double num= 6;
val = OddEven.EvenNum(num) // cant inherit the method dont know why???
assertEquals(ans,val);
}
}
You have a number of issues:
you are attempting to call a non-static method statically
method names in java are case sensitive and you've mixed up the case.
I corrected some things for you and just verified the code below:
OddEven.java:
public class OddEven {
public boolean evenNum(double num)
{
if(num%2 == 0)
{
System.out.print(true);
return true;
}
else
{
System.out.print(false);
return false;
}
}
}
OddEvenTest.java
import static org.junit.Assert.*;
import org.junit.Test;
public class OddEvenTest {
#Test
public void testEvenNum() {
boolean ans = true;
boolean val;
double num = 6;
OddEven oddEven = new OddEven();
val = oddEven.evenNum(num);
assertEquals(ans,val);
}
}
Assuming the calls to System.out.println() in OddEven are strictly for debugging, the whole thing could be collapsed down to:
OddEven.java
public class OddEven {
public boolean evenNum(double num) {
return num%2 == 0;
}
}
OddEvenTest.java
import static org.junit.Assert.*;
import org.junit.Test;
public class OddEvenTest {
#Test
public void testEvenNum() {
OddEven oddEven = new OddEven();
assertTrue(oddEven.evenNum(6));
assertFalse(oddEven.evenNum(5));
}
}
The code is now shorter and the unit test even covers an odd case for good measure.
Two things :
You are invoking a non-static method statically. The method should be declared static:
public static boolean evenNum(double num) {
}
You didn't type the name of the method correctly. Look closely. Also consider renaming it something more readable like, isEven(...)
This seems like testing gone mad to me, and programming gone mad too. All the method does is evaluate num % 2 == 0. You may as well just code that everywhere required and throw away both the method and its tests. If you must keep the method, it relies on a mathematical identity, you don't need to test those. You may as well test 1+1==2.