JAVA Square Footage Calculation [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have to Write a program in Java that will take the dimensions of two different homes and calculate the total square footage. The program will then compare the two values and print out a line of text appropriately stating whether it is larger or smaller than the other one.
I am not sure where to even begin. I am new to Java and have only done a Hello World

The first thing you have to do is take input from your user of the length and width of the object. Then you must calculate the sqr ft using the formula :
Length * Width = # of Sqr ft
If you want to do this to two houses you will just need to take two inputs for the second house of the length and width and display that homes total area the same way we did to the first house.
import java.util.*;
public class SqrFoot {
public static void main(String[] args) {
//creates a scanner object
Scanner scan = new Scanner(System.in);
//takes input
System.out.println("Enter the length : ");
double length = scan.nextDouble();
System.out.println("Enter the width : ");
double width = scan.nextDouble();
//calculates and displays answer
System.out.println(length*width + " Sqr ft");
}
}

Does this program take input from the user? If it does, you'll want to use a Scanner to accept user input, as such:
Scanner input = new Scanner(System.in);
You can then use the nextDouble() method to input the house dimensions, like so:
double length1 = input.nextDouble();
Then you can calculate the area of each house:
double area1 = length1 * width1;
Finally, you can use an if-else block to compare the two areas. Here's an example of how you could do it:
if (area1 > area2) {
System.out.println("House 1 is larger than house 2.");
} else if (area1 < area 2) {
System.out.println("House 1 is smaller than house 2.");
} else {
System.out.println("House 1 is the same size as house 2.");
}

This sounds like homework, so I'm not going to do it for you, but I will help you with syntax and let you put it all together.
To store a number you need to declare a variable. Variables come in all different types. There is a:
String Which like the name suggests, is a string of characters like "Hello World". To declare a String named hello that contains "Hello World", type the following:
String hello = "Hello World";
Some important things: String is capitalized. You will learn why later, but just remember it for now. The stuff you were storing in hello started with and ended with a ". As you will see, this is only the case for Strings. Finally, like you may already know, almost every line ends with a ;.
char Which is short for character and stores a single letter (or symbol, but worry about that later). To store the letter 'P' in a variable named aLetter, type the following:
char aLetter = 'P';
Some important things: char like the rest of the variable names I will tell you about, is lowercase. Also, a char starts and ends with an '. Next, I stored a capital P which in Java's mind is completely different than a lowercase p (the point I'm trying to make is everything in Java is case sensitive). Finally, even though my variable name aLetter is two words, I didn't put a space. When naming variables, no spaces. ever.
int Which is short for integer. An int stores a whole number (no decimal places) either positive or negative (The largest number an int can hold is around 2 billion but worry about that later). To store the number 1776 in an int named aNumber, type the following:
int aNumber = 1776;
Some important things: this is pretty straightforward, but notice there aren't any "'s or ''s. In Java "1776" is NOT the same as 1776. Finally, I hope you are noticing that you can name variables whatever you want as long as it isn't a reserved word (examples of reserved words are: int, String, char, etc.)
double Which is pretty similar to int, but you can have decimal points now. To store the number 3.14 in a double named aDecimal, type the following:
double aDecimal = 3.14;
boolean Which is a little harder to understand, but a boolean can only have 2 values: true or false. To make it easier to understand, you can change in your head (not in the code) true/false to yes/no. To store a boolean value of true in a variable named isItCorrect, type the following:
boolean isItCorrect = true;
There are tons more, but that is all you have to worry about for now. Now, lets go to math. Math in Java is pretty self explanatory; it is just like a calculator except times is * and divide is /. Another thing to make sure of, is that you are storing the answer somewhere. If you type 5-6; Java will subtract 6 from 5, but the answer wont be saved anywhere. Instead, do the following:
int answer = 0;
answer = 5-6;
Now, the result (-1) will be saved in the int named answer so you can use it later.
Finally, we have decision making. In computer science, you change sentences like "If the person's age is at least 21, let them into the bar. otherwise, don't let them in." In decision making, you need to turn all of your questions into yes/no questions. When you need to decide a yes/no question, use what are called if statements. The way to write if statements are a little weird: you write the word if then you ask your question in parentheses and you don't but a ;. Instead you put a set of curly braces {}, inside which you write your code that will run if the question in the if statement is true. For example, the bar example above would be, in code, the following:
int age = 25;
boolean letHimIn = false;
if(age>=21)
{
letHimIn = true;
}
Now, the question is, how do you ask a question. To do so, you use the following: <,>,<=,>=,==,!=. These are called comparators because they the things on either side of them. They do the following: < checks if the number on the left is less than the number on the right, > checks if the number on the left is greater than the number on the right, <= checks less than or equal, >= checks greater or equal, == checks if the two numbers are equal, and != checks if the two numbers are not equal. So if(age>=21) asks the question, is the number stored in age greater or equal to 21? If so, do the code in curly braces below. If not, then skip the code. As one more example, the code checks if age is exactly equal to 21 and if so, set letHimInTheBar to true.
int age = 25;
boolean letHimInTheBar = false;
if(age==21)
{
letHimInTheBar = true;
}
Since age is equal to 25 not 21, the code to make letHimInTheBar true never ran which means letHimInTheBar. The final thing to know about decisions is you can use a boolean variable to ask a question directly. In the following example, we are only letting people whose age is NOT equal to 30 into the bar and if we let them into the bar we will print "Welcome to the bar." and if we didn't then we will print "Stay away.". As a reminder ! in Java means not. Meaning that it will flip true to false and false to true.
int age = 25;
int badAge = 30;
boolean letHimIn = false;
if(age!=badAge)
{
letHimIn = true;
}
if(letHimIn)
{
System.out.println("Welcome to the bar.");
}
if(!letHimIn)
{
System.out.println("Stay away.");
}

Related

Why is there no output from the While loop in my code, despite everything else working?

I made this program in java, on the BlueJ IDE. It is meant to take a number in the decimal base and convert it into a base of the users choice, up till base 9. It does this by taking the modulus between two numbers and inserting it into a string. The code works till the input stage, after which there is no output. I am sure my maths is right, but the syntax may have a problem.
My code is as follows:
import java.util.*;
public class Octal
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int danum = 0;
int base = 0;
System.out.println("Please enter the base you want the number in (till decimal). Enter as a whole number");
base=in.nextInt(); //This is the base the user wants the number converted in//
System.out.println("Enter the number you want converted (enter in decimal)");
danum=in.nextInt(); //This is the number the user wants converted//
while ( danum/base >= base-1 && base < danum) {
int rem = danum/base; //The number by the base//
int modu = danum % base;//the modulus//
String summat = Integer.toString(modu);//this is to convert the integer to the string//
String strConverted = new String();//Making a new string??//
StringBuffer buff = new StringBuffer(strConverted);//StringBuffer command//
buff.insert(0, summat); //inserting the modulus into the first position (0 index)//
danum = rem;
if ( rem <= base-1 || base>danum) {//does the || work guys?//
System.out.println(rem + strConverted);
}
else {
System.out.println(strConverted);
}
}
}
}
I am very new to Java, so I am not fully aware of the syntax. I have done my best to research so that I don't waste your time. Please give me suggestions on how to improve my code and my skill as a programmer. Thanks.
Edit (previous answer what obviously a too quick response...)
String summat = Integer.toString(modu);
String strConverted = new String();
StringBuffer buff = new StringBuffer(strConverted);
buff.insert(0, summat);
...
System.out.println(strConverted);
Actually, strConverted is still an empty string, maybe you would rather than display buff.toString()
But I don't really understand why making all of this to just display the value of modu. You could just right System.out.println(modu).
I assume that you want to "save" your value and display your whole number in one time and not each digit a time by line.
So you need to store your number outside of while loop else your string would be init at each call of the loop. (and print outside)
So, init your StringBuffer outside of the loop. you don't need to convert your int to String since StringBuffer accept int
http://docs.oracle.com/javase/8/docs/api/java/lang/StringBuffer.html#insert-int-int-
(You could even use StringBuilder instead of StringBuffer. It work the same except StringBuffer work synchronized
https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuilder.html)
Your if inside the loop is a specific case (number lower than base) is prevent before the loop since it's the opposite condition of your loop. (BTW : rem <= base-1 and base>danum are actually only one test since rem == danum at this place)
so :
StringBuffer buff = new StringBuffer();
if(base > danum) {
buff.append(danum);
} else {
while (danum / base >= base - 1 && base < danum) {
int rem = danum / base;
int modu = danum % base;
buff.insert(0, modu);
danum = rem;
}
if(danum > 0) {
buff.insert(0, danum);
}
}
System.out.println(buff.toString());
I would also strongly recommand to test your input before running your code. (No Zero for base, no letters etc...)
2 Things
do a lot more error checking after getting user input. It avoids weird 'errors' down the path
Your conversion from int to String inside the loop is wrong. Whats the whole deal summat and buff.... :: modifying the buffer doesnt affect the strConverted (so thats always empty which is what you see)
try to get rid of this. :)
error is logic related
error is java related
Your code has the following problems:
Firstly, you have declared and initialized your strConverted variable (in which you store your result) inside your while loop. Hence whenever the loop repeats, it creates a new string strConverted with a value "". Hence your answer will never be correct.
Secondly, the StringBuffer buff never changes the string strConverted. You have to change your string by actually calling it.
You print your result inside your while loop which prints your step-by-step result after every repetition. You must change the value of strConverted within the loop, nut the end result has to be printed outside it.

Hangman that saves wrong guesses in array and prints them before each guess. also prints gameboard with "_" and correct guesses

so I've been studying Java for about 3 months and I am supposed to do a Hangman code using only arrays, loops, and if statements. the word to be guesses is read from another file and saved as a string. I have to be able to save the wrong guesses in an array. and after each guess print all the wrong guesses so far, as well as the gameboard with underscores for not guessed letters and the correct guesses of course in their place. here is my code so far :
for(int l = 0; l<wordlength;l++)
{
System.out.print("_");
}
System.out.println();
System.out.println("WRONG: ");
for(int c = 0; c<numofGuesses;c++)
{
System.out.println();
System.out.print("GUESS"+guessN+"/"+numofGuesses+": ");
char guess1=in.next().charAt(0);
char guess = Character.toUpperCase(guess1);
guessN = guessN+1;
for (int j = 0; j<wordlength;j++)
{
if (guess==guessword.charAt(j))
{
System.out.println("Great guess!");
System.out.print (guessword.charAt(j));
}
else
{
System.out.print("_");
WRONG[u]=guess;
u++;
}
}
if you guess A it prints correctly "A___" but then if you guess B after instead of printing "AB__" (the word to guess is ABLE) i get "B__" also the wrong array is not storing and printing all the wrong guesses each time. please help I've been trying for 5 days and that's all I did the entire day today and I couldn't get past this.
Because this sounds a lot like a homework assignment, I will give directions for solving this, but not provide a full working solution. Hopefully, seeing how one could1 go about approaching such a problem is enough of a step in the right direction to be able to solve it yourself.
Let's first think about what we need to do.
Read a word that needs to be guessed, say String toBeGuessed.
You did this. ✔
Keep track of the characters the player has guessed so far.
Keep track of the number of turns a player has gotten.
Keep track of if the word has been guessed (player won!).
Say that the number of guesses a player can make is fixed. This can be modeled using a constant:
/**
* Number of guesses a player can take.
*/
public static final int NUM_GUESSES = 10;
Now let's think about the main logic of our hangman game. It is good to first think about the structure of your program and only later actually implement it. When thinking of the program structure, we don't bother with specifics of the programming language of your choice yet. In pseudocode, it would be something like the following, maybe (let's indicate what you already have with ✔).
for turn from 1 upto NUM_GUESSES do ✔
show player what they guessed so far
show the gameboard
ask player for their new guess ✔
save player's guess and update internal state
check if the player won, let them know if they did
if player did not win
let them know
Right. So, we need to somehow store the guesses that a player made. Every guess is a character, and we know there will be at most NUM_GUESS guesses in total. A good option (and one that is suggested by your exercise) is an array!
/**
* Characters that have been guessed so far.
*/
private char[] guessed;
This can be initialized as follows, since we know the maximum number of guesses:
this.guessed = new char[NUM_GUESSES];
This gives us an array of NUM_GUESSES characters that are initialized to 0 (see here). Since users won't guess that character, we can use it to represent guesses that have not been done yet. Alternatively, we can keep track of the current turn of the player in a separate variable. Your choice!
In the following, I will not keep track of the current turn in a separate variable, just to show more of arrays and loops. It might be a fun exercise to change this to using an int turn variable!
show player what they guessed so far
Alright, this should be fairly straightforward now. We basically need to print the part of the guessed array that is not 0. That can be done using a loop, like so for example:
System.out.print("You so far guessed: ");
for (int i = 0; i < guessed.length; ++i) {
if (i > 0) {
System.out.print(", ");
}
if (guessed[i] != 0) {
System.out.print(guessed[i]);
} else {
break; // stop the loop as soon as we run into a 0
}
}
System.out.println(".");
This will print something like You so far guessed: a, b, c. when the player guessed those characters. See how we only print the comma when some other character was printed before?
show the gameboard
The next point of the program structure is trickier to get right. Let's think a bit about structure again.
for each character in toBeGuessed
if the character has been guessed
print it
else
print an underscore
Looping over every character of a word can be done as follows.
int length = toBeGuessed.length();
for (int i = 0; i < length; ++i) {
char character = toBeGuessed.charAt(i);
// do something with character here
}
How do you find if a character has been guessed yet? Well, by checking if it is stored in the guessed array. This again can be done using a loop. That loop will be very similar to the one we have written above, when showing what the player guessed so far. I think you should be able to figure that one out.
save player's guess and update internal state
We move on to the next point of the program structure. Say that we have a char guess that the player guessed. We need to store this in our array guessed. Where? Well, at the first open spot, that seems a reasonable choice. To find that one, let's use a loop again, and break the loop when we have found an open spot.
for (int i = 0; i < guessed.length; ++i) {
if (guessed[i] == 0) {
guessed[i] = guess;
break;
}
}
check if the player won, let them know if they did
What we need to know in order to see if the player won, is simply if the number of characters they guessed right is equal to the number of characters in toBeGuessed. You could modify the loop for showing the gameboard to not print characters, but count correct ones. Then at the end compare to toBeGuessed.length() and if they are equal, the player won.
if player did not win, let them know
This should be fairly easy, if you got the previous point working.
When you did all the above and stitched it together, you should have a working version of hangman. Your very own, something to be proud of!
Some tips and tricks:
you can implement most of the points described above as separate methods;
when you do so, you can write one main method that calls the other methods (this will make it easier to read your own code and make changes to it);
try to put as little code as possible in the main method.
Here is a little template that you can start from.
import java.io.PrintStream;
import java.util.Scanner;
public class HangMan
{
/** Number of guesses a player can take. */
public static final int NUM_GUESSES = 10;
/** Word to be guessed in a game of hangman. */
private String toGuess;
/** Letters that have been guessed so far. */
private char[] guessed;
/**
* Construct a new game of hangman, ready to be played.
*/
public HangMan(String toGuess)
{
this.toGuess = toGuess;
this.guessed = new char[NUM_GUESSES];
}
// your other methods go here
/**
* Read guesses from given input and print results to given output.
* Continues until guesses have run out, or word was guessed.
*/
public void play(Scanner in, PrintStream out)
{
for (int round = 0; round < NUM_GUESSES; ++round) {
showGuessedSoFar(out);
showGameBoard(out);
char guess = askGuess(in, out);
saveGuess(guess);
if (hasPlayerWon()) {
out.println("You won!");
return;
}
}
// at this point, player ran out of guesses and hence lost
out.println("You lost...");
}
/**
* The bit that runs our hangman game.
*/
public static void main(String[] args)
{
// read word to guess from arguments, with a default value
// you would probably insert your "read word from file" code here
HangMan game = new HangMan(args.length >= 1 ? args[0] : "ABLE");
// play a game, using system input and output
game.play(new Scanner(System.in), System.out);
}
}
Good luck!
TL;DR. Trying to teach one how to think about a problem and how to write code that executes the solution one thought of. Features some example code with arrays and loops.
1 This is only one possible solution, there are always many ways to solve a given problem.

Validating user input in java?

My guessing game takes either 5, 10, or 20 guesses from a user and they are supposed to try to guess a random number chosen by the computer. Everything in my code is working except this: when the code asks the user whether they want 5, 10, or 20 guesses, if the user were to enter 15, for example, which is not one of the options, it goes on and starts asking for their guesses. I need some type of validation that will make sure they enter one of the options. I'm not sure where or how to include this in the correct way since I am new to programming. I've tried several different ways but get errors for all. What I need is if the user puts a number that is not one of the options, it should just ask them again until they input one of the options. Can someone show me how I should do this?
First of all if (answer.length() ==3) makes no sense.
Maybe you meant:
if(answer.equals("yes"))
Besides, to accomplish what you want I would use a Set containing the valid guesses numbers. It is scalable and makes much more sense than checking against multiple values in an if clause. It will look like this:
Set<Integer> validNumberOfGuesses = new HashSet<Integer>(Arrays.asList(5, 10, 20));
int numberOfGuesses = scan.nextInt();
while (!validNumberOfGuesses.contains(numberOfGuesses)) {
/* ask again */
System.out.println(numberOfGuesses + " is not a valid number of guesses, please try again");
numberOfGuesses = scan.nextInt();
}
Take input from the user inside a loop. For example:
System.out.print("How many guesses would you like? (5, 10, 20)");
do {
int numberOfGuesses = scan.nextInt();
//on correct guess, break out of the loop
if(numberOfGuesses == 5 || numberOfGuesses == 10 || numberOfGuesses == 20)
break;
System.out.print("Please enter a guess having one of these values (5, 10, 20)");
} while (true);
Unless the user, enters one of the three values, he/she will kept being prompted to enter a correct guess value.
Java has the continue keyword that jumps to start of the current loop when run. See The Continue Statement documentation.
Once you have your user input you can do something like
if (numberOfGuesses != 5 && numberOfGuesses != 10 && numberOfGuesses != 20) {
continue; // jumps to start of while loop block, without running conditional
}
When you receive the "numberOfGuesses" you should check the value of that number before moving on. Otherwise you just move on in your code because you don't actually validate the number.
It may be a good idea to creat a function that returns a boolean value and then you can check the number there.
boolean isValidOption(int number)
In the function you want to perform some comparison and validate. Since you have three options you can opt for something like
if (number == 5 || ... )
You can consider how you'll verify the value as there are many ways. Just compare with valid numbers you know you want, you can do some if statements, or place the numbers in an array and compare the value while iterating through the array, and so on. Hope that helps you get started and happy coding!
Edit: Lastly I should have mentioned, but you need to consider the flow of your code. A loop of somesort like while(!isValidOption()) for your check should be use. Loop around the instructions until the user enters a valid option. You need to consider order of operations here in your code and understand the computer doesn't think for you. It does what you tell it, so understand what you are trying to tell it here. I want to step into my game, if and only if, the condition of isValidOption is met for example.
What you need to do is to stay in the loop until you get input that satisfy your demands for example you can use the following function
private int getNumberOfGuesses(Scanner scan) {
int numberOfGuesses;
boolean numberOfGuesesIsValid;
do {
System.out.println("How many guesses would you like? (5, 10, 20)");
numberOfGuesses = scan.nextInt();
numberOfGuesesIsValid = numberOfGuesses == 5 || numberOfGuesses == 10 || numberOfGuesses == 20;
if (!numberOfGuesesIsValid) {
System.out.print("Wrong option !!!");
}
} while (!numberOfGuesesIsValid);
return numberOfGuesses;
}
you can write your code inside a loop to make sure the value is either 5,10 or 20
while(numberOfGuesses!=5||numberOfGuesses!=10||numberOfGuesses=!20);
and the condition if(answer.length()==3 can cause errors. it means it will work every time the input is of length 3,even "noo"

Multiplying certain value in array based on certain condition in another array and storing value in a new array?

I am creating a program based on arrays that helps calculate the stipend for a number of tutors who assist students with their skills. The program takes in the number of tutors, then proceeds with the tutors name, asks how many students that tutor has assisted and then asks what degree level the tutor has (BS, MS, PhD). The tutor will be payed a different amount of money based on the degree level they have. So if the first tutor (Bill) has taught 5 students and has a PhD (which is $20 per student), then he will be payed $100.00 and, so on and so forth for the other tutors (MS = 15.00 per student, BS = 9.50 per student).
My problem is that when I have entered all the data, I just get 0.0 for the pay column and 0.0 for the total stipend. What I am trying to do is based on the degree entered in the degree array, you multiply the taught array (aka the number of students taught) by the amount of money per student, and then store that number in a new array called stipend. I have re-arranged, re-named, and done about everything I can think of to try and get the stipend to show up but I am running out of options and becoming very frustrated. So if anyone could please help me it would be greatly appreciated.
for(int pay=0; pay<numOfTutors; pay++) {
if (degree[pay] == "BS") {
stipend[pay] = taught[pay] * 9.50;
}
else if (degree[pay] == "MS") {
stipend[pay] = taught[pay] * 15.00;
}
else if (degree[pay] == "PhD") {
stipend[pay] = taught[pay] * 20.00;
}
sum+=stipend[pay];
}
The problem is that you are using the == operator, instead of the .equals() method, to check for string equality. You should change the lines of the form
degree[pay] == "some_string"
to
degree[pay].equals("some_string")
Or, if you want case insensitive matching, you could use
degree[pay].equalsIgnoreCase("some_string")
Here's what's going on: when you write degree[pay] = "some_string", you are checking for reference equality, which will not work for what you are doing, because a constant string and a generated string will not have equal references. The .equals() method will check for equal values, which is what you want.
Use String#equals to compare String content. The == operator is used to compare Object references. Because the references of the 2 values being compared are not equals, then none of the pay adjustments for the array stipend take place. Replace
if (degree[pay] == "BS") {
with
if (degree[pay].equals("BS")) {
Similarly for "MS" and "PhD" String checks.

if statement with integers [duplicate]

This question already has answers here:
Why does my if condition not accept an integer in java?
(7 answers)
Closed 3 years ago.
I'm new at Java. I'm looking for some help with homework. I wont post the full code I was doing that originally but I dont think it will help me learn it.
I have a program working with classes. I have a class that will validate a selection and a class that has my setters and getters and a class that the professor coded with the IO for the program (it's an addres book)
I have a statement in my main like this that says
//create new scanner
Scanner ip = new Scanner(System.in);
System.out.println();
int menuNumber = Validator.getInt(ip, "Enter menu number: ", 1, 3);
if (menuNumber = 1)
{
//print address book
}
else if (menuNumber = 2)
{
// get input from user
}
else
{
Exit
}
If you look at my if statement if (menuNumber = 1) I get a red line that tells me I cannot convert an int to boolean. I thought the answer was if (menuNumber.equals(1)) but that also gave me a similar error.
I'm not 100% on what I can do to fix it so I wanted to ask for help. Do I need to convert my entry to a string? Right now my validator looks something like:
if (int < 1)
print "Error entry must be 1, 2 or 3)
else if (int > 3)
print "error entry must 1, 2, or 3)
else
print "invalid entry"
If I convert my main to a string instead of an int wont I have to change this all up as well?
Thanks again for helping me I haven't been diong that great and I want to get a good chunk of the assignment knocked out.
if (menuNumber = 1)
should be
if (menuNumber == 1)
The former assigns the value 1 to menuNumber, the latter tests if menuNumber is equal to 1.
The reason you get cannot convert an int to boolean is that Java expects a boolean in the if(...) construct - but menuNumber is an int. The expression menuNumber == 1 returns a boolean, which is what is needed.
It's a common mix-up in various languages. I think you can set the Java compiler to warn you of other likely cases of this error.
A trick used in some languages is to do the comparison the other way round: (1 == menuNumber) so that if you accidentally type = you will get a compiler error rather than a silent bug.
This is known as a Yoda Condition.
In Java, a similar trick can be used if you are comparing objects using the .equals() method (not ==), and one of them could be null:
if(myString.equals("abc"))
may produce a NullPointerException if myString is null. But:
if("abc".equals(myString))
will cope, and will just return false if myString is null.
I get a red line that tells me I cannot convert an int to boolean.
Thats because = is an assignment operator. What you need to use is == operator.
A single equal sign is assignment: you assign value to a variable this way. use two equal signs (==) for comparison:
if ($menuNumber = 1) {
Update: forgot dollar sign: $menuNumber

Categories

Resources