Java code for guessing game not printing anything - java

So I have a Computer Science course at school in which we learn Java. We were assigned to do a simple text based recreation of the guessing game. I got it done until this point, and I cannot seem to find where I messed up because there is nothing printed when I run the core.
This is the code:
public class GuessGame
{
public static void main(String[] args)
{
new GuessGame();
}
public GuessGame ()
{
char end = 'y';
while (end!='y')
{
System.out.println ("Welcome to the Guessing Game!");
System.out.println ("\nThe computer has picked a number");
System.out.println ("between 1 and 100. Try to guess it.");
int num = (int)(Math.random()*(100-1)+1);
int guess = IBIO.inputInt ("Guess the number: ");
if (guess==num)
System.out.println ("You got it!");
else if (guess>num)
System.out.println ("That is too high.");
else
System.out.println ("That is too low.");
end = IBIO.inputChar ("Exit game? (y/n)");
}
}
}
By the way, IBIO is a class provided by my IB program that we use to make Input/Output statements.
This is IBIO.java:
public class IBIO
{
static void output (String info)
{
System.out.println (info);
}
static void output (char info)
{
System.out.println (info);
}
static void output (byte info)
{
System.out.println (info);
}
static void output (int info)
{
System.out.println (info);
}
static void output (long info)
{
System.out.println (info);
}
static void output (double info)
{
System.out.println (info);
}
static void output (boolean info)
{
System.out.println (info);
}
static String input (String prompt)
{
String inputLine = "";
System.out.print (prompt);
try
{
inputLine = (new java.io.BufferedReader (new java.io.InputStreamReader (System.in))).readLine ();
}
catch (Exception e)
{
String err = e.toString ();
System.out.println (err);
inputLine = "";
}
return inputLine;
}
static String inputString (String prompt)
{
return input (prompt);
}
static String input ()
{
return input ("");
}
static int inputInt ()
{
return inputInt ("");
}
static double inputDouble ()
{
return inputDouble ("");
}
static char inputChar (String prompt)
{
char result = (char) 0;
try
{
result = input (prompt).charAt (0);
}
catch (Exception e)
{
result = (char) 0;
}
return result;
}
static byte inputByte (String prompt)
{
byte result = 0;
try
{
result = Byte.valueOf (input (prompt).trim ()).byteValue ();
}
catch (Exception e)
{
result = 0;
}
return result;
}
static int inputInt (String prompt)
{
int result = 0;
try
{
result = Integer.valueOf (input (prompt).trim ()).intValue ();
}
catch (Exception e)
{
result = 0;
}
return result;
}
static long inputLong (String prompt)
{
long result = 0;
try
{
result = Long.valueOf (input (prompt).trim ()).longValue ();
}
catch (Exception e)
{
result = 0;
}
return result;
}
static double inputDouble (String prompt)
{
double result = 0;
try
{
result = Double.valueOf (input (prompt).trim ()).doubleValue ();
}
catch (Exception e)
{
result = 0;
}
return result;
}
static boolean inputBoolean (String prompt)
{
boolean result = false;
try
{
result = Boolean.valueOf (input (prompt).trim ()).booleanValue ();
}
catch (Exception e)
{
result = false;
}
return result;
}
}
Sorry for the lengthy question. Im new to Java.

The computer is doing exactly what you told it to. When GuessGame's constructor runs:
Declare end as a char local variable and initialise it to contain 'y':
char end = 'y';
Run the loop body while end does not contain 'y':
while (end!='y')
(since end does contain 'y' it does not run the loop body; it skips to the code after the loop).

The problem is that you will never enter the initial loop
char end = 'y';
while (end!='y')
You instantiate end to y, then enter only if end is not y which will always be false, hence never enter the loop.
Simply change the default value of end
char end = 'n';
Also, you don't have to cast the value 0 in your IBIO class
result = (char) 0;
You can simply do result = 0 and it will take the ASCII value.
I would also declare num and guess outside of the loop to avoid re-declaring them each time, as you did for end.
Finally, instead of declaring 7 output method with different paremeter type which simply do a System.out.println of the received parameter I would directly call System.out.println(value).
I would apply the same logic for all other methods that only call one method with the received parameter.

These two lines clearly contradict each other, the while loop will never execute. Initialize end to be a different value.
char end = 'y';
while (end!='y')

You initialize the variable char end with value 'y'.
char end = 'y';
Then the condition for your loop is
while (end!='y')
This condition is never fulfilled, that's why it's out of the loop. Change the initial value of the variable end.

Related

perform calculations with incoming args as my inputString for my calculator

If I run my calculator I want it to start to calculate automatically with the given args e.g. 4+4-2. When there are no args he just asks for the user to insert numbers (scanner). Here is my code.So the args need to be assigned to my inputString if there are nog args the scanner will ask the user to isert something.
Main
package com.haynespro.calculator;
import java.util.Scanner;
public class CharAtExample {
public static void main(String[] args) {
for (String arg : args) {
System.out.println(arg);
}
// inputString with scanner
String inputString = "0";
inputString = inputString.replace(",", "");
Scanner userInput = new Scanner(System.in);
System.out.print("please insert your calculations: ");
inputString = userInput.next();
userInput.close();
Calculator calculator = new Calculator();
calculator.startCalculator(inputString);
}// end of main
}// end of class
calculator
package com.haynespro.calculator;
import java.util.ArrayList;
public class Calculator {
public void startCalculator(String inputString) {
// Assign ArrayList of Strings "res" to splitExpression
ArrayList<String> res = splitExpression(inputString);
// Create an ObjectList that holds res
ArrayList<Object> objectList = new ArrayList<Object>(res);
System.out.print("\nLet my algorithm take care of it: \n\n");
// Loop through the objectList and convert strings to doubles
for (int i = 0; i < objectList.size(); i++) {
try {
objectList.set(i, Double.parseDouble((String)
objectList.get(i)));
} catch (NumberFormatException nfe) {
}
}
// Create a variable maxi to substract 2 from the objectList index
int maxi = objectList.size();
maxi = maxi - 2;
// Create variable lastSum out of the incoming for-loop's scope.
double lastSum = 0;
// Loop through the objectList with an algorhitm and perform
calculations with
// invoking the sum method
for (int i = 0; i < maxi; i += 2) {
String operator = (String) objectList.get(i + 1);
double a = (Double) objectList.get(i);
double b = (Double) objectList.get(i + 2);
double sum;
if (i == 0) {
sum = sum(a, b, operator);
} else {
sum = sum(lastSum, b, operator);
}
lastSum = sum;
System.out.println(lastSum);
}
}
// Method that matches the string input with operators to perform
calculations.
public static double sum(Double a, Double b, String operator) {
if (operator.equals("+")) {
return a + b;
}
if (operator.equals("-")) {
return a - b;
}
if (operator.equals("*")) {
return a * b;
}
if (operator.equals("/")) {
return a / b;
}
return 0;
}
// ArrayList splitExpression that casts to inputString
private static ArrayList<String> splitExpression(String inputString) {
// ArrayList result to return the result
ArrayList<String> result = new ArrayList<String>();
// Uses the toCharArray method to insert the string reference per
character into
// an array
char[] destArray = inputString.toCharArray();
// Empty String created
String token = "";
// Iterate through the "Items" in the Array
for (int i = 0; i < destArray.length; i++) {
// Nice all those references but we need an Object that actually
holds the array
char c = destArray[i];
// If not a number then add to token, else assign the value of c to
token
if (isBreakCharacter(c)) {
result.add(token);
result.add(Character.toString(c));
token = "";
} else
token = token + c;
}
result.add(token);
return result;
}
// a method that breaks characters which are not numbers.The object "c" also
// needs to hold this method.
public static boolean isBreakCharacter(char c) {
return c == '+' || c == '*' || c == '-' || c == '/';
}
}
change your main by using args (also some refactoring in the main class):
public static void main(String[] args) {
String input=null;
if(args.length>0){
input=args[0];
System.out.println(input);
}else{
input=askForInput();
}
Calculator calculator = new Calculator();
calculator.startCalculator(input);
}// end of main
private static String askForInput() {
// inputString with scanner
Scanner userInput = new Scanner(System.in);
System.out.print("please insert your calculations: ");
String inputString;
try {
inputString = userInput.next();
} finally {
userInput.close();
}
return inputString;
}
You are not validating args.length to figure out how many parameters have been passed in.
I will give you a simplified version since I don't have any idea how you are supposed to read/parse args.
String input;
if (args.length < 1) {
// you need a Scanner to read an input for the calculator
input = new Scanner(System.in).nextLine();
} else {
// you've got args to parse
input = String.join("", args);
}
new Calculator().startCalculator(input);

Function that checks Java program arguments

I'm trying to re-write this code in a cleaner way:
public static void main(String[] args) {
if(checkArgs(args) < 0) return;
return;
}
private static int checkArgs(String[] args) {
if (args.length == 0) {
System.out.println("Error: No Args");
return -1;
}
try{ //If it's a number
int myNumber = Integer.parseInt(args[0]);
System.out.println("My number is: " + myNumber);
}
catch (Exception e) {//If it's a String
try{
String[] myStr = args ;
System.out.print("My String is ");
for (int i=0; i<args.length; i++) {
myStr[i] = args[i];
System.out.print(myStr[i]);
}
System.out.print("\n");
return 0;
}
catch(Exception err){
System.out.println("Error");
return -1;
}
}
return 0;
}
The code checks the program args and tell the user if it's a String or just a number.
Any ideas on how to re-write this code without using try-catch?
First, you don't really need the second try...catch. This code:
String[] myStr = args ;
System.out.print("My String is ");
for (int i=0; i<args.length; i++) {
myStr[i] = args[i];
System.out.print(myStr[i]);
}
System.out.print("\n");
return 0;
Is not throwing any checked exception and is not very likely to ever throw a runtime exception.
Second, this code also has parts that are simply not needed - the myStr array - you assign the args array to it, and then you assign each element individually to it. And it's a local variable so it's going to go away as soon as you return anyway.
So:
System.out.print("My String is ");
for (int i=0; i<args.length; i++) {
System.out.print(args[i]);
}
System.out.print("\n");
return 0;
would do the same thing and is not going to throw exceptions.
Now, as for checking the integer - I think just using it like this and catching the exception is good enough. Just catch NumberFormatException instead of Exception. It's never a good idea to do a catch-all.
But if you insist on a method without try-catch, you could do something like this:
private static boolean checkInt(String str) {
if ( ! str.matches("-?0*[0-9]{1,10}")) {
return false;
}
long l = Long.valueOf(str);
if ( l > Integer.MAX_VALUE || l < Integer.MIN_VALUE) {
return false;
}
System.out.println("My number is: " + myNumber);
return true;
}
This first checks that you have no more than 10 digits with or without a minus sign (and any number of preceding zeros). If so, then it can be safely converted to a long, without exception checking. You can then check if the resulting long is in the range of an integer. It's a workaround that requires no try and catch, but I don't think it's better than the try-catch method.
So, with try-catch, you would have:
private static int checkArgs1(String[] args) {
if (args == null || args.length == 0) {
System.out.println("Error: No Args");
return -1;
}
try { // If it's a number
int myNumber = Integer.parseInt(args[0]);
System.out.println("My number is: " + myNumber);
} catch (NumberFormatException e) {// If it's a String
String[] myStr = args;
System.out.print("My String is ");
for (int i = 0; i < args.length; i++) {
myStr[i] = args[i];
System.out.print(myStr[i]);
}
System.out.print("\n");
return 0;
}
return 0;
}
And without it, using my checkInt() method:
private static int checkArgs2(String[] args) {
if (args == null || args.length == 0) {
System.out.println("Error: No Args");
return -1;
}
if ( ! checkInt(args[0])) {
// If it's a String
String[] myStr = args;
System.out.print("My String is ");
for (int i = 0; i < args.length; i++) {
myStr[i] = args[i];
System.out.print(myStr[i]);
}
System.out.print("\n");
return 0;
}
return 0;
}
I'm not really sure how useful your check is, though. Usually, argument checking is done in preparation for doing something with the args, and you don't save the information about whether it was a number or a string anywhere.
As mentioned in the comments your code has compilation issues. As far as logic is concerned, to find out if an input string contains only digits or not, you can use regex as shown below.
Pattern p = Pattern.compile("^-?[0-9]+$");
if(p.matcher(arg[0]).matches()) {
System.out.println("It's a number!!");
} else {
System.out.println("Not a number.");
}
In this case you don't have to use try/catch block.
Try like this...
public class CheckArgs {
public static void main(String[] args) {
if (args != null && args.length != 0) {
for (String arg : args) {
System.out.println(String.format("<----- %s ----->", arg));
System.out.println(String.format("is number %s", checkIfNumber(arg)));
System.out.println(String.format("is string %s", checkIfString(arg)));
System.out.println(String.format("<-------------->", arg));
}
}
}
private static boolean checkIfString(Object arg) {
if (arg instanceof String) {
return true;
}
return false;
}
private static boolean checkIfNumber(Object arg) {
if (arg instanceof Integer) {
return true;
}
return false;
}
}

Finding a repeated character in a string

The problem states the following: given a string and a character by the user find the number of times the character (given by the user) repeats itself in the string (also given by the user).
I have this piece of code
public int repeticion (int s){
int return = 0;
int cont = 0;
Scanner in = new Scanner(System.in);
System.out.println("Write a string: ");
String chain = in.next();
System.out.println("Write the character: ");
String character = in.next();
if (chain.contains(character)) {
cont = cont + 1;
}
System.out.println("The character repeats itself "+cont+"times");
return return;
But as you can see the .contains only counts the character once, not the number of times it appears in the string.
.contains() only says that a character exists within a string, not how many. You need to iterate over each character of a string to check if it equals the character you are searching for.
String chain = "your string";
int cont = 0;
for(int i=0; i<chain.length(); i++) {
if(chain.charAt(i) == character) {
cont++;
}
}
You could also repeatedly check that the character is in the string, get that index, then check the substring from after that index to the end of the string. I recommend the following:
int index = 0;
int count = 0;
while (chain.indexof(character, index) != -1 && index < chain.length()-1) {
index = chain.indexof(character, index) + 1;
count++;
}
Contains will simply tell you if the character is present. To actually count the number of times that character would appear, you'll need to iterate over the string and count the number of times the selected character appears. This method will work:
public countACharacter(char thecharacter, String stringtocountcharactersin) {
int count = 0;
for(int i = 0; i < stringtocountcharactersin.length(); i++) {
if(stringtocountcharactersin.charAt(i) == thecharacter) {
count++;
}
}
return count;
}
import java.io.*;
public class Duplicate {
public static void main(String[] args) throws IOException {
int distinct = 0;
int i = 0, j = 0;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter STRING : -");
String s = br.readLine();
try {
for (i = 0; i < s.length(); i++) {
while (s != null) {
s = s.trim();
for (j = 0; j < s.length(); j++) {
if (s.charAt(i) == s.charAt(j)) {
distinct++;
}
}
System.out.println(s.charAt(i) + "--" + distinct);
String d = String.valueOf(s.charAt(i));
s = s.replaceAll(d, " ");
distinct = 0;
}
}
} catch (Exception e) {}
}
}
public static void chars( String a, char k)
{
String z=""+k;
int s=0;
for(int i=0;i<a.length();i++)
{
if(z.equals(a.substring(i,i+1)))
s++;
}
System.out.println(s);
}
you can achieve your goal this way you're taking the integer s without any reason and what you're doing wrong is you are using .contains() method instead of that you should compare the given char with each char of the string and use a counter for maintaining number of times of the character or you can do it this way by converting the char into a string by concatenating it with an empty string("") and then use .equals method like i have used in my code.
//With out string methods.
public static void main(String[] args) {
String ss="rajesh kumar";
Field value = null;
try {
value = String.class.getDeclaredField("value");
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// It's private so we need to explicitly make it accessible.
value.setAccessible(true);
try {
char[] values = (char[])value.get(ss);
//String is converted to char array with out string functions
for (int i = 0; i < values.length; i++) {
int count=0;
for(int j=0;j<values.length;j++)
{
if(values[i]== values[j])
{
count++;
}
}
System.out.println("\n Count of :"+values[i] +"="+count);
}
System.out.println("Values "+values[1]);
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Reversing a word with a Stack

I am new here and in programming as well. I am trying to study other topics alone since my instructor isn't enough help when I have a question so here it goes. I want reverse a word with a generic Stack.
My pop,push,isEmpty and peek methods work (I tested them with a simpler program I made before I tried it on this one.) and the output seems to be giving me the reversed word char by char but always giving me a null before each char!
My questions are:
Why is this happening? And even though I have an expandCapacity method to work when the capacity is at 9 but it doesn't apply when the input passes the limit.
Here's my code
package Stack;
import java.util.Scanner;
public class ReverseDriver<T> {
private static String out;
private static String in;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter your sentence: ");
in = input.nextLine();
int size = in.length();
ArrayStack<Character> revStack = new ArrayStack<>(size);
for (int i = 0; i < in.length(); i++) {
char u = in.charAt(i);
revStack.Push(u);
if (in.length() > 9) {
revStack.expandCapacity();
}
}
while (!revStack.IsEmpty()) {
char u = revStack.Pop();
out = out + u;
System.out.flush();
System.out.print(out);
}
}
}
Here's the Output
run:
Enter a word:
word
nullr
nullro
nullrow
Exception in thread "main" java.lang.NullPointerException
at Stack.ReverseDriver.main(ReverseDriver.java:37)
Java Result: 1
BUILD SUCCESSFUL (total time: 2 seconds)
EDIT: here's the methods that I said that were working.
#Override
public void Push ( T element)
{
if (count == stack.length){
expandCapacity();
}
stack[++count] = element;
//System.out.println(count);
}
#Override
public String toString()
{
String result = "<top of stack>\n";
for (int index=count-1; index >= 0; index--){
result += stack[index] + "\n";
}
return result + "<bottom of stack>";
}
#Override
public boolean IsEmpty()
{ //Checks if array is empty
if(count == 0){
System.out.println("Nothing");
}
return count == 0;
}
public T Pop()
{
T output;
output = (stack[count - 1]);
count--;
return(output);
}
#Override
public T Peek()
{
//looks at the object at the top of this stack without removing it
//from the stack.
if(stack.length == 0){
// {
System.out.println("Cant peek a ghost");
}
return(stack[--count]);
}
// else
// {
// System.out.println( stack[count-1]);
// }
// }
#Override
public int Size()
{
//Sets the size of this vector
if(stack.length == 0){
System.out.println("Nothing inside");
}
System.out.println("The array's size is : " + count);
return count;
}
}
private static String out;
The value in out is null.
out = out + u;
// This is null = null + u;
Hence the null at the beginning of your output.
You simply need to create a new String object to give out an initial value:
private static String out = "";
i'm not sure why you need the ExpandCapacity bit there, this works aswell:
public static void main(String[] args)
{
String word ="reverse please";
Stack<Character> chStack = new Stack<Character>();
for (int i = 0; i < word.length(); i ++)
{
chStack.push(word.charAt(i));
}
String out = "";
while (chStack.size() != 0)
{
out += chStack.pop();
System.out.println(out);
}
}
There are a few notes:
You are not writing a generic class so drop .
Leave the iteration to for as much as possible.
Try using Java standard classes as much as possible, in this case Stack instead of ArrayStack.
You don't need to resize the stack, it will handle its size dynamically as you put more data in.
You should write the string once you are done creating it not once in every step.
Appending strings using + is very inefficient. Use StringBuilder.
Use methods they make your code readable.
Heres the code:
import java.util.Scanner;
import java.util.Stack;
public class ReverseDriver {
public static String reverse(String string) {
Stack<Character> revStack = new Stack<Character>();
for (char c : string.toCharArray()) {
revStack.push(c);
}
StringBuilder builder = new StringBuilder();
while(!revStack.isEmpty()){
builder.append(revStack.pop());
}
return builder.toString();
}
public static void main(String[]args){
Scanner input = new Scanner(System.in);
System.out.println("Enter your sentence: ");
String in = input.nextLine();
System.out.println(reverse(in));
}
}

Using the same values in separate if statements in java

I am working on a problem where I have a menu option 1. to shuffle the word, 2 to take the shuffle word and try to fix it by changing the array index numbers.
I did this part if (input==1) shuffle the word.
I now have to take that the same shuffle word in in if (input==2) section and try to fix it. Can anybody guide me how can I use the same values in this block if(input==1)?
import java.util.Scanner;
import java.io.*;
import java.util.*;
public class Project2 {
public static void main(String[] args) {
while (true) {
System.out.println("Select an item from below: \n");
System.out.println("(1) Mix");
System.out.println("(2) Solve");
System.out.println("(3) Quit");
int input;
Scanner scan = new Scanner(System.in);
input = scan.nextInt();
String team;
String mix_word;
char orig_team[];
char mix_team[];
boolean Result;
// System.out.println(input);
if (input == 1) {
team = orig();
System.out.println(team);
mix_word = mix(team);
System.out.println(mix_word);
orig_team = team.toCharArray();
mix_team = mix_word.toCharArray();
int arg_length = mix_team.length;
}
if (input == 2) {
}
if (input == 3) {
break;
}
if (input > 3 || input <= 0) {
System.out.println("input accurate numbers 1 or 2 or 3");
}
}
}
static String mix(String Team) {
String word = shuffle(Team);
return word;
}
static String shuffle(String input) {
List<Character> characters = new ArrayList<Character>();
for (char c : input.toCharArray()) {
characters.add(c);
}
StringBuilder output = new StringBuilder(input.length());
while (characters.size() != 0) {
int randPicker = (int) (Math.random() * characters.size());
output.append(characters.remove(randPicker));
}
return output.toString();
}
static String orig()
{
String[] lines = new String[1000];// Enough lines.
int counter = 0;
try {
File file = new File("input.txt");// The path of the File
FileReader fileReader1 = new FileReader(file);
BufferedReader buffer = new BufferedReader(fileReader1);
boolean flag = true;
while (true) {
try {
lines[counter] = buffer.readLine();// Store a line in the
// array.
if (lines[counter] == null) {// If there isn't any more
// lines.
buffer.close();
fileReader1.close();
break;// Stop reading and close the readers.
}
counter++;
} catch (Exception ex) {
break;
}
}
} catch (FileNotFoundException ex) {
System.out.println("File not found.");
} catch (IOException ex) {
System.out.println("Exception ocurred.");
}
int pick;
Random rand = new Random();
pick = rand.nextInt(counter) + 0;
return (lines[pick]);
}
}
In every loop cycle (which handles a single user input) you declare your variables, so their scope (the access range) is limited to that cycle.
If you declare your variables outside the while-loop, their scope will stretch over the whole loop (until the end of the method):
public static void main(String[] args) {
String team = "";
String mix_word = "";
char orig_team[] = null;
char mix_team[] = null;
boolean Result = false;
while (true) {
// ** your usual input handling here **
}
}
Also be sure to initialize them (e.g. with a default value), or else the program will not compile.
Another way would be to create member- or class-variables, which would have the advantage of automatic initialization and a larger scope.
This is a rather pathological use case of the switch statement but you can take advantage of the drop-through and do the following:
switch(input) {
case 1:
team = orig();
System.out.println(team);
mix_word = mix(team);
System.out.println(mix_word);
orig_team = team.toCharArray();
mix_team = mix_word.toCharArray();
arg_length = mix_team.length;
// No break; here!
case 2:
// do the rest of your thing as if it were case 2
break;
case 3:
break;
default:
System.out.println("input accurate numbers 1 or 2 or 3");
}

Categories