I wanted the help of you fellow users of Java in making up my computer project. I want to add the loop command for the "if-else"method given in the code below . I am attaching a picture of the design for clearer understanding.
Objective:
To make a calculator which shows how many odd or even numbers I have entered.
Problem:
I am not sure what the loop method is like.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
int odd = 0 ;
int even = 0 ;
int a = Integer.parseInt(txt1.getText());
if (a%2==0)
{
even++;
lbleven.setText(""+even);
}
else
{
odd++;
lblodd.setText(""+odd);
}
}
Every time you click on the button, even and odd will set to zero as they are local variables not instance variables, you have to make them instance variables so that they can hold the last value set to them.
private int odd;
private int even;
//....
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
int a = Integer.parseInt(txt1.getText());
if (a%2==0)
{
even++;
lbleven.setText(""+even);
}
else
{
odd++;
lblodd.setText(""+odd);
}
}
Or, you can get the odd&even labels text every time and increase them inside your condition.
int even= Integer.parseInt(lbleven.getText());
lbleven.setText(""+(++even))
Related
So I am a student. I am taking my first class in Java. I am sure my code is horrible, but please don't beat me up, I am really trying to learn. I have read quite a few method questions and adjusted my code according the the suggestions on this website. The closest post to my problem is Running Loop on Java Method. I adjusted my code according to the suggestions in this post, along with a few others. That said, it did not fix my problem. My methods are not pulling through properly.
Can anyone help? It will not pull any of the Boolean code into the main and I am not sure if the Boolean is pulling my methods correctly. Intro runs properly. Below is my code (edited down to include main and bool code only):
public static void main(String[] args)
{
intro(); // This works
while (repeat()) //This does not work
;
}//end Main
//None of this is being called
public static boolean repeat()
{
//Assign Variables
char calculate, calculateCS, repeat;
double inchCircle, inchSphere, radiusCS, volume, volumeSphere, area, areaCircle;
String shape;
//Initialze Variables
calculate = 1;
area = 1;
volume = 1;
inchCircle = 1;
inchSphere = 1;
shape = "";
//Ask if user wants to repeat
System.out.print("Do you want to calculate anouther round object (Y/N): ");
if (!takeInput().equalsIgnoreCase("y"))
{
System.out.println("Thank you for using the Round Object Calculator. Goodbye. ");
return false;
}
else
{
printCircleSphere(shape);
if (!printCircleSphere(shape).equalsIgnoreCase("c"))
{
printRadiusC(inchCircle);
printCircle(area);
}
else if (!printCircleSphere(shape).equalsIgnoreCase("s"))
printRadiusS(inchSphere);
printSphere(volume);
}
return true;
}//end repeat
I have a simple fact app that has an array of different facts.
I have a next, previous, and home button.
When the home button is pressed, I want the first fact to be displayed again, and after, it will start incrementing again from the first array value.
My home button is not working. If I hit the next button 5 times, then hit the home button, I will be directed to the first fact, but if I hit the next button, then the 6th fact will display, not the second.
Here is my code:
public String nextFact() {
i++;
if(i >= facts.length) {
i = 0;
}
return facts[i];
}
public String previousFact() {
i--;
if(i < 0) {
i = facts.length - 1;
}
return facts[i];
}
public String homeButton() {
int i = 0;
return facts[i];
}
You are declaring a new local version of i.
It should be:
public String homeButton() {
i = 0;
return facts[i];
}
According to your code, I am assuming i is a variable shared across the three methods, which keeps track of the index of the question currently displayed. If that is the case, your method should reset the class member i to 0, instead of creating a local variable.
public String homeButton() {
i = 0;
return facts[i];
}
This should do the trick.
I am currently making a text adventure game in Java, but I have come across a problem:
I need the value of a String variable to change each time the value of a particular int variable changes.
I want the program to perform this task (then continue where it left off) each time the value of an int variable changes:
if (enemyposition == 1) {
enemyp = "in front of you";
}
else if (enemyposition == 2) {
enemyp = "behind you";
}
else if (enemyposition == 3) {
enemyp = "to your left";
}
else if (enemyposition == 4) {
enemyp = "to your right";
}
else {
enemyp = "WOAH";
}
Thanks! :D
You could make the code much shorter using an array.
String[] message = {"WOAH", // 0
"in front of you", // 1
"behind you", // 2
"to your left", // 3
"to your right"}; // 4
enemyp = (enemyposition > 0 && enemyposition < 5) ? message[enemyposition] :
message[0];
The question you're asking sounds like it might be answerable by creating a class to hold the enemyposition integer. Add a "setter" method to your class to set the integer. You can write your setter method so that when the integer is set, it also sets up a string. Then write a "getter" method to retrieve the string. That's one common way of making sure two variables change together.
public class EnemyPosition {
private int enemyposition;
private String enemyp;
public void setPosition(int n) {
enemyposition = n;
enemyp = [adapt your code to set this based on the position]
}
public String getEnemyp() {
return enemyp;
}
}
I'm sure there are a lot of details missing, but you get the idea. Then instead of int enemyposition in the rest of your code, use EnemyPosition enemyposition = new EnemyPosition(), and use the setPosition method instead of assigning to it.
That's not the only solution (an array or Map that maps integers to strings may be good enough), but it's one OOP way to do things.
I just got a task asking me to do repeated addition from 1 to 21, as follows :
1,4,6,9,11,14,16,19,21
and get the total.
I tried this code but it returned to be a +2 addition, and it even bypass the prerequisite of bil<=21
public class test
{
public static void main(String[]args)
{
int bil=1;
long total=0;
boolean mult = true;
for(bil=1; bil<=21;bil++)
{
if(mult=true)
{
bil+=1;
mult=false;
}
else if(mult=false)
{
bil+=2;
mult=true;
}
System.out.println(bil);
total=total+bil;
}
System.out.println("----+");
System.out.println(total);
}
}
(if it's TL;DR)
Basically the request is 1+4+6+9+11+14+16+19+21=?
I can't seem to get these code to work, please help me?
EDIT : Thanks guys I got it now :D
You need boolean mult = false; so that the first time the loop runs, bil is incremented by 3 and not 2.
First, you are not comparing your boolean with ==. Therefore, every time the for() loop executes, the first block will be the one that enters since mult = true will always store true in mult... and then qualify that if() block to run.
If this assignment wasn't intentional, then you need to change it to == and also put some logic in your loop to toggle mult appropriately.
Basically when it runs through the first loop it only adds one because of the state of the boolean but also there should be an == operator to check instead of just an =
Try this:
for (bil = 1; bil < 21; bil++) {
if (bil % 2 == 0) { // If bil is divisible by 2, then add 2
bil += 2;
continue;
}
bil += 3;
}
I want to add an image to an ImageButton depending on a number between 0 and 10. My getNumber method is:
public int getNumber(){
// get a random number between 0 and 10
Random randomNumber = new Random();
num = randomNumber.nextInt(10);
return num;
}
I want every image to be unique but the problem I was having was that if numList did contain num it just would leave the button blank. I've tried to call permuteButton again recursively until num is not contained within my list but this does not seem to work.
public void permuteButton(ImageButton btn){
getNumber();
for(int i=0; i<=numList.size(); i++){
//check if the number is already being used
if( numList.contains(num) ){
permuteButton(btn);
}
// else the list doesnt have the number so assign the picture and add number to list
else{
numList.add(num);
assignPictures(btn);
}
}
}
Any help would be appreciated. I'm sorry if this is a simple question.
There are various things wrong with this code:
It would be better to have a single instance of Random instead of creating a new instance on each call to getNumber()
Rather than changing an instance variable within getNumber(), it would be sensible to just return the value and assign that to a local variable in permuteButton
Instead of recursion, you could use a while loop in permuteButton:
int num = getNumber();
while (numList.contains(num)) {
num = getNumber();
}
numList.add(num);
assignPictures(btn); // Presumably you'd now want to pass in num too
It would probably be a better idea to just shuffle the list to start with, create a Queue from it, then you can just take an item from the queue each time you need one. (This would also make it very easy to spot when you've used them all)
My answer is similar to the last suggestion from Jon Skeet.
// might be more than 10 ImageButtons, with only 10 images
for (ImageButton imageButton : imageButtons)
imageButton.putImage(randomImage.next());
...
public class RandomImage {
private final List<Image> shuffledImages;
private int currentIndex;
public RandomImage(List<Image> images) {
shuffledImages = new ArrayList<>(images.size());
shuffledImages.addAll(images);
currentIndex = -1;
}
public Image next() {
currentIndex++;
if (currentIndex % shuffledImages.size() == 0) {
currentIndex = 0;
Collections.shuffle(shuffledImages);
}
return shuffledImages[currentIndex];
}
}