Java program tips [duplicate] - java

This question already has answers here:
Syntax Errors in QuizGame and Tips [closed]
(2 answers)
Closed 9 years ago.
I am trying to make a quiz game. I was wondering when I run the program, I get an infinite loop on my while statements. When I run my code after I entered the game it prints the question, but before I input my answer it gives me an Exception error. I am not quite sure on how to fix it.
/**
* #(#)QuizGameFinal2.java
*
*
* #author
* #version 1.00 2013/4/30
*/
import java.util.Scanner;
import java.lang.Math;
import java.lang.String;
public class QuizGameFinal2
{
public static void main(String[]args)
{
int option_Selected = 0;
int option_Single_Player = 1;
int option_Multiplayer = 2;
int answer = 0;
int player_One_Answer = 0;
int player_Two_Answer = 0;
String response;
int player_One_Winnings = 0;
int player_Two_Winnings = 0;
int winnings = 0;
int computer_Winnings = 0;
double computer_Answer = 0;
Scanner input2 = new Scanner(System.in);
say_Intro();
say_Before_First_Question();
question_One();
human_Answer();
while (answer < 1 && answer >= 4);
{
System.out.println("Enter a number between 1 and 3");
}
if (answer == 1)
{
System.out.println("Correct Next Question");
question_Two();
human_Answer();
while (answer < 1 && answer >= 4);
{
System.out.println("Enter a number between 1 and 3");
}
if (answer == 1 )
{
System.out.println("Correct Next Question");
question_Three();
human_Answer();
while (answer < 1 && answer > 4);
{
System.out.println("Enter a number between 1 and 3");
}
if (answer == 4)
{
System.out.println("Correct Next Question");
}
else
{
System.out.println("Incorrect you win 1000 dollers");
winnings = 1000;
}
}
else
{
System.out.println("Incorrect you win 500 dollers");
winnings = 500;
}
}
else
{
System.out.println("Incorrect you win 0 dollers");
winnings = 0;
}
} // End of main method
public static void say_Intro() // Intro Method
{
System.out.println("Welcome to the QuizGame"); // Player selects which mode
}
public static void say_Before_First_Question() // Before game method
{
System.out.println("");
System.out.println(" If you get a question wrong your out.");
System.out.println("Also you will be competing against a super computer, after you play then he will generate answers, if you have the most then you win");
System.out.println("Ok first question");
}
public static void human_Answer () // Human Answer Single Player Method
{
Scanner input2 = null;
Object answer = input2.nextInt();
}
static void player_One_Answer() // Player One Multiplayer Method
{
Scanner input2 = null;
int player_One_Answer = input2.nextInt();
}
public static void player_Two_Answer() // Player two multiplayer Method
{
Scanner input2 = null;
int player_Two_Answer = input2.nextInt();
}
public static void computer_Answer () // Computer answer
{
double computer_Answer = (1-1 + 1) * Math.random() + 1;
computer_Answer = (int)computer_Answer;
}
public static void question_One() // Question 1 method
{
System.out.println("");
System.out.println("What is an application");
System.out.println("1: A program that performs a task 2:A mouse 3: java.util.Scanner");
}
public static void question_Two() // Question 2 to 10 methods below
{
System.out.println("What is the data type that hold the value 1");
System.out.println("1: int 2:float 3: short 4: long ");
}
public static void question_Three()
{
System.out.println("What is a not a high level language");
System.out.println("1: Java 2:C++ 3: Colbolt 4: Machine Language ");
}
/* public static void question_Five()
{
}
public static void question_Six()
{
}
public static void question_Seven()
{
}
public static void question_Eight()
{
}
public static void question_Nine()
{
}
public static void question_Ten()
{
}
public static void total_Winnings_Single_Player () // Calculating who wins method single player
{
if (computer_Winnings > winnings)
{
System.out.println("Computer Wins");
}
else
{
System.out.println("You win");
}
*/
}
// I get infinite loop om my while statements and I get an exepction error on my values with null

This is because input2 is null try this:
Scanner input2 = new Scanner(System.in);

Related

Keeping a tally of how many times a number appears using a random number generator. Java

In this code I am writing here the user inputs whether or not they would like to choose heads or tails in a coinflip game. I would like to keep a tally of how many times heads appears or tails appears and output it each time it changes. After hours of trying and searching I cannot figure it our perfectly so if someone could let me know what I could utilize let me know.
import java.util.Random;
import java.util.Scanner;
public class CoinToss {
private enum Coin {
Head, Tail
}
public static void main(String[] args) {
CoinToss game = new CoinToss();
game.startGame();
}
private void startGame() {
Scanner scanner = new Scanner(System.in);
Coin guess;
while (true) {
System.out.print("Enter your guess whether the coin will be heads or tails. Type 1 for heads, 2 for tails, or 3 to quit: ");
String choice = scanner.nextLine();
if (choice.equalsIgnoreCase("3")) {
break;
} else if (choice.equalsIgnoreCase("1")) {
guess = Coin.Head;
} else if (choice.equalsIgnoreCase("2")) {
guess = Coin.Tail;
} else {
System.out.println("Please select either heads tails or quit.");
continue;
}
Coin toss = tosscoin();
if (guess == toss) {
System.out.println("You guessed correctly!");
} else {
System.out.println("You guessed incorrectly");
}
}
scanner.close();
}
private Coin tosscoin() {
Random r = new Random();
int sideup = r.nextInt(2);
if (sideup == 1) {
return Coin.Head;
} else {
return Coin.Tail;
}
}
}
You can for example add two fields in your CoinToss class. Like int heads and int tails. Initialize them with 0 in the startGame() method. Then, in the tosscoin() method:
if (sideup == 1) {
heads++;
return Coin.Head;
} else {
tails++;
return Coin.Tail;
}
You can access these fields in the startGame() method and do whatever you want with them.
You could as well define these two variables directly in the startGame() method and increment them based on the type of Coin which you get from the tosscoin() method.
Below code should work. everytime it tosses, it stores the current value in a variable and compares it next time with the toss value.
import java.util.Random;
import java.util.Scanner;
public class CoinToss {
private static int headCounter;
private static int tailCounter;
private static int previousToss;
private enum Coin {
Head, Tail
}
public static void main(String[] args) {
CoinToss game = new CoinToss();
game.startGame();
}
private void startGame() {
headCounter = 0;
tailCounter = 0;
previousToss = 0;
Scanner scanner = new Scanner(System.in);
Coin guess;
while (true) {
System.out.print("Enter your guess whether the coin will be heads or tails. Type 1 for heads, 2 for tails, or 3 to quit: ");
String choice = scanner.nextLine();
if (choice.equalsIgnoreCase("3")) {
break;
} else if (choice.equalsIgnoreCase("1")) {
guess = Coin.Head;
} else if (choice.equalsIgnoreCase("2")) {
guess = Coin.Tail;
} else {
System.out.println("Please select either heads tails or quit.");
continue;
}
Coin toss = tosscoin();
if (guess == toss) {
System.out.println("You guessed correctly!");
} else {
System.out.println("You guessed incorrectly");
}
}
scanner.close();
}
private Coin tosscoin() {
Random r = new Random();
int sideup = r.nextInt(2);
Coin currentGuess;
if (sideup == 1) {
headCounter++;
currentGuess = Coin.Head;
} else {
tailCounter++;
currentGuess = Coin.Tail;
}
checkIfFlipped(sideup);
return currentGuess;
}
static void checkIfFlipped(int currentToss) {
if (currentToss != previousToss) {
if (currentToss == 0) {
System.out.println("Coin fliped from head to tail");
} else {
System.out.println("Coin fliped from tail to head");
}
}
previousToss = currentToss;
}
}

java game with tries options

I'm making a Guessing Game using Java and I need to add an option to count the number of guesses, but if the player gives the same answer multiple times, It will be count that as 1 try.
I don’t know how to proceed. Any help will be appreciated :)
Here's my current script:
import java.util.Scanner;
public class GuessTheNumber {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
int count = 0;
int a = 1 + (int) (Math.random() *9);
int guess = 0;
System.out.printf("Guess the number from 1 - 10: ");
while (guess != a) {
guess = keyboard.nextInt();
count++;
if (guess > a) {
System.out.printf("Lower!: ");
} else if (guess < a) {
System.out.printf("Higher!: ");
}
}
System.out.println("Congratulations! You guessed the number with "
+ count + " tries.");
}
}
You need to track all user's answers using a list so that you can iterate to the list if a similar answer exists before incrementing.
here it's pal
public class GuessTheNumber {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
ArrayList<Integer> answers = new ArrayList<Integer>();
;
int count = 0;
int a = 1 + (int) (Math.random() * 9);
int guess = 0;
System.out.printf("Guess the number from 1 - 10: ");
while (guess != a) {
guess = keyboard.nextInt();
boolean isAnswered = false;
for (Integer answer : answers) {
if (guess == answer) {
isAnswered = true;
break;
}
}
if (!isAnswered) {
count++;
answers.add(guess);
}
if (guess > a) {
System.out.printf("Lower!: ");
} else if (guess < a) {
System.out.printf("Higher!: ");
}
}
System.out.println("Congratulations! You guessed the number with "
+ count + " tries.");
}
}

Not sure how to do a while loop in this situation

I am writing a program to take the input for a sequence
import java.util.Scanner;
public class FibonacciCode {
public static void main(String[] args) {
System.out.println("Enter a number");
int count, number0 = 0, number1 = 1, loop = 0;
Scanner userInput = new Scanner(System.in);
count = userInput.nextInt();
while(loop > count)
{
System.out.print(number0 + ", ");
int sum = number0 + number1;
number0 = number1;
number1 = sum;
loop++;
}
}
}
This should be a usable implementation:
public class Menu {
public static void main(String[] args) {
Scanner a = new Scanner(System.in);
boolean orderCompleted = false;
while(!orderCompleted) {
printMenu();
String orderString = a.nextLine();
int order = Integer.parseInt(orderString);
int total = 0;
if(order == 1) {
} else if(order == 2) {
} else if(order == 3) {
} else if(order == 4) {
} else if(order == 5) {
}
System.out.println("Would you like to order more? Press 'y' to continue or 'n' to finish order.");
orderString = a.nextLine();
if(orderString.equals("n")){
orderCompleted = true;
}
}
}
private static void printMenu() {
System.out.println("Welcome to Hess Burgers");
System.out.println("1- Cheeseburger.............$7");
System.out.println("2- Barbeque Burger..........$8");
System.out.println("3- Southwestern Burger......$9");
System.out.println("4- Bacon Cheeseburger.......$10");
System.out.println("5- Double Stack Burger......$11");
System.out.println("");
System.out.print("Please enter your order selection:");
}
}
I pulled the menu printing to a separate method, and re-used scanner a as well as re-using the orderString. The while loop checks a completedOrder boolean flag, so that it can be used to do completion tasks prior to exiting the order loop if need be.
import java.util.Scanner;
public class FibonacciCode {
public static void main(String[] args) {
System.out.println("Enter a number");
int count, number0 = 0, number1 = 1, loop = 0;
Scanner userInput = new Scanner(System.in);
count = userInput.nextInt();
while(loop > count)
{
System.out.print(number0 + ", ");
int sum = number0 + number1;
number0 = number1;
number1 = sum;
loop++;
}
}
}
A while loop does whatever is in the block as long as the condition is true, in your case, you are simply repeating order = b.nextInt() until something other than 'y' is given as input
while (continuePlay= b.nextLine().equalsIgnoreCase ("y")) {
order = b.nextInt(); // This is inside the block
}
you should use a do while loop instead, like so:
do{
System.out.println("Welcome to Hess Burgers");
System.out.println("1- Cheeseburger.............$7");
System.out.println("2- Barbeque Burger..........$8");
System.out.println("3- Southwestern Burger......$9");
System.out.println("4- Bacon Cheeseburger.......$10");
System.out.println("5- Double Stack Burger......$11");
System.out.println(" ");
System.out.print("Please enter your order selection:");
Scanner a = new Scanner(System.in);
int order = a.nextInt();
int total = 0;
boolean continuePlay = true;
if (order == 1 ) {
} else if (order == 2) {
} else if (order == 3) {
} else if (order == 4) {
} else if (order == 5) {
}
Scanner b = new Scanner(System.in);
System.out.println("Would you like to order more? Press 'y' to continue or 'n' to finish order.");
} while (continuePlay= b.nextLine().equalsIgnoreCase ("y"));
Also I'd recommend reading some basic programming books or tutorials instead of going directly to Stack Overflow.

I am trying to call a variable from a different class so I can update the variable [closed]

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 5 years ago.
Improve this question
I haven't asked many questions on here so sorry if I have laid this question out wrongly.
I am trying to call the variable AmountOfTickets in the main class. So I can update it with each loop of the while loop. I don't know how to properly call the variable without eclipse showing an error.
This is the class where I have created the variable AmountOfTickets which
I am trying to update
public class TicketHandler {
public int TicketCost;
public static int AmountOfTickets;
public TicketHandler(int TicketCost, int AmountOfTickets){
this.TicketCost = TicketCost;
this.AmountOfTickets = AmountOfTickets;
}
public TicketHandler() {
TicketCost = 200;
AmountOfTickets = 50;
}
public int getTicketCost() {
return TicketCost;
}
public void setTicketCost(int ticketCost) {
TicketCost = ticketCost;
}
public static int getAmountOfTickets() {
return AmountOfTickets;
}
public void setAmountOfTickets(int amountOfTickets) {
AmountOfTickets = amountOfTickets;
}
public void ReduceNoOfTickets(int TicketsSold) {
this.AmountOfTickets = this.AmountOfTickets - TicketsSold;
}
}
This is the main program code where I am trying to call the variable and used it
import java.util.Scanner;
public class ApplicationProgram {
static Scanner inKey = new Scanner(System.in);
public static void main(String[] args) {
TicketHandler Red = new TicketHandler (200,50);
TicketHandler Green = new TicketHandler (200,50);
TicketHandler Blue = new TicketHandler (200,50);
TicketHandler Yellow = new TicketHandler (200,50);
boolean running = true;
//Main menu
while (running) {
printMenu();
int KeyIn = inKey.nextInt();
//menu
switch (KeyIn) {
case 1:{
RedRoute();
break;
}
case 2:{
GreenRoute();
break;
}
case 3:{
BlueRoute();
break;
}
case 4:{
YellowRoute();
break;
}
case 5:{
ShowAvailableTicketsAndPrice();
break;
}
case 6:{
System.out.println("Do you wish to quit: type Y to confirm");
String quitYN = inKey.next ();
//System.out.println(quitYN);
if ((quitYN.matches("Y")) || (quitYN.matches("y"))) {
System.out.println("Goodbye\n\n");
running = false;
System.exit(0);
}
break;
}
default:{
System.out.println("Not a valid option, try again.");
break;
}
}
}
}
public static void printMenu(){
System.out.println("Bus Tickets");
System.out.println("---- ----");
System.out.println("1. \tRedRoute");
System.out.println("2. \tGreenRoute");
System.out.println("3. \tBlueRoute");
System.out.println("4. \tYellowRoute");
System.out.println("5. \tShowAvailableTicketsAndPrice");
System.out.println("6. \tQuit");
}
public static void RedRoute(){
Scanner Red = new Scanner(System.in);
System.out.println();
int count = 200;
while (count <= 200) {
System.out.println("Insert £" + count);
int KeyIn = Red.nextInt();
count = count - KeyIn;
if (count == 0){
System.out.println("Enjoy");
break;
}
}
}
public static void GreenRoute(){
Scanner Red = new Scanner(System.in);
System.out.println();
int count = 200;
while (count <= 200){
System.out.println("Insert £" + count);
int KeyIn = Red.nextInt();
count = count - KeyIn;
if (count == 0){
System.out.println("Enjoy");
break;
}
}
}
public static void BlueRoute(){
Scanner Red = new Scanner(System.in);
System.out.println();
int moneyin = 200;
while (moneyin <= 200){
System.out.println("Insert £" + moneyin);
int KeyIn = Red.nextInt();
moneyin = moneyin - KeyIn;
if (moneyin == 0){
System.out.println("Enjoy");
AmountOfTickets = get.AmountOfTickets - 1
break;
}
}
}
public static void YellowRoute(){
Scanner Red = new Scanner(System.in);
System.out.println();
int count = 200;
while (count <= 200) {
System.out.println("Insert £" + count);
int KeyIn = Red.nextInt();
count = count - KeyIn;
if (count == 0){
System.out.println("Enjoy");
break;
}
}
}
public static void ShowAvailableTicketsAndPrice(){
System.out.println("Routes available:");
System.out.println("\tRed route, Tickets left: "+ "Price: ");
System.out.println("\tBlue route, Tickets left: " + "Price: ");
System.out.println("\tGreen route, Tickets left: " + "Price: ");
System.out.println("\tYellow route, Tickets left: " + "Price: ");
}
}
Thank you.
First of all, your var called AmountOfTickets is static, it means one copy will live to all objects, also your method getAmountOfTickets.
you have a problem here
AmountOfTickets = get.AmountOfTickets - 1
you must call the variable using the ClassName.YourVar like this:
TicketHandler.AmountOfTickets = TicketHandler.getAmountOfTickets() - 1;
also your method.
Also you could import a static like this:
import java.util.Scanner;
import static huh.TicketHandler.*;
so you can use:
AmountOfTickets = getAmountOfTickets() - 1;
"You could think in create an object and call the var like this"
public static void BlueRoute(){
Scanner Red = new Scanner(System.in);
TicketHandler objectOne = new TicketHandler(); //HERE I CREATED AN OBJECT
System.out.println();
int moneyin = 200;
while (moneyin <= 200)
{
System.out.println("Insert £" + moneyin);
int KeyIn = Red.nextInt();
moneyin = moneyin - KeyIn;
if (moneyin == 0){
System.out.println("Enjoy");
objectOne.AmountOfTickets = objectOne.getAmountOfTickets() - 1; //HERE I USED IT
break;
}
But as this is static it will replace objectOne to
TicketHandler.AmountOfTickets = TicketHandler.getAmountOfTickets() - 1; //HERE I USED IT
So, in my humble opinion you can or use an import static (so you avoid to write the same class name before your static), or put the name of your class first then the name and method.
Using an import static could be bad if there is another class with the same name or method as yours and you imported, because compiler could say, hey which one am I suppose to use?
So, I'd rather use fullnameClass.varOrMethod
hope it helps
btw using this: TicketHandler.AmountOfTickets and this: TicketHandler.getAmountOfTickets() are avable to be used in all ApplicationProgra's class code as i said because it is static, and because you difined them public
public static int AmountOfTickets;
public static int getAmountOfTickets() {
return AmountOfTickets;
}
=) i guess that was what you asked for. c-ya

While loop behaving unexpectedly in Java

I'm trying to get my loop to go over and over again until the user types in "quit" then it will quit.
Basically I'm trying to get my Finch robot to change nose color depending on how it's positioned, but I'm confused on how to get it to allow the user to position it again after it has already been positioned so that the nose color can change color multiple times. When it first runs the Finch will execute the code but quits immediately afterwards.
Here is my code:
public class finch {
public static final int INCREASE = 20;
public static final int SEC = 1000;
public static final int MAXSPEED = 255;
public static final int HALFSEC = 500;
public static Finch myFinch;
public static void main(String[] args) {
myFinch = new Finch();
Menu();
}
public static void Menu() {
Scanner console = new Scanner(System.in);
System.out.println("Enter your choice:" + "");
int input;
int input1;
boolean flag=true;
while(flag){
System.out.println("1.\t" + "Rolling" + "Finch");
System.out.println("2.\t" + "Obedient" + "Finch");
System.out.println("3.\t" + "Exit");
System.out.println();
System.out.println("Enter your choice:");
System.out.println();
input = console.nextInt();
flag=false;
if (input == 1) {
//input = DarkFinch;
System.out.println("Position the Finch \"down\" or \"up\" to change nose color");
rolling(myFinch);
} else if (input == 2) {
// input = ChasetheFinch;
// System.out.println("Chase The Finch");
} else if (input == 3) {
// input = Exit;
System.out.println("Goodbye");
} else {
// System.out.println("Try again");
flag=true;
/* return Menu(); */
}
}
}
public static boolean rolling(Finch myFinch) {//This method will change the Finches nose color depending on the Finches position.
//"up" = place the finch upright standing on its tail
for (int i = 1; i <= 20; i++) {
while (myFinch.isBeakDown() || myFinch.isBeakUp()) {
if (myFinch.isBeakDown()) {
myFinch.setLED(0,0,255,3000);
} else if (myFinch.isBeakUp()) {
myFinch.setLED(255,0,0,3000);
} else {
myFinch.setLED(0,0,0,5000);
}
}
}
return true;
}
}
Don't set your flag = false before the condition on the input value. Set it to false in the if(input == 3) case

Categories

Resources