Stuck on a part in a java project - java

"If a player's playerID ends in 00 to 49, this person is on the “lucky list”; however if the playID ends in 50 to 99, this person is on the “normal list”."
//Players ID, is what i have so far
System.out.println("Please enter the player’s ID (8 digits): ");
int playerId = input.nextInt();
//When i use if else statements i can select for certain cases. for example
if (playerId % 50)
normalList;
if (playerId % 3)
luckyList;
These are two example that i can think of. I assume there is a shorter and more logical way to do this but i dont have a clue how.

Be more clear on what normal list; and what luckyList; are. You say lists, so I am assuming you are using array or java.util.ArrayList to store your objects.
What I would do is to the effect of this:
`//Players ID, is what you have so far.
int playerID;
System.out.println("Please enter the player’s ID (8 digits): ");
playerID=input.nextInt();
System.out.println("Please re-enter the player's ID(8 digits):");
String IDword=input.next(); //can also use nextLine here
//now what happens is I have made a string version and an int version of your ID. Now, using charAt, I can access the last two values.
if(IDword.charAt(IDword.length()-2)=='4')
{
LuckyList.add(playerID);
}
if(IDword.charAt(IDword.length()-2)=='3')
{
LuckyList.add(playerID);
}
if(IDword.charAt(IDword.length()-2)=='2')
{
LuckyList.add(playerID);
}
if(IDword.charAt(IDword.length()-2)=='1')
{
LuckyList.add(playerID);
}
if(IDword.charAt(IDword.length()-2)=='0')
{
LuckyList.add(playerID);
}
else
normalList.add(playerID);`
This detects the second to last digit- if it is 4 or less, it adds to luckyList. Else, it will add to normalList.
You may just want to add something indicating that the data is always 8 digits (that just being if(IDword.size()==8) do the following.

Related

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"

Breaking out" of a while loop still executing whats inside?

The purpose of this program is to take in positive integers and once the sentinel value (-1) is hit the program will return the 2 lowest numbers. My program works, but in some scenarios it doesn't. for example if I enter 10,15,20,-1 the program will result in 10 rather than 10 and 15. Here is my program:
public class Small{
public static void main(String [ ] args){
int number;
number=IO.readInt();
int lowest=number;
int lowest2=number;
while (number!=-1){
number=IO.readInt();
if(number>0){
if(number<lowest && number!=-1){
lowest=number;}
else{if((number<lowest2||!(number>=lowest2))&& number!=-1){
lowest2=number;}
}
}
}
IO.outputIntAnswer(lowest);
IO.outputIntAnswer(lowest2);
}
}
The main problem with your code is that you set lowest and lowest2 to the first value you enter. If all the other numbers you enter are higher than the first number, it will never be able to find anything lower.
With your example, the first number is 10 which you assign to lowest and lowest2. When you enter 15, it's not lower than 10, so neither variable can be reset. Same with 20.
You've also got a lot of redundant checks in your if-statements.
public class Small {
public static void main(String [ ] args) {
int number;
int lowest = Integer.MAX_VALUE;
int lowest2 = Integer.MAX_VALUE;
while (number!=-1) {
number=IO.readInt();
if (number > 0) {
if(number < lowest) {
lowest=number;
}
else if (number < lowest2) {
lowest2=number;
}
}
}
}
IO.outputIntAnswer(lowest);
IO.outputIntAnswer(lowest2);
}
The problem is with your logic flow of the program. Here's what the code is doing:
Read in one number, store in both lowest and lowest2.
Go through loop to read in more numbers
2a. If the number is positive, check against lowest.
2a1. If the read in value is lower than lowest, change lowest's value to the read in value.
2a2. Otherwise, if the read in value is lower than lowest2, change lowest2's value to the read in value. Only do this if lowest was not changed.
2b. If the read in value is -1, end the loop.
2c. If the read in value is negative but not -1, continue but don't add the number to lowest or lowest2.
Print out the values for lowest and lowest2.
If you see the error, it's in 2a2. This is linked to the fact that your setup before the while loop is formatted as you did: you made both lowest and lowest2 that first value.
This code would normally run correctly, except for one instance: what if that first value were to be the smallest positive value you entered, with all other values greater than it? lowest2 would be set to that value, and you're checking to see if any other values are smaller than it (which they're not, because they're all going to be greater than it).
Tips for when you're coding:
1) Attempt to develop a logical thinking mentality. Think through how you want to create algorithms for your program. Make sure you don't run into any situations where your program does not run the way you want it to, like in this case (this is called a logic error).
2) Run through your programs by hand when you're finished coding, or after you've run it and got an error. Step through every line of your code, and try to see where and why your code isn't working the way you want it to. Or have someone else see, like a fellow programmer. Sometimes, even the best eyes do not catch their own mistakes.
EDIT:
There are various ways to solve this particular problem. One way is to do what Seeker and Rick did:
1) Set both values to the largest possible Integer value, and thus all values entered will be lower than the first values.
2) Ask for the first two inputs at the beginning before the loop, and check them against each other to set the first two lowest values.
However, I believe there are certain things to watch out for when you're doing something like this. These should all be outlined before you code, of course.
1) What if the user is entering only one or zero valid values? Seeker's method wouldn't work, unless he checks that the first/second value is negative/-1. Rick's method wouldn't work either because at least one of the lowest/lowest2 values would still be that max Integer value.
2) What if there were no positive values entered before the -1? This is similar to number 1, and your ints would be null.
You can certainly use Seeker's and Rick's algorithms, but you should check for these conditions if you use them.
import java.util.Scanner;
public class Small {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter Number");
int lowest = scanner.nextInt();
System.out.println("Enter Number");
int lowest2 = scanner.nextInt();
if (lowest > lowest2) {
int t = lowest;
lowest = lowest2;
lowest2 = t;
}
while (true) {
System.out.println("Enter Number");
int number = scanner.nextInt();
if (number == -1)
break;
if (number < lowest2 && number < lowest) {
lowest = number;
} else if (number < lowest2) {
lowest2 = number;
}
}
System.out.println("lowest:" + lowest);
System.out.println("lowest2:" + lowest2);
scanner.close();
}
}

JAVA Square Footage Calculation [closed]

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.");
}

Cannot use arrays or foreach loops to iterate over list of data and print out only certain values

The Prompt:
A program that accepts a candy name (for example, “chocolate-covered blueberries”), price per pound, and number of pounds sold in the average month, and displays the item’s data only if it is a best-selling item. Best-selling items are those that sell more than 2000 pounds per month.
b. A program that accepts candy data continuously until a sentinel value is entered and displays a list of high- priced, best-selling items. Best-selling items are defined in Exercise 2a. High-priced items are those that sell for $10 per pound or more.
Here is an example of a good design in operation:
High-priced, Best-selling Candy
Fudge $12.50 4500 lbs
Vanilla Creme $13.75 2200 lbs.
Fudge, 12.50, 4500 Jawbreakers, 6.50, 5500 Chocolate, 14.00, 790 Butterscotch, 9.50, 4500 Vanilla Creme, 13.75, 2200
Item that sold most pounds: Jawbreakers
but the problem I am having is that my teacher is not letting me use for loops, or arrays. And I do not want to define multiple instances of the same variable because it is finite to a certain amount.... What would be the most efficient way of doing this?
start
// Declarations
num QUIT = "Y";
final String HEADING = "High Priced, Best Selling Candy" + "\n" + "\n";
final String HSPS = candyName + " " + candyPrice + " " + candySold + " ";
final String MOSTSOLD = "Item that sold the most pounds is "
while <> QUIT;
enterCandy();
printHighPriceBestSelling();
printSoldMostPounds();
endwhile;
stop
entercandy()
String candyName = "poop";
double candyPrice = 0.0;
double candyWeight = 0.0;
int candySold = 0;
output "Please enter name of candy.";
input candyName;
output "Please enter candy price.";
input candyPrice;
output "Please enter pounds sold.";
input candySold;
printHighPriceBestSelling()
if(candySold > 2000 && candyPrice > 10)
{
output HEADING;
output HSPS;
}
else
{
output "There were/are no best selling, high priced candy!"
}
printSoldMostPounds();
//There is no basis for comparison.
There are only two ways of doing this. Create lots of different, artbitrary, and predefined variables to be filled by the loop until they are overwritten. Lets say 10. Or create an array. I am sure there is an overly complex way of doing it with nested if/switch/while loops, but why teach us/force us to use the ugly inefficient way?
output "MOSTSOLD ";
I'm assuming that, besides arrays, you're teacher isn't allowing you to use any standard Collection objects.
You could always just build your own LinkedList of entered candy orders--it's ugly, but it would work. A single "link" in the chain would look like this
public class CandyOrderLink {
private String candyName;
private Double candyPrice;
private Double orderAmount;
private CandyOrderLink nextOrderLink;
public CandyOrderLink(String candyName, Double candyPrice, Double orderAmount) {
this.candyName = candyName;
this.candyPrice = candyPrice;
this.orderAmount = orderAmount;
}
public CandyOrderLink getNextLink() {
return nextOrder;
}
public void setNextLink(CandyOrderLink nextOrderLink) {
this.nextOrderLink= nextOrderLink;
}
public String getCandyName() {
return candyName;
}
public Double getCandyPrice() {
return candyPrice;
}
public Double getOrderAmount() {
return orderAmount;
}
}
Not sure if I'm quite grasping the point of the assignment, but using a list data-structure to keep track of all orders will work. Just build a link for each entry (candyName, price, amount) and set that link as the next link of the previous one. At the end of input, iterate through the list by repeatedly calling getNextLink() on each link and printing information (if appropriate). Here is Wikipedia's article on linked lists: http://en.wikipedia.org/wiki/Linked_list
From the problem's description, I see no need to store the data entered so that it can be sorted. Both a and b state simple conditions for displaying a candy: greater than 2,000 pounds and at least $10/lb. You can print each entry immediately after it is entered.
However, your example output implies that you must pick the single best-selling candy which contradicts the description. Which is correct?

Checking values in boolean array (Java)

I am having som slight difficulties with the following problem.
I have initialized a boolean array called numberArray with 31 indexes. The user is supposed to enter 5 digits between 1 and 30, and each time a digit is entered, the program is supposed to set the proper index to true. For instance, if I enter 5 then:
numberArray[5] = true;
However, if the user enters the value 5 a second time, a message should be given to the user that this number has already been entered, and so the user has to choose a different value. I have tried to create a loop as follows:
public void enterArrayValues() {
for(int i = 1; i < 6; i++) {
System.out.print("Give " + i + ". number: ");
int enteredNumber = input.nextInt();
while (numberArray[enteredNumber] = true) {
System.out.println("This number has already been chosen.");
System.out.print("Give " + i + ". number again: ");
enteredNumber = input.nextInt();
}
numberArray[enteredNumber] = true;
}
}
The problem is that when I run the program, I automatically get the message "The number has already been chosen" no matter what I enter. Even the first time I enter a number. I don't get this. Isn't all the values in the boolean array false by default?
I would greatly appreciate it if someone could help me with this!
while (numberArray[enteredNumber] = true) {
make that
while (numberArray[enteredNumber] == true) {
or change to
while (true == numberArray[enteredNumber]) {
or simply drop the ==true
while (numberArray[enteredNumber]) {
while (numberArray[enteredNumber] = true)
is an assignment, use the == operator or simply while (numberArray[enteredNumber]).
I know its hard to get into while you are still learning, but the earlier you start coding in an IDE the better off you will be. This is one tiny example of something an IDE will warn you about.
Change the while line to:
while (numberArray[enteredNumber]) {
Because mistakenly entering = instead of == is a common mistake, some people always code this type of statement in the following manner:
while (true == numberArray[enteredNumber]) {
With this format, if you use = instead of ==, you will get a compiler error.
Also, if you use a type of static analysis tool such as PMD, I believe you get a warning for the statement that you originally wrote.
Thde problem is in the condition of the while loop - you are using the assignment operator (=), whereas you are supposed to use the equality comparer (==). This way the loop condition is always true, because you are assigning true to the indexed field.
I hope this will work :-) .
The condition in the while loop should be while (numberArray[enteredNumber] == true). You're using the assignment operator =, not the comparison operator ==. Assignment is an expression that returns the assigned value, which is true in your case.

Categories

Resources