Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
I've just started learning Java and I've been playing around with a few ideas. I've written the following small piece of code which when run outputs a different room in a house. The room is decided by a random integer between the value of 1 and 3. The code seems to work just fine. However, as I am new to programming my concern is that I may have misunderstood one of the tutorials informing my work and used an inefficient way to complete it.
Can anyone tell me if am I using the best practises to achieve my desired result and explain any changes I could make to make the code better?
import java.util.Random;
public class Rooms {
public static void main(String[] args) {
Random random = new Random();
int roomNumber = random.nextInt(3) + 1;
String getRoom = "";
if (roomNumber == 1) {
getRoom = "Living Room";
} else if (roomNumber == 2) {
getRoom = "Kitchen";
} else if (roomNumber == 3) {
getRoom = "Bathroom";
}
System.out.println(getRoom);
}
}
Thanks for reading this.
You could simply put the rooms into an array:
String[] rooms = { "Living Room", "Kitchen", "Bathroom" };
int roomNumber = random.nextInt(rooms.length);
System.out.println(rooms[roomNumber]);
Background: Random.nextInt(n) takes an int argument as the upperbound which returns an integer between 0 and (but not including) n. Using rooms.length here will allow you to select a random index from the array without causing an ArrayIndexOutOfBoundsException.
Your code is just fine. The only thing I can recommend is: Using switch instead of multiple-if's with else's is faster, but as you run this random once, that doesn't really matter. That switch if you need:
switch (roomNumber) {
case 1: getRoom = "Living Room";
break;
case 2: getRoom = "Kitchen";
break;
case 3: getRoom = "Bathroom";
break;
default: getRoom = "Error!";
break;
}
Also you can use List or Arrays. Arrays will speed you up too, always use arrays if you have defined number of elements.
String[] rooms = new String[]{"Living Room", "Kitchen", "Bathroom"};
getRoom = rooms[random.nextInt(rooms.length)];
Related
Is there a way to grab the resulting number from each iteration of this loop and compare it to the next?
This is a Slot Machine Sim in Java,
I'm trying to find a way to see how many of the results match.
so I thought I would capture the number that is resulted from each round of the For loop and compare it to the previous one.
but I have no idea how to write that?
is there a better way to do this?
what I have so far:
for (int count=1; count<= 3 ; ++count)
{
number = slotM.nextInt(6);
switch (number)
{
case 0:
System.out.print("-cherries-");
break;
case 1:
System.out.print("-Oranges-");
break;
case 2:
System.out.print("-Palms-");
break;
case 3:
System.out.print("-Bells-");
break;
case 4:
System.out.print("-Melones-");
break;
default:
System.out.print("-Bars-");
break;
}
System.out.print(number);
}
Yep there are several better ways. If you have a fixed number of options (6 in your case) an enum might be a good option:
enum Picture {
CHERRIES, ORANGES, PALMS, BELLS, MELONS, BARS;
public String getName() {
return "-" + name().substring(0, 1) + name().substring(1).toLowerCase() + "-";
}
That way you can store your numbers as pictures rather than numbers.
Picture pictures[3];
Random random = new Random();
for (int i = 0; i < pictures.length; i++)
picture[i] = Picture.values[random.nextInt(pictures.length)];
To get the printed version:
for (Picture picture: picture)
System.out.print(picture.getName());
You’ll need some kind of storage outside of the loop so that each iteration can reference it.
int[] results Look in to arrays - you can put the results of each round into a part of the array, and look up the value.
You are declaring your count variable in the for loop, just declare outside and make a comparison with it
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
After i saved my class while i was working on it last night, it got deleted this morning. I am sure its not corrupted since i am sure i saved it and closed it right. I already tried restore from local history. I also searched google and i found no help...
i worked hard on the class, i really don't want to code it again.ScreenShot
The other classes are fine and they have evreything from last night. its just my main...
UPDATE:
Sorry for posting this here, my bad. I was just really pissed cuz half my code got deleted. Anyways here's some real help i need... Before my code got deleted my Computer Science teacher helped me write the switch code for my main. Now that it's deleted i need some help from you guy's!!! I need my input to be able to read Chars and Int's. This is what i have so far...
public static void main(String[] args) throws InterruptedException {
do {
try {
System.out.println("Enter your birthYear");
birthYear = Integer.parseInt(input.next());
int length = String.valueOf(birthYear).length();
System.out.println(length);
if (length != 4) {
lengthTest = false;
System.out.println("Invalid Choice");
} else {
lengthTest = true;
}
test = true;
} catch (Exception e) {
System.out.println("Invalid Choice");
}
} while (test == true ^ lengthTest != false);
do {
System.out.println("Please enter a number between 1-4 \n"
+ "1 = AreaOfTriangle \n" +
"----------------------------------\n" +
"2 = HoursToDaysAndHours Calculator \n" +
"---------------------------------- \n" +
"3 = CelciusToFahrenheit Calculator \n" +
"----------------------------------\n" +
"4 = BirthdayGame \r\n" +
"----------------------------------");
try {
choice = (char)Integer.parseInt(input.next().toLowerCase());
System.out.println(choice);
switch (choice) {
case 1:
aOT.areaOfTriangle();
break;
case 2:
hTDAH.hoursToDaysAndHours();
break;
case 3:
cTF.celciusToFahrenheit();
case 4:
System.out.println("Code not implemented yet");
break;
case 'e':
repeat = false;
break;
default:
System.out.println("This part of the program has not been implemented");
break;
}
}catch (Exception e) {
System.out.println("Invalid Awnser");
}
} while (repeat == true);
}
It looks like you should setup a version control system e.g. Git. To quote Attlasian What is version control page:
Version control systems are a category of software tools that help a software team manage changes to source code over time. Version control software keeps track of every modification to the code in a special kind of database. If a mistake is made, developers can turn back the clock and compare earlier versions of the code to help fix the mistake while minimizing disruption to all team members.
Windows has a featured to get ancient version of a file i think,
https://hls.harvard.edu/dept/its/restoring-previous-versions-of-files-and-folders/
try this maybe. GL
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
Hello please may someone run my code and assist me in debugging it. I'm having a lot of troubles trying to figure it out and i have not a lot of guidance when it comes to coding.
the problem with my code right now is that it runs certain parts twice. please annotate the issue and any
reccomendations to fix it. Thanks in advance
a brief of what i'm trying to do:
number guessing game
the idea is that the computer will generate a random number and will ask the user if they know the number
if the user gets the answer correct they will get a congrats message and then the game will end but if the user
enters a wrong number they get a try again message and then they will try again
import javax.swing.*;
import java.lang.*;
public class Main {
public static void main(String[] args) {
/*
number guessing game
the idea is that the computer will generate a random number and will ask the user if they know the number
if the user gets the answer correct they will get a congrats message and then the game will end but if the user
enters a wrong number they get a try again message and then they will try again
the problem with my code right now is that it runs certain parts twice. please annotate the issue and any
recomendations to fix it. Thanks in advance
*/
enterScreen();
if (enterScreen() == 0){
number();
userIn();
answer();
}
}
public static int enterScreen (){
String[] options = {"Ofcourse", "Not today"};
int front = JOptionPane.showOptionDialog(null,
"I'm thinking of a number between 0 and 100, can you guess what is is?",
"Welcome",
JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE,
null, options, "Yes" );
if(front == 0){
JOptionPane.showMessageDialog(null, "Goodluck then, you might need it. :D");
}
else {
JOptionPane.showMessageDialog(null, "okay i dont mind");
}
return front;
}
private static int number(){
double numD;
numD = (Math.random() * Math.random()) * 100;
int numI = (int) numD;
System.out.println(numD);
return numI;
}
private static int userIn(){
String userStr = JOptionPane.showInputDialog("What number do you think im thinking of?");
int user = Integer.parseInt(userStr);
return 0;
}
private static void answer(){
// here is the problem
if(userIn() == number()){
JOptionPane.showMessageDialog(null, "Well done! You must be a genius.");
}
else {
JOptionPane.showMessageDialog(null, "Shame, TRY AGAIN!");
userIn();
}
}
}
Your problem is this part:
enterScreen();
if (enterScreen() == 0) {
number();
userIn();
answer();
}
You can leave out the first enterScreen(). Because you call it again in the if statement. If you look at the return type of the method: public static int, it returns and int. This makes it so that the outcome of the method is directly available in the if statement. The fist enterScreen is basicly useless, because you dont use the result.
You could do this:
int num = enterscreen();
if (num == 0) {
number();
userIn();
answer();
}
Which is basicly the same as:
if (enterScreen() == 0) {
number();
userIn();
answer();
}
You call enterScreen() twice. Just call it once, and compare the value returned only once.
Also, StackOverflow typically is not for "Here's my code, fix it" kind of not questions.
https://stackoverflow.com/help/how-to-ask
You call enterScreen() and userIn() functions twice or more. Please Computer Science and coding. Hint: Computer's execute intructions from top to bottom.
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 6 years ago.
Improve this question
I'm trying to generate a random double for this section of my assignment.
The question is
"Each week, each female Guppy who is 10 weeks old or older has a 25 percent chance of spawning".
I would like to generate a random double to determine if each female Guppy should spawn or not.
My code so far:
Random r = new Random();
if (isFemale == true && getAgeInWeeks() >= 10) {
//?
}
I don't see any reason to generate a random double according to your question. What you need is an integer ranging from 0 to 3 inclusive where each number account for 25% for the spawning.
Random r = new Random();
if (isFemale == true && getAgeInWeeks() >= 10) {
// Generate a random integer in [0,3]
// Since there is a 25% or 1/4 chance
if(Math.abs(r.nextInt()) % 4 == 1){
//Note that the 1 in the condition can be replaced by any
// integer in [0,3]
//Put spawning code here
}
}
Check out this link for more information on random:
Random (Java Platform SE 7
To generate a random double, you can look at this question, however, this problem can more easily be solved by generating random ints.
In your situation, generating an int between 0 to 3 is what you want because checking if it is 0 will be true 25% of the time (1 Value / 4 Possible values = 25%).
EDIT: If you would like to also generate a random number to see how many spawn a Guppy will have use threadLocalRandomInstance.nextInt(int bound); like before.
These constraints can be translated to code like this:
import java.util.concurrent.ThreadLocalRandom;
public class Test {
public static void main(String[] args) {
ThreadLocalRandom tlr = ThreadLocalRandom.current();
int num = tlr.nextInt(3 + 1); //Bound is exclusive so add 1.
int spawn;
if(num == 0) {
spawn = tlr.nextInt(100 + 1); //Again, bound is exclusive so add 1.
} else spawn = 0;
System.out.println("This guppy had " + spawn + " spawn.");
}
}
I use ThreadLocalRandom as it is more straightforward as supported by this answer.
If you are not using Java 1.7+, use Random#nextInt(int) instead as also shown by that answer.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
How do I assign a numeric value to a string in Java? I'm using cards from Ace to king, and I want to assign the value 11 to "Jack" so I can compare it to, say, "Six".
Any ideas?
If you're using a language which supports enums, those are probably your best bet. For instance, in C#, you could do (this is rough and untested):
public enum CardDeck
{
1 = 1,
2 = 2,
3 = 3,
...
Jack = 10,
Queen = 11,
King = 12,
Ace = 13
}
You can then compare (if (int)Ace == (int)1) {}
Use HashMaps:
Map<String,Integer> map = new HashMap<>();
map.put("Jack", 11);
You have a few options. You can, say, store the strings in an array and search for them, returning the index:
List<String> names = new ArrayList<String>();
names.add("ace");
names.add("two");
names.add("three");
int number = names.indexOf("ace");
You could use a map of strings to numbers and do a lookup, this allows use of nonconsecutive numbers:
Map<String,Integer> names = new HashMap<String,Integer>();
names.put("ace", 1);
names.put("jack", 11);
names.put("queen", 12);
int number = names.get("ace");
You could also use an enum with properties, e.g.:
enum CardValue {
ACE(1),
JACK(11),
QUEEN(12);
final int value;
CardValue (int value) { this.value = value; }
int getValue () { return value; }
}
int number = Enum.valueOf(CardValue.class, "ace".toUpperCase()).getValue();
Or in the above you could use ordinal() if they are consecutive.
Add error handling as necessary.
You could also just use a brute force large if, or use a switch block (since Java 1.7):
int value (String name) {
switch (name.toLowerCase()) {
case "ace": return 1;
case "jack": return 11;
case "queen": return 12;
default: return -1;
}
Personally, I'd go for the array or map approach in your case. It is simple to code and allows easy conversion of string to value and back, and, unlike the enum technique, doesn't tie compile-time type names to user input strings (e.g. difficult if you, say, add support for another language).
The switch block is easy to code as well.