Where should I place my increment? - java

I'm having a hard time figuring out where I should put my ers++ or ers+=1. I've tried doing a for loop and do-while, it worked and reached the limit of 3, but it should also let the user input again and check the inputs again.
if (ers < 3) {
if (a.equals(SignupPage.ee) && b.equals(SignupPage.dd) && !(a.isEmpty()) && !(b.isEmpty())) {
System.out.println(a+" "+b);
tf = true;
JOptionPane.showMessageDialog(null, "Welcome!", "Payment Portal", JOptionPane.INFORMATION_MESSAGE);
ElectricityPage ep = new ElectricityPage();
ep.setVisible(true);
} else if (a.equals("Admin") && b.equals("javaness") && !(a.isEmpty()) && !(b.isEmpty())) {
SignupPage.aa = Admin.Fname[0];
SignupPage.aa = Admin.Lname[0];
ers+=1;
ElectricityPage ep = new ElectricityPage();
ep.setVisible(true);
} else {
JOptionPane.showMessageDialog(null, "something is wrong", "Payment Portal", JOptionPane.ERROR_MESSAGE);
//ers=ers+1;
}
System.out.println(ers);
}

Related

2 counters not appearing at the same time in android

I am new to android and java and im trying my best to do a simple game called rockpaper scissor.
I am wondering why does my code cScore = 0; wont appear at the same time with yScore=0. I need to press again the rock button to reset the cScore back to 0.
Please help, any kind of suggestions will do.
thanks.
public class MainActivity extends AppCompatActivity {
TextView youOutput, compOutput, youScore, compScore;
int yScore=0, cScore=0, cPicked;
Random abc = new Random();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
youOutput =(TextView)findViewById(R.id.youOutput);
compOutput = (TextView)findViewById(R.id.compOutput);
youScore = (TextView)findViewById(R.id.youScore);
compScore = (TextView)findViewById(R.id.compScore);
}
public void rockButton(View view) {
youOutput.setText("Rock");
cPicked = 1+abc.nextInt(3);
if (cPicked == 1) {
compOutput.setText("Rock");
compScore.setText(Integer.toString(cScore));
youScore.setText(Integer.toString(yScore));
} else if(cPicked == 2) {
compOutput.setText("Paper");
cScore++;
if(cScore == 10){
cScore = 0;
yScore = 0;
Toast.makeText(this, "Computer won", Toast.LENGTH_LONG).show();
}else
compScore.setText(Integer.toString(cScore));
youScore.setText(Integer.toString(yScore));
} else {
compOutput.setText("Scissor");
yScore++;
if(yScore == 10){
cScore = 0;
yScore = 0;
Toast.makeText(this, "You won", Toast.LENGTH_LONG).show();
}else
compScore.setText(Integer.toString(cScore));
youScore.setText(Integer.toString(yScore));
}
}
Add curly brackets in last else block and else block in if (cPicked == 2)
if (cPicked == 1) {
compOutput.setText("Rock");
compScore.setText(Integer.toString(cScore));
youScore.setText(Integer.toString(yScore));
} else if (cPicked == 2) {
compOutput.setText("Paper");
cScore++;
if (cScore == 10) {
cScore = 0;
yScore = 0;
Toast.makeText(this, "Computer won", Toast.LENGTH_LONG).show();
//added curly brackets
} else {
compScore.setText(Integer.toString(cScore));
youScore.setText(Integer.toString(yScore));
}
} else {
compOutput.setText("Scissor");
yScore++;
if (yScore == 10) {
cScore = 0;
yScore = 0;
Toast.makeText(this, "You won", Toast.LENGTH_LONG).show();
//added curly brackets
} else {
compScore.setText(Integer.toString(cScore));
youScore.setText(Integer.toString(yScore));
}
}

Retrieving status of JCheckbox inside a JTable

For some reason, i cannot find out what is wrong with my code. Basically
I have a counter (total) initialized to 2 in this case
Increment to a max of 6, each time a JCheckbox is checked (in this case 4 )and throws a message when too much is clicked.
At first, it throws null pointer when exactly a total of 6 is checked; but works fine if more than 6 checkboxes are selected, then reduced to 6 with more than one button click.
Can anyone guide me to where it is messing with my head? Thank you very much.
public void panelThree(JTable user, JButton save, JButton logout, JButton exit, int j) {
System.out.println("J in external main is: " + j);
save.addActionListener(new ActionListener() {
boolean arr[] = new boolean[user.getRowCount()];
public void actionPerformed(ActionEvent e) {
int total = j;
System.out.println("Total in listener is: "+total);
System.out.println("No of rows: " + user.getRowCount());
for (int z = 0; z < arr.length; z++) {
arr[z] = false;
}
for (int i = 0; i < user.getRowCount(); i++) {
if (Boolean.valueOf(user.getModel().getValueAt(i, 3).toString()) == true) {
if (arr[i] == false) {
arr[i] = true;
total++;
}
} else {
if (arr[i] == true) {
arr[i] = false;
total--;
}
}
}
System.out.println("Total is: " + total);
if (total > 6) {
JOptionPane.showMessageDialog(null, "Please choose up to a maximum of " + (6 - j) + " modules");
} else {
int reply = JOptionPane.showConfirmDialog(null, "Are you sure to enroll in these modules?", "Yes", JOptionPane.YES_NO_OPTION);
if (reply == JOptionPane.YES_OPTION) {
JOptionPane.showMessageDialog(null, "Enrollment Successful");
}
}
}
});
}
The line if (Boolean.valueOf(user.getModel().getValueAt(i, 3).toString()) == true) seems to be responsible for all the error all the edit i am making console says null pointer at that line
Your table seems to contain null values. So you need to consider it in your check. Something like this:
if (user.getModel().getValueAt(i, 3) == Boolean.TRUE)
If my suggestion don't work please provide a SSCCE so we can also reproduce your problem.

Game of Nim, computer will not make move

I am attempting to make a Game of Nim for a school project, but whenever the computer attempts to make its move, it will not actually do anything unless there is three or less rocks left. My temp code will also execute in the console, so it runs through it, its just not working.
These are the custom voids:
public void winnerCheck(){
if(rocksLeft == 0 && lastPlayer == 0){
logBox.append("Plose gameOver");
}else if(rocksLeft == 0 && lastPlayer == 1){
logBox.append("Close gameOver");
}
//temp
System.out.println("winnerCheck() successful");
}
public void playersMove() throws BadLocationException{
lastPlayer = 0;
//used to gather players input and attempt to make a move
try{
playersRocks = Integer.parseInt(txtfPlayer.getText());
if(playersRocks <= 3 && playersRocks>=1){
rocksLeft -= playersRocks;
logBox.append("You have taken "+playersRocks+" rocks.\nThere are: "+rocksLeft+" rocks left.\nIt is the computer's turn.\n\n");
}else{
isValid = false;
}
}catch(NumberFormatException e){
isValid = false;
}
//temp
System.out.println("playersMove() successful");
}
public void computerAttempt(int computersRocks){
//this void is a snippet for the computer trying to make a play.
//contains only outputs and rocksLeft altering equation
logBox.append("\nThe computer is making a play.\n");
try {
//makes the game feel more realistic, as the computer takes time to make a move.
Thread.sleep(1600);
} catch (InterruptedException ex) {
Logger.getLogger(GameOfNim.class.getName()).log(Level.SEVERE, null, ex);
}
rocksLeft -= computersRocks;
logBox.append("The computer has taken "+computersRocks+" rocks.\nThere are: "+rocksLeft+" rocks left.\nIt is your turn!\n\n");
}
public void computersMove() throws BadLocationException{
lastPlayer = 1;
//computer will attempt to win, if not possible at the time it will take a random number
if(rocksLeft == 3){
computerAttempt(2);
}else if(rocksLeft == 2){
computerAttempt(1);
}else if(rocksLeft == 1){
logBox.append("The computer takes 1 rock.\n There are: 0 rocks left.\n\n Y O U H A V E W O N\n\n");
}else if(rocksLeft > 3){
computersRocks = (int) (Math.random()*(3-1+1)+1);
}
//temp
System.out.println("computersMove() succesful");
}
These are the two buttons:
private void buttonStartActionPerformed(java.awt.event.ActionEvent evt) {
//starts/resets game
rocksLeft = (int)(Math.random()*(30-15+1)+15);
buttonStart.setText("Reset");
buttonPlay.setEnabled(true);
logBox.setText("T h e g a m e h a s b e g u n !\n\nThere are: "+rocksLeft+" rocks left.\nIt is your turn!\n\n");
}
private void buttonPlayActionPerformed(java.awt.event.ActionEvent evt) {
//check if game is over
if(rocksLeft == 0){
logBox.append("The game has completed!\n Press the reset button to play again!");
System.out.println("gameOver succesful");
}else{
try {
//allows each player to move then checks if the player won or not
playersMove();
winnerCheck();
computersMove();
winnerCheck();
//temp
System.out.println("buttonPlay() succesful\n");
} catch (BadLocationException ex) {
Logger.getLogger(GameOfNim.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
I don't know the game you are making, but here is your mistake I think.
If there are more than 3 rocks left, you call
}else if(rocksLeft > 3){
computersRocks = (int) (Math.random()*(3-1+1)+1);
}
Which, I think, should be
}else if(rocksLeft > 3){
computerAttempt((int) (Math.random()*(3-1+1)+1));
}
Because you just changed the variable without calling the method on the value.(And I presume the important variable is the 'rocksLeft' which never got changed in your code, when the value was > 3.

Boolean if statement being ignored?

I don't understand why the if statements in the final method are being ignored. Is it because I used too many if statements?
I've commented out all the if statements and tried using this code in printShowChosen(....) to see if the boolean values are actually carried over
System.out.println(showchosen[0]);
System.out.println(showchosen[1]);
System.out.println(showchosen[2]);
System.out.println(showchosen[3]);
And it printed out
true
false
false
true
Can someone explain where I went wrong?
Here is the complete code:
import javax.swing.*;
public class short8 {
public static void main(String[] args) {
String[] ShowName = {"Les Miserables","Mamma Mia","Cats", "Chicago", "Phantom of the Opera"};
String[] TheatreName = {"Queens Theatre", "Garrick Theatre", "Palmer Theatre", "Spoa Theatre", "Dend Theatre"};
boolean[] showchosen = new boolean [5];
askTouristChoices(TheatreName, showchosen);
printShowsChosen(ShowName, TheatreName, showchosen);
}//ends main
public static String askTouristChoices(String[] ShowName, boolean[] showchosen)
{
System.out.println("Please type yes if you are interested in any of the following shows:");
String interestedMiserables = JOptionPane.showInputDialog("Les Miserables");
String interestedMammaMia = JOptionPane.showInputDialog("Mamma Mia");
String interestedCats = JOptionPane.showInputDialog("Cats");
String interestedChicago = JOptionPane.showInputDialog("Chicago");
String interestedPhantom = JOptionPane.showInputDialog("Phantom of the Opera");
if ((interestedMiserables.equals("Yes")) || (interestedMiserables.equals("yes")))
{
showchosen[0] = true;
}
else if ((interestedMiserables.equals("No")) || (interestedMiserables.equals("no")))
{
showchosen[0] = false;
}
else
{
JOptionPane.showMessageDialog(null, "Enter either Yes or No!!");
}
if ((interestedMammaMia.equals("Yes")) || (interestedMammaMia.equals("yes")))
{
showchosen[1] = true;
}
else if ((interestedMammaMia.equals("No")) || (interestedMammaMia.equals("no")))
{
showchosen[1] = false;
}
else
{
JOptionPane.showMessageDialog(null, "Enter either Yes or No!!");
}
if ((interestedCats.equals("Yes")) || (interestedCats.equals("yes")))
{
showchosen[2] = true;
}
else if ((interestedCats.equals("No")) || (interestedCats.equals("no")))
{
showchosen[2] = false;
}
else
{
JOptionPane.showMessageDialog(null, "Enter either Yes or No!!");
}
if ((interestedChicago.equals("Yes")) || (interestedChicago.equals("yes")))
{
showchosen[3] = true;
}
else if ((interestedChicago.equals("No")) || (interestedChicago.equals("no")))
{
showchosen[3] = false;
}
else
{
JOptionPane.showMessageDialog(null, "Enter either Yes or No!!");
}
if ((interestedPhantom.equals("Yes")) || (interestedPhantom.equals("yes")))
{
showchosen[4] = true;
}
else if ((interestedPhantom.equals("No")) || (interestedPhantom.equals("no")))
{
showchosen[4] = false;
}
else
{
JOptionPane.showMessageDialog(null, "Enter either Yes or No!!");
}
return null;
} //ends askTouristChoices
public static void printShowsChosen(String[] ShowName,String[] TheatreName, boolean[] showchosen)
{
if(showchosen[0] = true)
{
System.out.println(ShowName[0] + ": " + TheatreName[0]);
}
if(showchosen[1] = true)
{
System.out.println(ShowName[1] + ": " + TheatreName[1]);
}
if(showchosen[2] = true)
{
System.out.println(ShowName[2] + ": " + TheatreName[2]);
}
if(showchosen[3] = true)
{
System.out.println(ShowName[3] + ": " + TheatreName[3]);
}
if(showchosen[4] = true)
{
System.out.println(ShowName[4] + ": " + TheatreName[4]);
}
}//ends printShowsChosen
}//ends short8
The
if(showchosen[0] = true)
should read
if(showchosen[0] == true)
or
if(showchosen[0])
A single = is assignment, not comparison.
The statement
if(showchosen[0] = true)
should be:
if(showchosen[0] == true)
or even better:
if(showchosen[0])

How do I check if a class' return of a method equals null?

In my program, I have a while loop that will display a list of shops and asks for an input, which corresponds with the shop ID. If the user enters an integer outside the array of shops, created with a Shop class, it will exit the loop and continue. Inside this loop is another while loop which calls the sellItem method of my Shop class below:
public Item sellItem()
{
displayItems();
int indexID = Shop.getInput();
if (indexID <= -1 || indexID >= wares.length)
{
System.out.println("Null"); // Testing purposes
return null;
}
else
{
return wares[indexID];
}
}
private void displayItems()
{
System.out.println("Name\t\t\t\tWeight\t\t\t\tPrice");
System.out.println("0. Return to Shops");
for(int i = 0; i < wares.length; i++)
{
System.out.print(i + 1 + ". ");
System.out.println(wares[i].getName() + "\t\t\t\t" + wares[i].getWeight() + "\t\t\t\t" + wares[i].getPrice());
}
}
private static int getInput()
{
Scanner scanInput = new Scanner(System.in);
int itemID = scanInput.nextInt();
int indexID = itemID - 1;
return indexID;
}
The while loop in my main class method is as follows:
boolean exitAllShops = true;
while(exitAllShops)
{
System.out.println("Where would you like to go?\nEnter the number which corresponds with the shop.\n1. Pete's Produce\n2. Moore's Meats\n3. Howards Hunting\n4. Foster's Farming\n5. Leighton's Liquor\n6. Carter's Clothing\n7. Hill's Household Products\n8. Lewis' Livery, Animals, and Wagon supplies\n9. Dr. Miller's Medicine\n10. Leave Shops (YOU WILL NOT BE ABLE TO RETURN)");
int shopInput = scan.nextInt();
if(shopInput >= 1 && shopInput <= allShops.length)
{
boolean leaveShop = true;
while(leaveShop)
{
allShops[shopInput - 1].sellItem();
if(allShops == null)
{
System.out.println("still null"); // Testing purposes
leaveShop = false;
}
}
}
else
{
System.out.println("Are you sure you want to leave?\n1. Yes\n2. No");
int confirm = scan.nextInt();
if(confirm == 1)
{
exitAllShops = false;
}
}
The problem is here:
boolean leaveShop = true;
while(leaveShop)
{
allShops[shopInput - 1].sellItem();
if(allShops == null)
{
System.out.println("still null"); // Testing purposes
leaveShop = false;
}
}
No matter what I do, I can't get "still null" to print to confirm that I'm correctly calling the return statement of the method sellItem of the class Shop. What am I doing wrong?
After calling allShops[...].sellItem(), allShops is still a valid array reference -- there's no way it could be null! You probably want to test the return value from sellItem:
if(allShops[shopInput-1].sellItem() == null)

Categories