Why am I not getting any values back? - java

When running the below method, I do not get anything back. Always getting terminated without any results. Could someone tell me why I am not getting any results back?
I hava adjusted according to the comments but havent worked. I have add the main method below;
public class ModuleGrader {
final int examID = 123;
String excellent =null;
String good=null;
String satisfactory=null;
String compensatableFail=null;
String outrightFail=null;
int grade;
public String gradeModule(int mark) {
String result = null;
if (mark>=70 && mark<=100)
{
result = excellent;
System.out.println(" ");
}
else if (mark>=60 && mark<=69)
{
result = good;
}
else if (mark>=50 && mark<=59)
{
result = satisfactory;
}
else if (mark>=40 && mark<=49)
{
result = compensatableFail;
}
else if (mark>=0 && mark<=39) {
result = outrightFail;
}
else {
System.out.println("Invalid entery, please insert an number between 100-0");
}
return result;
}
So I have add my invoking main method;
the method to call maybe the problem?
public static void main(String[] args) {
ModuleGrader mg=new ModuleGrader();
mg.gradeModule(100);
mg.gradeModule(66);}

You have assigned no values to String excellent;, String good;, so it fails because those values have not been initialized to anything when you call them.
How would you know that it is not working? You have no output of the final result to the console. I added System.out.println() to correct that.
You can't reference something which is not static from something which is static. Change public class ModuleGrader to public static class ModuleGrader.
Final Working Code
public class Main {
public static void main(String[] args) {
ModuleGrader mg=new ModuleGrader();
System.out.println(mg.gradeModule(100));
System.out.println(mg.gradeModule(66));
}
public static class ModuleGrader {
final int examID = 123;
String excellent = null;
String good = null;
String satisfactory = null;
String compensatableFail = null;
String outrightFail = null;
int grade;
public String gradeModule(int mark) {
String result = null;
if (mark >= 70 && mark <= 100) {
result = excellent;
System.out.println(" ");
} else if (mark >= 60 && mark <= 69) {
result = good;
} else if (mark >= 50 && mark <= 59) {
result = satisfactory;
} else if (mark >= 40 && mark <= 49) {
result = compensatableFail;
} else if (mark >= 0 && mark <= 39) {
result = outrightFail;
} else {
System.out.println("Invalid entery, please insert an number between 100-0");
}
return result;
}
}
}
You need to put quotes around the strings you want to assign.
result = excellent; should be result = "excellent"; and soforth for all your assignments to return

public class ModuleGrader {
final int examID = 123;
//String excellent=null;
//String good=null;
//String satisfactory=null;
//String compensatableFail=null;
//String outrightFail=null;
int grade;
public String gradeModule(int mark) {
String result = null;
if (mark>=70 && mark<=100)
{
result = "excellent";
System.out.println(" ");
}
else if (mark>=60 && mark<=69)
{
result = "good";
}
else if (mark>=50 && mark<=59)
{
result = "satisfactory";
}
else if (mark>=40 && mark<=49)
{
result = "compensatableFail";
}
else if (mark>=0 && mark<=39) {
result = "outrightFail";
}
else {
System.out.println("Invalid entery, please insert an number between 100-0");
}
return result;
}

Related

Head First Java book battleship game

I am reading "Head First Java" book and I came across the problem in chapter 5 with the battleship game (with simple version). I knew that the book's code doesn't work and I tried my self fixing it, but it still didn't work.
So tried to google it and I found some post on this website but I still have a problem. The game isn't working properly as it should.
If a player enters any random number, the output is always "hit"...
This is the last version of the code:
DotCom class:
public class DotCom {
private ArrayList<String> locationCells = new ArrayList<>();
public void setlocationCells(int[] loc) {
if (loc != null)
for (int val : loc)
locationCells.add(String.valueOf(val));
}
public String checkYourself(String userInput) {
String result = "miss";
int index = locationCells.indexOf(userInput);
if (index >= 0) {
locationCells.remove(index);
}
if (locationCells.isEmpty()) {
result = "kill";
} else {
result = "hit";
}
System.out.println(result);
return result;
}
}
DotComGame class:
public class DotComGame {
public static void main(String[] args) {
int guessingTimes = 0;
DotCom dot = new DotCom();
GameHelperrr helper = new GameHelperrr();
int randomNum = (int) (Math.random() * 5);
int[] locations = { randomNum, randomNum + 1, randomNum + 2 };
dot.setlocationCells(locations);
boolean isAlive = true;
while (isAlive == true) {
String guess = helper.getUserInput("Enter a number");
String result = dot.checkYourself(guess);
guessingTimes++;
if (result.equals("kill")) {
isAlive = false;
System.out.println("You took " + guessingTimes + " guesses");
}
}
}
}
I would really appreciate to get a detailed and understandable answer, because I'm stuck and I couldn't move on with the book for a few days now.
int index = locationCells.indexOf(userInput);
This method will return -1 if the element doesn't exist in the collection.
So if you miss, it won't hit this condition:
if (index >= 0) {
locationCells.remove(index);
}
There are still elements in this collection because you didn't remove anything...
if (locationCells.isEmpty()) {
result = "kill";
} else {
result = "hit";
}
So on a miss, the result still shows "hit."
Try this instead:
if (locationCells.isEmpty()) {
result = "kill";
} else {
result = index == -1 ? "miss" : "hit";
}
If you haven't killed the opponents ships, then you either miss all ships or you hit a single ship.
I would guess the checkYourself-Method must be like this:
public String checkYourself(String userInput) {
String result = "miss";
int index = locationCells.indexOf(userInput);
if(index >= 0) {
locationCells.remove(index);
if (locationCells.isEmpty()) {
result = "kill";
}else {
result = "hit";
}
}
System.out.println(result);
return result;
}
In it's current form the ArrayList is never empty because you insert 3 Values but only remove 1 if the user-input is in the list so .isEmpty() is never TRUE.

junit.framework.AssertionFailedError - Incomplete Stack Trace Given

Full Disclosure: This was an assignment, it has been marked already, but I want to understand why I'm getting this error.
I'm having some issues understanding why junit.framework.AssertionFailedError is being thrown. Normally when errors occur I could at least look at the stack trace and see what is happening. In this case, the output console shows this:
Testcase: testIsCorrectMCQ(mr_3.myTester): FAILED
null
junit.framework.AssertionFailedError
at mr_3.MyTester.testIsCorrectMCQ(Assign03Tester.java:207)
testIsCorrectMCQ(mr_3.MyTester): FAILED
In the test result tab in NetBeans, copying the stack trace gives me:
junit.framework.AssertionFailedError
at mr_3.myTester.testIsCorrectMCQ(myTester.java:207)
In the tester file, I have this:
#Test
public void testIsCorrectMCQ() {
System.out.println("isCorrect of MCQ");
MCQuestion instance = new MCQuestion(1,"Capital city of Canada is", 'A',
"Ottawa", "Vancouver", "New York", "Toronto");
assertFalse(instance.isCorrect("B"));
assertTrue(instance.isCorrect("A")); // line 207
}
My isCorrect method is this:
#Override
public boolean isCorrect(Object guess) {
if (guess == null)
return false;
if (guess instanceof String) {
String userGuess = (String)guess;
return (userGuess.charAt(0) == this.getAnswer());
}
if (guess instanceof Character) {
Character userGuess = (Character)guess;
return (userGuess == this.getAnswer());
}
else return false;
}
Any help in understanding what is happening is greatly appreciated.
Edit 1 : My MCQuestion source code
public class MCQuestion extends Question {
private char answer;
private String[] options;
public MCQuestion() {
super();
questionType = QuestionType.MULTIPLE_CHOICE;
}
public MCQuestion(int id, String text, char answer, String... options) {
super(id, text);
setOptions(options);
setAnswer(answer);
questionType = QuestionType.MULTIPLE_CHOICE;
}
public String[] getOptions() {
String[] getOptions = new String[this.options.length];
System.arraycopy(this.options, 0, getOptions, 0, this.options.length);
return getOptions;
}
public void setOptions(String... options) {
if (options.length > 0) {
this.options = new String[options.length];
for (int i = 0; i < options.length; i++) {
if (options[i].isEmpty())
throw new IllegalArgumentException("You have nothing in this option");
else
this.options[i] = options[i];
}
}
else throw new IllegalArgumentException("You have no options set");
}
public char getAnswer() {
return this.answer;
}
public void setAnswer(char ans) {
ans = Character.toLowerCase(ans);
int index = ans - 97;
if (Character.isLetter(ans) && index >= 0 && index < this.options.length)
this.answer = ans;
else throw new IllegalArgumentException(ans + " is not a valid answer option");
}
#Override
public boolean isCorrect(Object guess) {
if (guess == null)
return false;
if (guess instanceof String) {
String userGuess = (String)guess;
return (userGuess.charAt(0) == this.getAnswer());
}
if (guess instanceof Character) {
Character userGuess = (Character)guess;
return (userGuess == this.getAnswer());
}
else return false;
}
#Override
public String toString() {
String option = "";
if (this.options.length == 0)
option = "No options added, yet!";
else {
char index = 'a';
for (String e: options)
option += index + ") " + e + "\n";
}
return (super.toString() + "\n" + option);
}
}
You execute ans = Character.toLowerCase(ans); for whatever reason in your setAnswer() method before saving it in this.answer. This means that (userGuess.charAt(0) == this.getAnswer()) will return false when you provide the answer in upper case, but compare it with the stored lower case character.
Depending on if you want case insensitive answers or not, you should add or remove the Character.toLowerCase() call to your isCorrect() method as well.

IndexOutOfBound error with string manipulation

this is the code for a pig-latin translator in JAVA, it works with one word but never with a sentence. It seems that the code at line 30 is messing everything up, and I'm not sure how it is doing that or how I can fix it. IndexOutOfBoundError on line 8 and line 30. I'm not sure how to fix this, help.
public class Practice
{
public static void main(String[] args)
{
String a = "hello Stranger";
System.out.println(translate(a)); //8
}
private static String translate(String a)
{
String XD = a;
boolean repeat = true;
int first = 1;
int second = 0;
do
{
second = XD.indexOf(" ");
if (second == -1)
{
repeat = false;
XD = vowelFinder(a);
break;
}
else
{
XD = XD + vowelFinder(a.substring(first, second)); //30
}
first = second +1;
}while(repeat == true);
return XD;
}
private static boolean isVowel (char c)
{
if (c == 'a'|| c== 'e'|| c== 'i' || c == 'o' || c== 'u')
{
return true;
}
return false;
}
private static String vowelFinder(String s)
{
String nope = s;
for(int i = 0; i <= s.length(); i++)
{
if(isVowel(s.charAt(i)) == true)
{
nope = nope.substring(i) + "-"+nope.substring(0, i);`
return nope;
}
}
return nope;
}
}
Try this;
import java.util.Scanner;
public class PigLatin {
public static void main(String[] args) {
Scanner input = new Scanner( System.in );
String yourSentence="";
do {
String[] words;
System.out.print("Enter your words here: ");
yourSentence = input.nextLine();
words = yourSentence.split(" ");
for (String word : words) {
if (word.startsWith("a") || word.startsWith("e") || word.startsWith("i") || word.startsWith("o") || word.startsWith("u"))
System.out.print(word + "way ");
else if (word.startsWith("sh") || word.startsWith("ch") || word.startsWith("th"))
System.out.print(word.substring(2)+word.substring(0,2)+"ay ");
else
System.out.print(word.substring(1)+word.substring(0,1)+"ay ");
}
System.out.println();
} while(!yourSentence.equals("quit"));
}
}

NullPointerException using Scanner

I am new to programming and I'm starting to create a simple calculator in Java, but I keep getting an error on the line
for (int i = 0; i < user_input.length(); i++)
The error says:
Exception in thread "main" java.lang.NullPointerException
How can I fix this problem?
import java.util.*;
import java.awt.*;
import javax.swing.*;
import java.util.Scanner;
public class stringCalculator
{
public static ArrayList<String> input = new ArrayList<String>();
public static ArrayList<String> calcOperators = new ArrayList<String>();
public static ArrayList<Integer> calcOperands = new ArrayList<Integer>();
public static String user_input;
public static String first;
public static int int1;
public static String char1;
public static int int2;
public static String next;
}
public static void input()
{
Scanner user_input = new Scanner(System.in);
int1 = user_input.nextInt();
char1 = user_input.next();
int2 = user_input.nextInt();
next = user_input.nextLine();
}
public void calcOperators()
{
for (int i = 0; i < user_input.length(); i++)
{
if (char1 == "+")
{
calcOperators.add(char1);
}
else if (char1 == "-")
{
calcOperators.add(char1);
}
else if (char1 == "char1")
{
calcOperators.add(char1);
}
else if (char1 == "/")
{
calcOperators.add(char1);
}
}
public void calcOperands()
{
for (int i = 0; i < user_input.length(); i++)
{
if (int1 == 1 || int2 == 1)
{
calcOperands.add(1);
}
else if (int1 == 2 || int2 == 2)
{
calcOperands.add(2);
}
else if (int1 == 3 || int2 == 3)
{
calcOperands.add(3);
}
else if (int1 == 4 || int2 == 4)
{
calcOperands.add(4);
}
else if (int1 == 5 || int2 == 5)
{
calcOperands.add(5);
}
else if (int1 == 6 || int2 == 6)
{
calcOperands.add(6);
}
else if (int1 == 7 || int2 == 7)
{
calcOperands.add(7);
}
else if (int1 == 8 || int2 == 8)
{
calcOperands.add(8);
}
else if (int1 == 9 || int2 == 9)
{
calcOperands.add(9);
}
else if (int1 == 0 || int2 == 0)
{
calcOperands.add(0);
}
}
}
}
public class Main
{
public static void main(String[] args)
{
stringCalculator c = new stringCalculator();
c.input();
c.calcOperators();
c.calcOperands();
}
}
I am kind of confused in here why you have
public static String user_input
and then
Scanner user_input = new Scanner(System.in);
int1 = user_input.nextInt();
char1 = user_input.next();
int2 = user_input.nextInt();
next = user_input.nextLine();
And finally you are using the same var name for strings and ints in loops:
for (int i = 0; i < user_input.length(); i++)
for (int i = 0; i < user_input.length(); i++)
I would highly recommend refactoring this code.
.....
private ArrayList<String> input = new ArrayList<String>();
private ArrayList<String> calcOperators = new ArrayList<String>();
private ArrayList<Integer> calcOperands = new ArrayList<Integer>();
private String user_input;
private String first;
private String next;
private String char1;
private int integer2;
private int integer1;
}
public static void input()
{
Scanner input = new Scanner(System.in);
int int1 = input.nextInt();
int int2 = input.nextInt();
string str = input.next();
string nxt = input.next();
setInteger1(int1);
setInteger2(int2);
setStringFirst(str);
setStringNext(...);
....
// And so on
}
private void setInteger1(int int1) {
this.integer1 = int1;
}
private Integer getInteger1() {
return this.integer1;
}
private void setInteger2(int int2) {
this.integer2 = int2;
}
private Integer getInteger2() {
return this.integer2;
}
private void setStringFirst(String fst) {
this.first = fst;
}
private String getStringFirst() {
return this.first;
}
// And so on. Create all get and set methods for each global variable and for future
// reference do not use variable names that are the same as method, names
// and try to use more meaningful variable names. In fact, if you look at
// Java naming conventions it would do you good.
Could you also tell us perhaps what these loops are meant to do? As I don't really understand what is this? Do you want to iterate over an array of "things" and match each operation to given array element? Or do you just want a single element to match one of the operations?
Side note: Class names should be capitalized:
public class StringCalculator
==================================================================================
OK, I have made a simple program that allows you to add a string into an array and then display it. It is based on what you were doing although you will see it is structured differently. This should give you a head start and allow you to implement this further and finish whatever you are doing.
public class Thing {
private String operator;
private void getUserInput() {
Scanner input = new Scanner(System.in);
if(input.hasNextInt()) {
System.out.println("I have entered an integer: " + input.nextInt());
}
else {
setOperator(input.nextLine());
addOperators();
System.out.println("I have entered a string: " + getOperator());
}
displayThing();
}
private ArrayList<String> addOperators() {
ArrayList<String> operatorsList = new ArrayList<String>();
if(getOperator().equals("+")) {
operatorsList.add(operator);
}
if(getOperator().equals("-")) {
operatorsList.add(operator);
}
else {
operatorsList.add(getOperator());
}
return operatorsList;
}
private void displayThing() {
System.out.println(addOperators());
}
public static void main(String[] args) {
Thing program = new Thing();
program.getUserInput();
}
// Setters and getters
private void setOperator(String operator) {
this.operator = operator;
}
private String getOperator() {
return this.operator;
}
}
You have declared the public static String user_input; which is used in a for loop and not initialised, so thus the exception. Initialise it in your input method, like this.user_input=user_input.nextLine().
You have a static String named user_input defined as:
public static String user_input; // This is null and what the for loop is reading
Set a value to that string when you're using your Scanner... which you shouldn't have also named user_input.

StackOverFlowError in Java postfix calculator

The following class is used by another program. When it is accessed, it throws a StackOverFlowError. This is part of a Postfix Calculator I have to do as a project at my university.
Any help would be greatly appreciated, thank you in advance. I'm quite new at Java and I have no idea what to do.
CODE:
import java.util.Queue;
import java.util.Stack;
public class MyPostfixMachine implements PostfixMachineInterface {
MyMathOperations mmo = new MyMathOperations();
MyPostfixMachine mpm = new MyPostfixMachine();
public String evaluate(Queue q) {
if (q.isEmpty()) {//if the input is empty, terminate the program
System.exit(0);
}
if (q.size() == 1) {//if there is only one number in the queue, return it as the solution
if (mpm.isParsableToDouble(String.valueOf(q.remove()))) {
return String.valueOf(q.remove());
}
}
Stack<String> finalxp = new Stack<String>();//create an empty stack
if (mpm.isParsableToDouble(String.valueOf(q.remove()))) {//if first element of queue q is a number,push it into the stack
finalxp.push(String.valueOf(q.remove()));
} else {//depending on the operator perform the corresponding operations
if (q.remove() == "+") {
String str = String.valueOf(finalxp.pop());
String str2 = String.valueOf(finalxp.pop());
finalxp.push(mmo.addition(str, str2));
}
if (q.remove() == "-") {
String str = String.valueOf(finalxp.pop());
String str2 = String.valueOf(finalxp.pop());
finalxp.push(mmo.substraction(str, str2));
}
if (q.remove() == "*") {
String str = String.valueOf(finalxp.pop());
String str2 = String.valueOf(finalxp.pop());
finalxp.push(mmo.product(str, str2));
}
if (q.remove() == "/") {
String str = String.valueOf(finalxp.pop());
String str2 = String.valueOf(finalxp.pop());
finalxp.push(mmo.division(str, str2));
}
if (q.remove() == "fibo") {
String str = String.valueOf(finalxp.pop());
finalxp.push(mmo.fibonacci(str));
}
if (q.remove() == "fac") {
String str = String.valueOf(finalxp.pop());
finalxp.push(mmo.factorial(str));
}
if (q.remove() == "han") {
String str = String.valueOf(finalxp.pop());
finalxp.push(mmo.hanoi(str));
}
}
return String.valueOf(finalxp.pop());
}
public boolean isParsableToDouble(String candidate) {
try {
Double.parseDouble(candidate);
return true;
} catch (NumberFormatException nfe) {
return false;
}
}
}
public class MyMathOperations implements MathOperationsInterface {
public String addition(String s1, String s2) {
double A = Double.parseDouble(s1);
double B = Double.parseDouble(s2);
return String.valueOf((A + B));
}
public String substraction(String s1, String s2) {
double A = Double.parseDouble(s1);
double B = Double.parseDouble(s2);
return String.valueOf((A - B));
}
public String product(String s1, String s2) {
double A = Double.parseDouble(s1);
double B = Double.parseDouble(s2);
return String.valueOf((A * B));
}
public String division(String s1, String s2) {
double A = Double.parseDouble(s1);
double B = Double.parseDouble(s2);
return String.valueOf((A / B));
}
public String fibonacci(String s) {
int n = Integer.parseInt(s);
return String.valueOf(fibo(n));
}
public int fibo(int f) {
if (f < 0) {
throw new IllegalArgumentException("Cannot apply Fibonacci method");
} else if (f == 0) {
return 0;
} else if (f == 1) {
return 1;
} else {
return fibo(f - 1) + fibo(f - 2);
}
}
public String hanoi(String s) {
int a = Integer.parseInt(s);
int han = 0;
if (a < 0) {
throw new IllegalArgumentException("Not a valid integer");
} else {
han = (int) Math.pow(2, a) - 1;
}
return String.valueOf(han);
}
public String factorial(String s) {
int a = Integer.parseInt(s);
if (a < 0) {
throw new IllegalArgumentException("Incorrect argument for factorial operatiion");
}
switch (a) {
case 0:
case 1:
return String.valueOf(1);
default:
int res = a;
while (true) {
if (a == 1) {
break;
}
res *= --a;
}
return String.valueOf(res);
}
}
private static double pDouble(String s) {
double res = 0d;
try {
res = Double.parseDouble(s);
} catch (NumberFormatException e) {
System.exit(1);
}
return res;
}
}
The problem is that your class MyPostfixMachine has a private field MyPostfixMachine mpm which is initialized with a new MyPostfixMachine. Since this new MyPostfixMachine also has a private field MyPostfixMachine mpm which is initialized with a new MyPostfixMachine... you get it. :) This goes on and on forever (or until your stack is full).
Here is the problematic piece of code:
public class MyPostfixMachine implements PostfixMachineInterface {
MyMathOperations mmo = new MyMathOperations();
MyPostfixMachine mpm = new MyPostfixMachine(); // problem is here
// ...
}
I think you can simply remove the private field mpm. Just call the methods on the current instance. So instead of:
if (mpm.isParsableToDouble(String.valueOf(q.remove()))) {...}
you can simply write:
if (isParsableToDouble(String.valueOf(q.remove()))) {...}
or (equivallent but more explicit):
if (this.isParsableToDouble(String.valueOf(q.remove()))) {...}
Anyway, just remove the private field mpm and the StackOverflowException should be gone.
I'm not sure how you're getting a StackOverflowError (I don't see any loops or recursion in this code), but one definite problem is your overuse of Queue.remove(). Every time you look at the queue in your if clauses, you're lopping-off the first element -- I'd expect this code to be barfing-out NoSuchElementExceptions.
To say nothing of all the EmptyStackExceptions you should be getting from popping from an empty Stack.
So I'd say....
Quit calling `remove()` when you should be calling `peek()` instead.
Quit popping from an empty stack; you want to be pulling those values from your input queue, yes?
The problem giving you your `StackOverFlowError` is elsewhere. (Unless I'm overlooking something -- always possible!) Look for a loop or a recursive call.

Categories

Resources