count incrementer is wrong - java

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

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.

(Noob) Quick help on output statement

if (gpa < 2.0)
System.out.println("The student " +first +last + " is not graduating.");
This is my output statement. However the result I get is
The student BobPaul is not graduating.
How do I add a space between the +first and +last so that way my output statement looks like
The student Bob Paul is not graduating.
the correct answer is
System.out.println("The student " +first + " " + last + " is not graduating.");
It is simple. Just concatenate a string " " with empty space in between.
System.out.println("The student " +first + " " + last + " is not graduating.");

Why is the char value transforming during the output?

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
###
###
###

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();
}

Displaying an array in a TextView in java

hi i made a program that counts the elements in an array and i done it already. Now i want to display the result in a textView.. I want to display it this way...
1 appeared 2times
2 appeared 1times
3 appeared 1times
6 appeared 1times
this is my code..
The last element only displays in the textView..
please help me..Thanks
String []values = ( input.getText().toString().split(","));
Arrays.sort(values);
int c=1,i=0,range=4;
while(i<values.length-1){
while(values[i]==values[i+1]){
c++;
i++;
}
jLabel7.setText(values[i] + " appeared " + c + " times");
c=1;
i++;
if(i==values.length-1)
jLabel7.setText(values[i] + " appeared " + c + " times");
}
Try this:
jLabel7.setText(jLabel7.getText() + "\n" + values[i] + " appeared " + c + " times");
Att:
If u are using swing componentes, is not a TextView but JLabel, or u are working for Android?
update your code to:
String []values = ( input.getText().toString().split(","));
Arrays.sort(values);
int c=1,i=0,range=4;
while(i<values.length-1){
while(values[i]==values[i+1]){
c++;
i++;
}
jLabel7.setText(jLabel7.getText() + "\n" + values[i] + " appeared " + c + " times");
c=1;
i++;
if(i==values.length-1)
jLabel7.setText(jLabel7.getText() + "\n" + values[i] + " appeared " + c + " times");
}
append all the values into a single String object and then use the setText method to display the string

Categories

Resources