So the program that I am trying to write is something like this. The opponent picks a number at random where each number corresponding to a person. then the user does the same thing. then the out is to show what the user pick, what the opponent picked and who won that match. its similiar to rock, paper scissor but with some more stuff added to it. i also have to show the numbers of rounds played and how many times the user had won. But my problem is this. No matter what my input is, it keeps saying that i made an invalid choice and to pick it again. This is what I have.
public static void main(String[] args) {
int game=0;
int won = 0;
int opponent;
Random rand = new Random();
System.out.println("Welcome to the game. Here are the rules:");
Scanner in = new Scanner(System.in);
rules();
choices();
int choice = selected(in);
while (choice !=0) {
rules();
choices();
choice = selected(in);
opponent = opp();
result(choice, opponent, in);
game+=1;
}
System.out.println("You played " +game+" games.");
System.out.println("Quitting");
}
public static void rules(){
System.out.println("\nFlurg beats Stuga and Kvartal");
System.out.println("Stuga beats Kvartal");
System.out.println("Kvartal beats Lerberg");
System.out.println("Lerberg beats Flurg and Stuga");
System.out.println("The computer wins in the event of a tie.");
System.out.println();
}
public static int opp(){
Random rand = new Random();
int opponent = rand.nextInt(4)+1;
return opponent;
}
public static void choices(){
System.out.println("Please select your choice:");
System.out.println("'1' for Flurg ");
System.out.println("'2' for Stuga ");
System.out.println("'3' for Kvartal ");
System.out.println("'4' for Lerberg ");
System.out.println("'0' to Quit ");
System.out.print("Selection: ");
}
public static int selected(Scanner in){
int choice = in.nextInt();
while (choice != 1 && choice != 2 &&
choice != 3 && choice != 4 &&
choice != 0) {
System.out.println("Invalid choice");
choices();
choice = in.nextInt();
}
return choice;
}
public static int result(int choice, int opponent, Scanner in) {
int won=0;
System.out.print("You picked:" +choice+". Opponent picked:" +opponent+".");
if(choice == 1 && (opponent == 2) || (opponent == 3)){
System.out.println("You won!");
won+=1;
}
else if(choice == 2 && opponent == 3){
System.out.println("You won!");
won+=1;
}
else if(choice == 3 && opponent == 4){
System.out.println("You won!");
won=+1;
}
else if(choice == 4 && (opponent == 1 || opponent == 2)){
System.out.println("You won!");
won+=1;
}
else {
System.out.println("You lost!");
}
return won;
}
}
EDIT
So I fixed exactly what i was told about the !=1 part. but it is again looping. for some reason, it does not want to run result()
EDIT#2
Main also has been fixed with the similar problem.
EDIT#3
I have added more lines based on what I was told.
change this
choice != '1' && choice != '2' &&
choice != '3' && choice != '4' &&
choice != '0'
to this
choice != 1 && choice != 2 &&
choice != 3 && choice != 4 &&
choice != 0
What you were trying to do was int != char and the value for '1' in ASCII is 49 SO it was indeed not 1. You are reading int from the Scanner.
The problem is here
int choice = in.nextInt();
while (choice != '1' && choice != '2' &&
choice != '3' && choice != '4' &&
choice != '0') {
System.out.println("Invalid choice");
nextInt() will return the decimal value of an int type. (int)1 != (char)'1'. The easiest solution I can think of is
while (choice != 1 && choice != 2 &&
choice != 3 && choice != 4 &&
choice != 0) {
You are comparing the found values to chars.
int choice = in.nextInt();
while (choice != '1' //...
However, this compares the entered numerical value to the ASCII-code of the character which is 49 for the character '1'. Therefore, your loop will continue until you enter one of the numbers 48 ('0') to 52 ('4').
You should compare to the numbers instead:
while (choice != 1 && choice != 2 && choice != 3 && choice != 4 && choice != 0) {
System.out.println("Invalid choice");
}
The same goes for
while (choice !='0') {
rules();
choices();
selected(in);
opp();
result(choice, opponent, in);
}
in your main method -- change this to
while (choice != 0) { // change this to 0 instead of '0'
rules();
choices();
choice = selected(in); // assign the value to choice
opponent = opp(); // assign the value to opponent
result(choice, opponent, in);
}
You also did not assign the return values of the methods to the local variables -- they are never going to change and the loop will never end like that!
Related
I'm working on a card game for a personal project and I was wondering how I could make it so that each specific card can only be used a set number of times. I'm thinking about making an loop that adds to a specific number, and if the number reaches that specific value, the card can no longer be played. My issue is that I am having trouble with syntax and have just been confusing myself. cardLimiter is the variable i want to use to add to a specific value, though I just need a few pointers. Thanks!
public static void emperorsTurn() {
Random cards = new Random();
int computerinput = 0;
int numberx = 5;
for (int counter = 1; counter <= 3; counter++) {
computerinput = 1 + cards.nextInt(2);
}
Scanner sc = new Scanner(System.in);
System.out.println("Please pick the card you are playing. \n if you are playing the Emperor press 1, if you are playing the citizen press 2 ");
int userinput = sc.nextInt();
if (userinput == 1 && computerinput == 1 && cardLimiter == 0) {
System.out.println("you have played the emperor! \n the emperor is defeated by the slave");
cardLimiter++;
if ((userinput == 1 && computerinput == 1 && cardLimiter == 1)) {
System.out.println("you cannot play the emperor this turn \n you have played the citizen instead");
}
} else if (userinput == 1 && computerinput == 2) {
System.out.println("you have played the emperor the emperor defeats the citizen");
winOrLose();
wincounter();
numberx--;
} else if (userinput == 2) { //when the user input is 2
if (computerinput == 1) {
System.out.println("you have played the citizen, this defeats the slave");
wincounter();
} else if (computerinput == 2) {
System.out.println("you have played the citizen, this ties with the citizen");
}
//print out something else if number is not 1,2 or 3
}
}
In this part, you've got the second if statement nested inside the first:
if (userinput == 1 && computerinput == 1 && cardLimiter == 0) {
System.out.println("you have played the emperor! \n the emperor is defeated by the slave");
cardLimiter++;
if ((userinput == 1 && computerinput == 1 && cardLimiter == 1)) {
System.out.println("you cannot play the emperor this turn \n you have played the citizen instead");
}
}
If userinput == 1 && computerinput == 1 && cardLimiter == 0 it will print out "you have played the emperor" etc. But then you immediately increment cardLimiter, so it will also print out "you cannot play the emperor this turn".
I imagine that's not the desired behavior, so I would recommend moving that second if statement out of the first one. Perhaps something like this:
if (userinput == 1 && computerinput == 1 && cardLimiter == 0) {
System.out.println("you have played the emperor! \n the emperor is defeated by the slave");
cardLimiter++;
} else if ((userinput == 1 && computerinput == 1 && cardLimiter == 1)) {
System.out.println("you cannot play the emperor this turn \n you have played the citizen instead");
}
That way, only one of the System.out.println statements will execute.
I have to make this program which asks for a furniture type, the material type and calculates the cost of the furniture while displaying price and the type of material.
// Adam Bashir
public class Exercise1 {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
char furntype;
char fabtype;
int c =1000;
int C =1000;
int l =750;
int L =750;
int r =1200;
int R =1200;
String couch="";
System.out.println("Please enter the type of furniture you want! C for couch L for loveseats, and R for Recliner");
furntype = (char)System.in.read();
if (furntype == 'c' || furntype == 'C') {
System.out.println("You chose a couch! It sells for $ " + c);
} else if (furntype == 'l' || furntype == 'L') {
System.out.println("You chose a loveseat! It sells for $750");
} else if (furntype == 'r' || furntype == 'R') {
System.out.println("you chose recliner! It sells for $1200");
} else {
System.out.println("Invalid choice");
}
System.out.println("Would you like fabric or leather for the couch, leather costs 35% more.");
fabtype = (char)System.in.read();
if (fabtype == 'f' || fabtype =='F') {
System.out.println("you selected fabric! your total is $" + furntype);
} else if (fabtype == 'l' || fabtype =='L') {
System.out.println("you chose leather! your new total is $" + fabtype);
} else {
System.out.println("Invalid choice");
}
}
I cannot figure out why my second set of if statements doesn't let me input the fabric choice
Why don't you use a scanner?
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
char furntype;
char fabtype;
int c =1000;
int C =1000;
int l =750;
int L =750;
int r =1200;
int R =1200;
String couch="";
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter the type of furniture you want! "+
"C for couch L for loveseats, and R for Recliner");
//Take user input as a String, and get the first char.
furntype = scanner.nextLine().charAt(0);
if (furntype == 'c' || furntype == 'C')
System.out.println("You chose a couch! It sells for $ " + c);
else if (furntype == 'l' || furntype == 'L')
System.out.println("You chose a loveseat! It sells for $750");
else if (furntype == 'r' || furntype == 'R')
System.out.println("you chose recliner! It sells for $1200");
else
System.out.println("Invalid choice");
System.out.println("Would you like fabric or "+
"leather for the couch, leather costs 35% more.");
//Get the first char of input string
fabtype = scanner.nextLine().charAt(0);
if (fabtype == 'f' || fabtype =='F')
System.out.println("you selected fabric! your total is $" + furntype);
else if (fabtype == 'l' || fabtype =='L')
System.out.println("you chose leather! your new total is $" + fabtype);
else{
System.out.println("Invalid choice");
}
}
Ideally, I would recommend to use String instead of char. Treat your input as a String and use new Scanner().readLine();. Then to check for equality, use if(input.equalsIgnoreCase("c")). It will make your program easier to write.
If the user input is odd and within the range it works fine. Can't seem to figure out how to get it to work with even number input though.
I've seen that there is an "easier" way to do this program on other posts but I got this on my own before having to look up any issues and want to see if there is any way I can make this work through this method.
import java.util.Scanner;
public class Lab7_3{
public static void main(String args []){
Scanner input = new Scanner(System.in);
char userStart;
int countA=1, countB=1, rowsColumns;
System.out.println("Do you want to start?");
userStart = input.next().charAt(0);
while (userStart == 'Y' || userStart == 'y'){
System.out.println("How many rows/columns? (5-21)");
rowsColumns = input.nextInt();
while (rowsColumns < 5 || rowsColumns > 21){
System.out.println("Invalid range. Reenter (5-21)");
rowsColumns = input.nextInt();
}//end while3
for(countA = 1; countA <= rowsColumns; countA++){
System.out.println("");
for(countB = 1; countB <= rowsColumns; countB++){
if((rowsColumns % countA) == 0 || (rowsColumns % countB) == 0)){
System.out.print("*");
}//end if
else{
System.out.print("1");
}//end else
}//end for2
}//end for
System.out.println("\nDo you want to continue? (Y/N)");
userStart = input.next().charAt(0);
}//end while
}//end main
}//end class
The line if((rowsColumns % countA) == 0 || (rowsColumns % countB) == 0)) gives wrong results.
if(countA==1 || countA == rowsColumns || countB == 1 || countB == rowsColumns) works for both odd and even numbers.
I'm working on this program that asks for model numbers of cars infinitely until the person inputs 0 to break the loop. When i run it and input a number it just infinitely loops either your car is defective or it is not defective until it crashes. I'm pretty stuck right now any help would be greatly appreciated.
Scanner input = new Scanner(System.in);
System.out.print("Enter a model number or 0 to quit: ");
modelNum = input.nextInt();
while (modelNum != 0) {
if (modelNum >= 189 && modelNum <= 195) {
System.out.println("Your car is defective it must be repaired");
} else if (modelNum == 189 || modelNum == 221) {
System.out.println("Your car is defective it must be repaired");
} else if (modelNum == 780) {
System.out.println("Your car is defective it must be repaired");
} else if (modelNum == 119 || modelNum == 179) {
System.out.println("Your car is defective it must be repaired");
} else {
System.out.println("Your car is not defective");
}
if (modelNum == 0) {
System.out.println("end");
break;
}
}
It's because you never ask the user for another input. You should do so before the end of the loop.
Include the this part into your loop:
Scanner input = new Scanner(System.in);
System.out.print("Enter a model number or 0 to quit: ");
modelNum = input.nextInt();
You have to ask for a new value to be evaluated:
while (modelNum != 0) {
// if conditions
modelNum = input.nextInt();
}
Also note that:
if (modelNum == 0) {
System.out.println("end");
break;
}
won't be necessary because if the last value is 0 the condition in the while loop will be false and won't loop again.
Last thing: why you have all those if-else-if when they all do the same thing (print "Your car is defective it must be repaired"). This will be enough:
while (modelNum != 0) {
if ((modelNum >= 189 && modelNum <= 195) || modelNum == 221 || modelNum == 780 || modelNum == 119 || modelNum == 179) {
System.out.println("Your car is defective it must be repaired");
} else {
System.out.println("Your car is not defective");
}
modelNum = input.nextInt();
}
if you enter 0, the loop will break, therefore the last if statement will never run.
This loop just tells you if the car is defective or not depending on the model number, but you never tell the program to exit the loop if the car is defective. To do so you have to put break statements into each if statement of the loop.
Moreover this statement is useless:
if(modelNum == 0)
{
System.out.println("end");
break;
since if u enter 0 the loop won't start.
I was tasked with making a simple program that will play Rock-Paper-Scissors with the user. Unfortunately, when I try to run the program, my return(sentence+outcome) both returns null. I am new to using methods, so please explain what I am doing wrong here... Thank you!
package rockpaperscissors;
/**
*
* #author Owner
*/
import java.util.Scanner;
import java.io.IOException;
public class RockPaperScissors {
static int weaponChoice;
static int computerChoice;
static int tie = 0;
static int lose = 0;
static int win = 0;
static String outcome;
static String sentence;
/**
* #param args the command line arguments
* #throws java.io.IOException
*/
public static void main(String[] args) throws IOException {
Scanner userInput = new Scanner(System.in);
System.out.println(" =========================");
System.out.println("====ROCK=PAPER=SCISSORS====");
System.out.println(" =========================");
int playAgain = 1; //sets a play again function
do {
System.out.println("Please select your weapon.");
System.out.println("1 - Rock");
System.out.println("2 - Paper");
System.out.println("3 - Scissors");
System.out.println("Choose wisely:");
String choice = userInput.nextLine();
weaponChoice = Integer.parseInt(choice);
do {
if (weaponChoice != 1 && weaponChoice != 2 && weaponChoice != 3) {
System.out.println("Please choose again, grasshopper. There are only"
+ " three choices.");
System.out.println("1 - Rock");
System.out.println("2 - Paper");
System.out.println("3 - Scissors");
choice = userInput.nextLine();
weaponChoice = Integer.parseInt(choice);
}
} while (weaponChoice != 1 && weaponChoice != 2 && weaponChoice != 3);
if (weaponChoice == 1) {
System.out.println("You have selected Rock as your weapon.");
} else if (weaponChoice == 2) {
System.out.println("You have selected Paper as your weapon.");
} else {
System.out.println("You have selected Scissors as your weapon.");
}
//Computer's Choice
computerChoice = 1 + (int) (Math.random() * ((3 - 1) + 1));
if (computerChoice == 1) {
System.out.println("The computer has chosen Rock.");
} else if (computerChoice == 2) {
System.out.println("The computer has chosen Paper.");
} else {
System.out.println("The computer has chosen Scissors.");
}
determineOutcome(outcome, sentence);
System.out.println(sentence+outcome);
System.out.println("==SCORES==");
System.out.println("WINS: " + win);
System.out.println("TIES: " + tie);
System.out.println("LOSSES: " + lose);
System.out.println("Press 1 to play again, or any other number to exit.");
String play = userInput.nextLine();
playAgain = Integer.parseInt(play);
} while (playAgain == 1);
}
public static String determineOutcome(String outcome, String sentence) {
sentence = "Your result is: ";
do {
if (weaponChoice == 1 && computerChoice == 1 || weaponChoice == 2 && computerChoice == 2 || weaponChoice == 3 && computerChoice == 3) {
tie++;
outcome = "TIE";
} else if (weaponChoice == 1 && computerChoice == 3 || weaponChoice == 2 && computerChoice == 1 || weaponChoice == 3 && computerChoice == 2) {
win++;
outcome = "You WON!";
} else {
lose++;
outcome = "You LOSE. Better luck next time?";
}
} while (lose <0 || win < 0 || tie < 0);
return(sentence+outcome);
}
}
To make this work, you'll need to replace
determineOutcome(outcome, sentence);
System.out.println(sentence+outcome);
with
String valueReturned = determineOutcome(outcome, sentence);
System.out.println(valueReturned);
because Java is pass by value, not pass by reference. That means that the determineOutcome method will work with its own copies of outcome and sentence, and not modify the versions that belong to the method that called it.
But also, the method is not actually using the two arguments you pass into it. It would be much less confusing if you just omit the parameters entirely, and change it to public static String determineOutcome() ... and declare String sentence; and String outcome; inside the method.
When calling a function that is returning a result you must either call the function within System.out.println() or assign the result to a variable which you then print.
Option 1:
String result = determineOutcome(outcome, sentence);
System.out.println(result);
or option 2:
System.out.println(determineOutcome(outcome, sentence));
In addition to the points other people made in their answers, it looks like your while loop is never being executed. The variables tie, win and lose are never less than 0, so the condition of the while loop is never true. You can try changing it to:
while (lose <= 0 || win <= 0 || tie <= 0);
But be warned, this will result in an infinite loop, so you may need to rethink your logic. You may not need a loop here, depending on what you're trying to do.