Why is the char value transforming during the output? - java

I am making my program to throw a die (as in dices) for a school assignment in Java SE. The user can place a character as standard input, so the character the user picks will represent the eyes of the die. Sometimes when I print the result, it shows a completely different character.
package ThrowADie;
import java.util.Scanner;
public class ThrowADie {
public static void main(String[] args) {
//Ask user for the char in which the dices eyes should be printed in.
System.out.print("Which character should I use for the eye: ");
//Allow user to place input in the eye variable
Scanner input = new Scanner(System.in); //Make the stdinput object
char eye = input.next().charAt(0);
//Time to throw the die. Place result in dieResult
int dieResult = throwDie();
//Reveal of the result
printDieResult(dieResult, eye);
}
/*
* Method name: throwDie()
* Purpose: Picks a number from 1 to 6 randomly, like a die does
* Parameters: N/A
* Returns: Integer number from 1 to 6
*/
public static int throwDie(){
int range = (6 - 1) + 1;
return (int)(Math.random() * range) + 1;
}
/*
* Method name: printDieResult()
* Purpose: Generate result of the die throw in ASCII art
* Parameters: numberOfEyes, typeOfEyes
* Returns: N/A
*/
public static void printDieResult(int numberOfEyes, char typeOfEyes){
if (numberOfEyes == 1){
//Print art
System.out.println(
" " + " " + " \n"
+ " " + typeOfEyes + " \n"
+ " " + " " + " ");
} else if (numberOfEyes == 2){
//Print art
System.out.println(
typeOfEyes + " " + " \n"
+ " " + " " + " \n"
+ " " + " " + typeOfEyes);
} else if (numberOfEyes == 3){
//Print art
System.out.println(
typeOfEyes + " " + " \n"
+ " " + typeOfEyes + " \n"
+ " " + " " + typeOfEyes);
} else if (numberOfEyes == 4){
//Print art
System.out.println(
typeOfEyes + " " + typeOfEyes + "\n"
+ " " + " " + " \n"
+ typeOfEyes + " " + typeOfEyes);
} else if (numberOfEyes == 5){
//Print art
System.out.println(
typeOfEyes + " " + typeOfEyes + "\n"
+ " " + typeOfEyes + " \n"
+ typeOfEyes + " " + typeOfEyes);
} else {
//Print art
//Accidentally written down 9 eye representation
System.out.println(
typeOfEyes + typeOfEyes + typeOfEyes + "\n"
+ typeOfEyes + typeOfEyes + typeOfEyes + "\n"
+ typeOfEyes + typeOfEyes + typeOfEyes);
}
}
}
Output
This program will generate proper results. But occasionally the char that has been input, that represent the eye of the die, transforms in to a number.
In the case below, the program should print 9 '#' characters. Instead it prints 192 on the first row. (I know dices have 6 eyes but I bumped into this strange output while accidentally printing 9 eyes)
run:
Which character should I use for the eyes: #
192
###
###
I can not find the cause of this, can anyone see what I have done wrong here?

Character arithmetic!
Consult this table. # is character 64
typeOfEyes + typeOfEyes + typeOfEyes + "\n"
This first line is actually adding up the values of the characters (64 + 64 + 64) = 192, then addending that with a newline, so we get 192\n.
The compiler is choosing to add those up rather than create a String of characters. The easy way to solve this is to preface that with an empty string in front: "" + typeOfEyes...
Basically, the compiler is "dumb." When we add integers to Strings, "foo" + 123 the compiler can interpret that as foo123 just fine because it recognizes the first element as a String. However, we've defined a char which is a numeric type representing a character. So the compiler does math with it. Even though we shouldn't be. Adding the String literal tells it we actually want text.

int test = (int) (typeOfEyes + typeOfEyes + typeOfEyes);
System.out.println("\n" + test + "\n"
+ typeOfEyes + "" + typeOfEyes + "" + typeOfEyes + "\n"
+ typeOfEyes + "" + typeOfEyes + "" + typeOfEyes + "\n"
+ typeOfEyes + "" + typeOfEyes + "" + typeOfEyes);
Which character should I use for the eye: #
192
###
###
###

Related

Java error handling for project- Line matched except underscores: Invalid Event Code_?

I completed this java project for a class, but I cannot seem to fix the error I'm getting for the web software that grades it- it's called webcat. I've tried the test input the software suggests for a reference test against my solution, and my output looks exactly the same, but I still lost points for this error-
"Error in method main of class Event: Line number 2 of your output is incorrect (line numbers begin at 1). Your main method does not print the correct output when the input is "This is a short test " (input less than 26 characters) [] Line matched except underscores: Invalid Event Code_".
How can I fix this error when the expected ouput looks fine? Thanks in advance!
Code:
public class Event {
/**
* accepts coded event info, prints the info back to std output, and
actual cost and prize number.
*
* #param args Command line arguments - not used.
*/
public static void main(String[] args) {
// variables needed
String shrink, event, date, time, section, row, seat;
double price, discount, cost;
int prizeNum;
// accept input
Scanner userInput = new Scanner(System.in);
// format the numbers
DecimalFormat formatNum = new DecimalFormat("$#,##0.00");
// enter input and trim the space
System.out.print("Enter your event code: ");
shrink = userInput.nextLine().trim();
if (shrink.length() < 26) {
System.out.println();
System.out.println("Invalid Event Code");
System.out.println("Event code must have at least 26 characters.");
return;
}
// locates spot in index of code and assigns
event = shrink.substring(25, shrink.length());
date = shrink.substring(0, 8);
time = shrink.substring(8, 12);
section = shrink.substring(19, 21);
row = shrink.substring(21, 23);
seat = shrink.substring(23, 25);
price = Double.parseDouble(shrink.substring(12, 15)
+ "." + shrink.substring(15, 17));
discount = Double.parseDouble(shrink.substring(17, 19));
// calculates final cost
cost = price - (price * (discount / 100));
// random final number
prizeNum = (int) (Math.random() * 1000 + 1);
// prints the data to std output
System.out.println();
System.out.print("Event: " + event + " " + " " + " ");
System.out.print("Date: " + date.substring(0, 2) + "/"
+ date.substring(2, 4) + "/" + date.substring(4, 8) + " "
+ " " + " ");
System.out.println("Time: " + time.substring(0, 2) + ":"
+ time.substring(2, 4) + " " + " " + " ");
System.out.print("Section: " + section + " " + " " + " ");
System.out.print("Row: " + row + " " + " " + " ");
System.out.println("Seat: " + seat);
System.out.print("Price: " + formatNum.format(price) + " " + " " + " ");
// formats discount before print
formatNum.applyPattern("#.#'%'");
System.out.print("Discount: " + formatNum.format(discount) + " "
+ " " + " ");
// formats cost before print
formatNum.applyPattern("$#,##0.00");
System.out.println("Cost: " + formatNum.format(cost));
System.out.print("Prize Number: " + prizeNum);
Output:
Enter your event code: This is a short test
Invalid Event Code
Event code must have at least 26 characters.

How can I print an array while keepping the indentation?

I have this array that shows the user the indexes of the position on a board of a game I'm making, the board is hexagonal and the notations bellow aren't finished yet because I'm to lazy to finish them right now :), but I'm wondering how can I print it on the console while keeping the format.
Thanks in advance
public static final String[] NOTATION = {
" 0/4 0/6 0/8 0/10 0/12 ",
" 1/3 1/5 1/7 1/9 1/11 1/13 ",
" 2/2 2/4 2/6 2/8 2/10 2/12 2/14 ",
" F + + + + + + + + ",
" E + + + + + + + + + ",
" D + + + + + + + + 9",
" C + + + + + + + 8 ",
" B + + + + + + 7 ",
" A + + + + + 6 ",
" 1 2 3 4 5 "
};
I recommend making a method you can call that prints it so you can print it easily many times, for example printBoard:
public static void printBoard() {
for (String str : NOTATION) {
System.out.println(str);
}
}
This utilizes an enhanced for loop to iterate through the array, and print each String moving to the next line with println.
Use it with:
public static void main(String[] args) {
printBoard();
}
Output:
0/4 0/6 0/8 0/10 0/12
1/3 1/5 1/7 1/9 1/11 1/13
2/2 2/4 2/6 2/8 2/10 2/12 2/14
F + + + + + + + +
E + + + + + + + + +
D + + + + + + + + 9
C + + + + + + + 8
B + + + + + + 7
A + + + + + 6
1 2 3 4 5
Note: I recommend reworking this into not using static and instead using OOP in something like a Board class.

How to search a token for a specific word in Java?

I have a segment of code that splits a string into tokens and prints them each out on a new line. I am having a hard time writing a code that determines if a word is a reserved word or not. I have to print "Reserved word is: " if the word is a java keyword, otherwise print "Current word is: ". Here is my code so far:
package projectweek3;
/**
*
* Name -
* Email Address -
* Date -
*
*/
public class Week3Project {
final static String program = "/*\n" +
" * To change this license header, choose License Headers in Project Properties.\n" +
" * To change this template file, choose Tools | Templates\n" +
" * and open the template in the editor.\n" +
" */\n" +
"package testapplication2;\n" +
"\n" +
"import java.util.Scanner;\n" +
"\n" +
"/**\n" +
" *\n" +
" * #author james\n" +
" */\n" +
"public class TestApplication2 {\n" +
"\n" +
" /**\n" +
" * #param args the command line arguments\n" +
" */\n" +
" public static void main(String[] args) {\n" +
" Scanner input = new Scanner(System.in);\n" +
" \n" +
" System.out.println(\"Enter integer #1\");\n" +
" int num1 = input.nextInt();\n" +
" \n" +
" System.out.println(\"Enter integer #2\");\n" +
" int num2 = input.nextInt();\n" +
" \n" +
" System.out.println(\"Enter integer #3\");\n" +
" int num3 = input.nextInt();\n" +
" \n" +
" System.out.println(\"Enter integer #4\");\n" +
" int num4 = input.nextInt();\n" +
" \n" +
" System.out.println(\"Enter integer #5\");\n" +
" int num5 = input.nextInt();\n" +
" \n" +
" //determine the sum\n" +
" int sum = num1 + num2 + num3 + num4 + num5;\n" +
" \n" +
" //this is helpful to make sure your sum is correct\n" +
" System.out.println(\"The sum is: \" + sum);\n" +
" \n" +
" //why doesn't this generate the sum correctly\n" +
" double average = sum / 5;\n" +
" \n" +
" //The average, lets hope its right...\n" +
" System.out.println(\"The average of your numbers is: \" + average);\n" +
" \n" +
" }\n" +
" \n" +
"}\n" +
"";
**public static void main(String[] args)
{
String str = program;
String s = "";
for (int i = 0; i < str.length(); i++) {
s += str.charAt(i) + "";
if (str.charAt(i) == ' ' || str.charAt(i) == '\t' || str.charAt(i) == '\n' || (str.charAt(i) == ' ' && str.charAt(i) == '\n')) {
String currentWord = s.toString();
String res = "int";
if (currentWord.equals(res)) {
System.out.println("Reserved word is: [" + currentWord + "]");
}
else {
System.out.println("Current word is: [" + currentWord + "]");
}
s = "";//Clear the string to get it ready to build next token.
}
}**
I would reconsider the way you're looping through the "program."
Instead of going through character by character, use the Java String.split() function.
String program = "int num1 = input.nextInt();\n";
String[] words = program.split("[\\n\\s\\t]");
for (String word : words) {
System.out.println(word);
}
Output:
int
num1
=
input.nextInt();
EDIT:
Since you can't use String.split(), your looping solution looks good. To check if the current word is reserved, try using Set.contains().
Set<String> reserved = new HashSet<>();
reserved.add("int");
// ...
if reserved.contains(word) {
System.out.println("Reserved word is: " + word);
} else {
System.out.println("Current word is: " + word);
}
That is, assuming you're allowed to use Set.

Storing part of method as another method?

Basically, I have code that uses the same few lines in different scenarios, and it makes the code a bit messy (especially since I probably overcomplicated what I made, but that's another issue). What I wanted to do is store that piece of code as another function and calling it in the longer one. WHich should work as far as I know, except, the longer function has variables that aren't set in the shorter one, and if they were, I'm pretty sure it would change the final result of the function.
Here is the longer code:
public static void combat(Character a,Character b){
int battleturn = 1;
int maxTurns=20;
int draw1 = 0;
//stop after 20 turns, or stop when one player has 0 HP.
while (a.health > 0 && b.health > 0 && maxTurns > 0){
/* run a round of combat*/
if (b.health < 0.25 * b.maxHealth){
if (b.getFlee(a)){
System.out.println(">>>>>>>>>>The enemy has fled successfully<<<<<<<<<<");
break;
}else{
System.out.println("Battle turn " + battleturn + ", <attack> or <flee>?");
Scanner input = new
Scanner(System.in);
String move = input.next();
while(!move.equals("attack") && !move.equals("flee")){
System.out.println("Error: Please input <attack> or <flee>.");
input = new Scanner(System.in);
move = input.next();
}
if (move.equals("attack")){
System.out.println(a.name + " dealt " + a.combatRound(b) + " damage to " + b.name + "." + " Enemy has "
+ b.getHealth() + "/" + b.getMaxHealth() + " health.");
System.out.println(b.name + " dealt " + b.combatRound(a) + " damage to " + a.name + "." + " You have " +
a.getHealth() + "/" + a.getMaxHealth() + " health");
maxTurns--;
battleturn++;
}else if(move.equals("flee")){
if (a.getFlee(b)){
draw1++;
System.out.println(">>>>>>>>>>You have fled!<<<<<<<<<<");
break;
}else{
System.out.println(a.name + " dealt " + a.combatRound(b) + " damage to " + b.name + "." + " Enemy has " +
b.getHealth() + "/" + b.getMaxHealth() + " health.");
System.out.println(b.name + " dealt " + b.combatRound(a) + " damage to " + a.name + "." + " You have " +
a.getHealth() + "/" + a.getMaxHealth() + " health");
maxTurns--;
battleturn++;
}
}
}
}else{
System.out.println("Battle turn " + battleturn + ", <attack> or <flee>?");
Scanner input = new
Scanner(System.in);
String move = input.next();
while(!move.equals("attack") && !move.equals("flee")){
System.out.println("Error: Please input <attack> or <flee>.");
input = new Scanner(System.in);
move = input.next();
}
if (move.equals("attack")){
System.out.println(a.name + " dealt " + a.combatRound(b) + " damage to " + b.name+ "." + " Enemy has " +
b.getHealth() + "/" + b.getMaxHealth() + "health.");
System.out.println(b.name + " dealt " + b.combatRound(a) + " damage to " + a.name + "." + " You have " +
a.getHealth() + "/" + a.getMaxHealth() + " health");
maxTurns--;
battleturn++;
}else if(move.equals("flee")){
if (a.getFlee(b)){
draw1++;
System.out.println(">>>>>>>>>>You have fled!<<<<<<<<<<");
break;
}else{
System.out.println(a.name + " dealt " + a.combatRound(b) + " damage to " + b.name+ "." + " Enemy has " +
b.getHealth() + "/" + b.getMaxHealth() + " health.");
System.out.println(b.name + " dealt " + b.combatRound(a) + " damage to " + a.name + "." + " You have " +
a.getHealth() + "/" + a.getMaxHealth() + " health");
maxTurns--;
battleturn++;
}
}
}
}
}
As you can see there is a part of code that is repeated, and that is.
System.out.println("Battle turn " + battleturn + ", <attack> or <flee>?");
Scanner input = new
Scanner(System.in);
String move = input.next();
while(!move.equals("attack") && !move.equals("flee")){
System.out.println("Error: Please input <attack> or <flee>.");
input = new Scanner(System.in);
move = input.next();
}
if (move.equals("attack")){
System.out.println(a.name + " dealt " + a.combatRound(b) + " damage to " + b.name + "." + " Enemy has "
+ b.getHealth() + "/" + b.getMaxHealth() + " health.");
System.out.println(b.name + " dealt " + b.combatRound(a) + " damage to " + a.name + "." + " You have " +
a.getHealth() + "/" + a.getMaxHealth() + " health");
maxTurns--;
battleturn++;
}else if(move.equals("flee")){
if (a.getFlee(b)){
draw1++;
System.out.println(">>>>>>>>>>You have fled!<<<<<<<<<<");
break;
}else{
System.out.println(a.name + " dealt " + a.combatRound(b) + " damage to " + b.name + "." + " Enemy has " +
b.getHealth() + "/" + b.getMaxHealth() + " health.");
System.out.println(b.name + " dealt " + b.combatRound(a) + " damage to " + a.name + "." + " You have " +
a.getHealth() + "/" + a.getMaxHealth() + " health");
maxTurns--;
battleturn++;
}
}
}
It won't compile if I set that chunk of code as a method, because it doesn't have the variables battleturn, maxturns, draw1, but if I put them in there, the amount of battle turns messes up.
Any ideas?
Java applications should be modular: each class fulfilling its own function, each method generally performing a single operation.
In a method you can use either class variables or its own local variables.
If you need several methods work with the same data, it should either be part of a class (instance and/or static variables) or passed to each method as parameters.
Make sure that you do not define class variables in a method. This will create local variables that will shadow class variables.
This might help you accomplish what you're trying to do.
private static void reportDamage(Character a,
Character b) {
System.out.println(a.name + " dealt "
+ a.combatRound(b) + " damage to " + b.name
+ "." + " Enemy has " + b.getHealth() + "/"
+ b.getMaxHealth() + " health.");
}
I suggest changing your combat method like this.
int battleturn = 0;
int maxTurns = 20;
// stop after 20 turns, or stop when one player has 0
// HP.
Scanner input = new Scanner(System.in);
try {
while (a.health > 0 && b.health > 0
&& battleturn < maxturn) {
battleturn++;
/* run a round of combat */
if (b.getFlee(a)) {
System.out.println(">>>>>>>>>>"
+ "The enemy has fled successfully"
+ "<<<<<<<<<<");
break;
} else {
System.out.println("Battle turn "
+ battleturn + ", <attack> or <flee>?");
boolean isFlee = false;
boolean isAttack = false;
String move = input.next();
for (;;) {
isAttack = "attack".equalsIgnoreCase(move);
isFlee = "flee".equalsIgnoreCase(move);
if (isFlee || isAttack) {
break;
}
System.out.println("Error: "
+ "Please input <attack> or <flee>.");
move = input.next();
}
if (isAttack) {
reportDamage(a, b);
reportDamage(b, a);
} else { // isFlee
if (a.getFlee(b)) {
System.out.println(">>>>>>>>>>"
+ "You have fled successfully"
+ "<<<<<<<<<<");
break;
} else {
// b is fleeing.
// reportDamage(a, b);
reportDamage(b, a);
}
}
}
}
} finally {
input.close();
}

count incrementer is wrong

My assignment calls for the line number to be display with the output. The professor suggested I do it with a counter and as seeing Java doesn't have an easy way to print out the current line number, I just created a counter as suggested. The below code is as follows:
//Count Increment
for (count = 1; count<= 5; count++)
{
}
//Display information
System.out.println(count + "." + " " + "Street:"+ " " + streetName + " " + "#" + streetNumber);
System.out.println(count + "." + " " + "Total Rooms:"+ " " + numofRooms);
System.out.println(count + "." + " " + "Total Area:"+ " " + totalSqFt + " sq.ft");
System.out.println(count + "." + " " + "The price per Sq. Ft is " + "$" + priceperSqFt);
System.out.println(count + "." + " " + "The estimated property value is "+ "$" + estimatedPropertyvalue);
However, the output starts the line counter at six as demonstrated here:
6. Street: park avenue #44
6. Total Rooms: 5
6. Total Area: 2500.0 sq.ft
6. The price per Sq. Ft is $120.4
6. The estimated property value is $301000.0
Removing the brackets doesn't help either. How can I get the line count to correctly state 1,2,3,4,5?
Please ask for clarification if needed!! Thanks.
Your prints are outside of the for loop. Your for loop ends when the counter is "6" which is when it exits the for loop. This variable doesn't change so the current value is "6",that is why it always prints "6" below on your code. If you want to print the line number for each instruction you could do something like this:
count = 0;
System.out.println(++count + "." + " " + "Street:"+ " " + streetName + " " + "#" + streetNumber);
"++count", you increment the variable the moment you write a line, in the first case it should print 1 then 2 etc. Hope this helped :)
The loop is not required cause you are only counting the lines one time each. If you put those lines in a loop that goes from 0 to 5 you will be counting each line 5 times. Since you only need to count each line ONE time you dont need the loop and just the simple increment I previously mentioned. Hope this clears out why the loop is not required
I assume that you have somewhere above this a line defining count:
int count;
So after the for loop, you've incremented count to 6 and then started printing with count left at the last incremented value from the for loop.
So, remove the for loop and just pre-increment the count variable for each line of ouput.
int count = 0;
//Display information
System.out.println( (++count) + "." + " " + "Street:"+ " " + streetName + " " + "#" + streetNumber);
...
class Print{
static int lineno = 0;
private int static getLineNo(){
lineno = lineno + 1;
return lineno;
}
}
//Display information
System.out.println(Print.getLineNo() + "." + " " + "Street:"+ " " + streetName + " " + "#" + streetNumber);
System.out.println(Print.getLineNo() + "." + " " + "Total Rooms:"+ " " + numofRooms);
System.out.println(Print.getLineNo() + "." + " " + "Total Area:"+ " " + totalSqFt + " sq.ft");
System.out.println(Print.getLineNo() + "." + " " + "The price per Sq. Ft is " + "$" + priceperSqFt);
System.out.println(Print.getLineNo() + "." + " " + "The estimated property value is "+ "$" + estimatedPropertyv

Categories

Resources