Magic 8ball Using securerandom with switch statements and while loops - java

I have my following code working like this:
import java.util.Scanner;
import java.lang.Math;
public class Magiceightball {
private static void Number() {
int magic = (int) Math.ceil(Math.random() * 10);
String x;
switch (magic)
{
case 1: x = "Yes.";
break;
case 2: x = "No.";
break;
case 3: x = "The odds are in favor.";
break;
case 4: x = "The odds are against you.";
break;
case 5: x = "Never.";
break;
case 6: x = "Definitely!";
break;
case 7: x = "Maybe.";
break;
case 8: x = "I don't think so.";
break;
case 9: x = "I'd say no.";
break;
case 10: x = "Probably.";
break;
default: x = "Try Again.";
break;
}
System.out.println(x);
}
public static void main (String [ ] args)
{
Scanner scan = new Scanner(System.in);
boolean a = true;
while (a)
{
System.out.println();
System.out.println();
System.out.println("What would you like to ask the Magic Eight Ball? Make it a \"Yes\" or \"No\" question for it to work.");
System.out.print("\n\n--> ");
String what = scan.nextLine();
System.out.println();
Number();
System.out.println();
System.out.println();
System.out.println();
System.out.println("Would you like to go again? Enter \"Y\" for yes, and \"N\" for no.");
System.out.print("\n\n--> ");
String run = scan.nextLine();
run = run.toLowerCase();
if (run.equals("n"))
{
a = false;
}
}
}
} `
My dilemma is, I want all these methods being used the switch statement, the while loop but I want to replace the Math.random with the SecureRandom method how would I go about doing that?
I tried using the whole SecureRandom randomNumber = new SecureRandom(); to do it but it kept giving me errors that I could not convert secure random to "int".

You just need to instantiate a SecureRandom object and use its nextInt() method:
Random rand = new SecureRandom();
int magic = 1 + rand.nextInt(10);

You can use this function:
public static int generateRandomInteger(int min, int max) {
SecureRandom rand = new SecureRandom();
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
Call it with
int magic = generateRandomInteger(1,10); // to get a number between 1 and 10.

Related

How i can use the string in switch case as an action?

I'm trying to code a Calculator on Java but in the switch statement, it takes the operation as a String, how can I transform it into an action?
switch(op) {
case 1: operation = "res= a + b";
break;
case 2: operation = "res = a - b";
break;
case 3: operation = "res = a * b";
break;
case 4: operation = "res = a / b";
break;
}
System.out.println(operation);
If I remove the quotes it says that I haven't initialized the variables. They are asked after choosing the operation.
EDIT:
I was applying the wrong logic to the program.
Don't perform the operation until you have the arguments:
import static java.lang.Integer.*;
import java.util.*;
class t1 {
static void calc(Scanner in) {
System.out.print("Operation: ");
int op = in.nextInt();
System.out.print("a: ");
int a = in.nextInt();
System.out.print("b: ");
int b = in.nextInt();
int res = 0;
switch(op) {
case 1:
res = a + b;
break;
case 2:
res = a - b;
break;
case 3:
res = a * b;
break;
case 4:
res = a / b;
break;
default:
System.out.println("Invalid operation");
System.exit(-1);
}
System.out.println(res);
}
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
while (true) {
calc(in);
}
}
}
You could verify the operation before asking for the operands, with an additional switch statement.
There are ways to set the operation before obtaining the operands, but it's best to learn to walk before you run.

How would you give the user the option to exit the program after answering 4 consecutive questions correctly?

I'm attempting to give the user the option to exit the program after he/she gets 4 multiplication questions correct. If he/she chooses to continue, I have to give him/her another chance to exit each time. I hope that makes sense.. My posted code works but I have a feeling that I will have to change some things in order to give user the option to terminate.
import java.security.SecureRandom; //program will use random numbers
import java.util.Scanner; //program will need user input
public class RandomMultiplication
{
public static void main(String[] args)
{
while(true)//continues to play game
{
question();
}
}
public static void question()
{
boolean repeat = false;
SecureRandom randomNumbers = new SecureRandom();
//pick random numbers (1-9) for multiplication scenario
int number1 = randomNumbers.nextInt(10); //first number
int number2 = randomNumbers.nextInt(10); //second number
while(!repeat)
{
int responseCode = randomNumbers.nextInt(4);
if(multiplicationProblem(number1,number2))
{
switch(responseCode)
{
case 0: System.out.println("Very Good!");
break;
case 1: System.out.println("Excellent!");
break;
case 2: System.out.println("Keep up the good work!");
break;
case 3: System.out.println("Nice work!");
break;
}//ends switch
repeat = true; //stops repeating the same question
}//end if statement
else
{
responseCode = randomNumbers.nextInt(4);
switch(responseCode)
{
case 0: System.out.println("No. Please try again!");
break;
case 1: System.out.println("Wrong, Try once more!");
break;
case 2: System.out.println("Don't give up!");
break;
case 3: System.out.println("No. Keep trying!");
break;
}//ends switch
}//ends else condition
}//ends while loop
}
public static boolean multiplicationProblem(int number1, int number2)
{
Scanner input = new Scanner(System.in);
int userInputAnswer;
int correctCounter = 0;
System.out.printf("How much is %d times %d?", number1, number2);
userInputAnswer = input.nextInt();
if (userInputAnswer == number1 * number2)
{
return true;
}
else
{
return false;
}
}
}

Why is the if statement not evaluated every loop

Ok I am making a simple text based game and I am unsure why and infinite loop is being created. Its not really infinite but I am unsure why the if statement is not evaluated every loop. Here is the whole program. The if Statement I need fixed is in the roomEight method which is at the end of the code.
//********************************
// A simple game that moves the
// player though the map
//********************************
import java.util.*;
import java.text.*;
public class mazegame
{
private static Scanner scan = new Scanner (System.in); // starts scanner for the program
public static Scanner scanS;
// ScanS is a scanner for strings.
// To call this variable type mazegame.scanP;
public static int lifeCount = 15;
public static int damage = 1;
// imp stats
public static int impAmount = 0;
public static int impDamage = 1;
public static int impLife = 1;
// Low level monster stats
// m followed by a number stands for monster then the level of monster
public static int m1health = 5;
public static int m1damage = 2;
// High level monster
public static int m2health = 10;
public static int m2damage = 2;
// Boss stats
public static int bosshealth = 30;
public static int bossdamage = 10;
// Placement of player
public static int placement = 3;
public static String movement;
public static int scanVal; // holder a scanner value generic.
public static void main(String[] args)
{
System.out.println("You wake up on a cold hard floor");
time();
System.out.println("you are unsure how you got there.");
time();
System.out.println("There is an opening a head");
time();
System.out.println("you walk forward into the opening the ground begins to tremble");
time();
System.out.println("the wall behind you closes you are trapped.");
time();
time();
clear(); // clears screen for user.
roomThree();
}
public static void timeHalfSec()
{
try
{
Thread.sleep(500); //1000 milliseconds is one second.
}catch(InterruptedException ex)
{
Thread.currentThread().interrupt();
}
}
public static void time()
{
try
{
Thread.sleep(1500); //1000 milliseconds is one second.
}catch(InterruptedException ex)
{
Thread.currentThread().interrupt();
}
}
public static void clear()
{
final String ANSI_CLS = "\u001b[2J";
final String ANSI_HOME = "\u001b[H";
System.out.print(ANSI_CLS + ANSI_HOME);
System.out.flush();
}
public static void position(int placement)
{
switch( placement )
{
//********************************
// For each room create a method and
// call it in this switch statement.
//********************************
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
break;
case 6:
break;
case 7:
break;
case 8: roomEight();
break;
case 9:
break;
case 10:
break;
case 11:
break;
case 12:
break;
case 13:
break;
case 14:
break;
case 15:
break;
case 16:
break;
case 17:
break;
case 18:
break;
case 19:
break;
case 20:
break;
case 21:
break;
case 22:
break;
case 23:
break;
case 24:
break;
case 25:
break;
}
}
public static void askMove()
{
System.out.println("You can walk forward, left , or right. Beware the imps.");
System.out.println("Enter L for left, R for right, and F for forward.");
time();
System.out.print("Move:");
movement = scan.nextLine();
}
public static void roomThree()
{
askMove();
//--------------------------------
// This switch stament is only for this room
//--------------------------------
switch ( movement )
{
case "l":
case "L":
placement = 2;
System.out.println("Changing rooms Please wait");
time();
clear();
break;
case "r":
case "R":
placement = 4;
System.out.println("Changing rooms Please wait");
time();
clear();
break;
case "f":
case "F":
placement = 8;
System.out.println("Changing rooms Please wait");
time();
clear();
break;
}
// The switch statement changes position and position calls the next room method.
position(placement);
}
public static void roomEight()
{
System.out.print ("You have just entered a new room.");
System.out.print ("There is an imp ahead would you like to see its stats? 1 for yes and 0 ");
impAmount = 1;
scanVal = scan.nextInt();
if(scanVal == 1 )
{
impStats();
}
System.out.println("Would you like to hit the imp? 1 for yes and 0 for no.");
scanVal = scan.nextInt();
while (impAmount != 0)
{
if (scanVal == 1)
{
impAmount = 0;
damage++;
lifeCount = 15;
System.out.println("You killed an imp! You found brass knuckles your damage increased by one. Here are your stats");
playerStats();
}else{
lifeCount--;
System.out.println("The imp hit you. You took one damage");
playerStats();
timeHalfSec();
dead();
}
}
}
public static void playerStats()
{
System.out.println("*----------------*");
System.out.println("Your Hearts: " + lifeCount);
System.out.println("Your Damage: " + damage);
System.out.println("*----------------*");
}
public static void impStats()
{
System.out.println ("*----------------*");
System.out.println("Amount of Imps: " + impAmount);
System.out.println("Imp Health: 1");
System.out.println("impDamage: 1");
System.out.println("*----------------*");
}
public static void dead()
{
if(lifeCount < 1)
{
System.exit(0);
}
}
}
//********************************************************************************************************************************
// Places to look for code and things to look up.
// Lookup: .equalsIgnoreCase, global scanner.
// Places to look for code:
// http://stackoverflow.com/questions/23586732/how-to-make-a-one-static-scanner-global-variable-without-closing-scan-constantly
// https://www.youtube.com/watch?v=zijvKOjnmwY
// http://stackoverflow.com/questions/16706716/using-two-values-for-one-switch-case-statement
// http://www.csci.csusb.edu/dick/samples/java.classes.html#System
// http://stackoverflow.com/questions/22452930/terminating-a-java-program
//
//
//
//********************************************************************************************************************************
You'd probably want to move the following two lines into the loop :
System.out.println("Would you like to hit the imp? 1 for yes and 0 for no.");
scanVal = scan.nextInt();
As I can see, you scan the nextInt that a user enter, you do stuff with it and then you re-scan the nextInt. The problem with that is when you use the scanner and ask for a single int, there is still the new-line char in the scanner ('\n'). Thus, when you ask a second time for the int, this will return the new line char. My understanding of all this is not on point, but what you have to do is one of those solution :
Use nextLine instead of nextInt and parse the string value into an Int. This will clear the buffer, and you will be able to validate if the user entered a valid Int. You'd do it like this :
String scanVal = scan.nextLine();
//You can add some try catch in order to validate the int being parsed
int choice = Integer.parseInt(scanVal);
Or you can clear the buffer after you have scanned your int by calling scan.nextLine()after scan.nextInt()
Hope this helps!

Ordinals java - Java I class

Stuck on getting the prompt to enter a number 1 to 10 - and results should add the st, rd, th, and nd to the number.
Write a program that prompts the user to enter any integer from 1 to 10 and then displays the integer in ordinal form with suffix attached.
public class Ordinals {
public static String Ordinals(int i) {
System.out.println("Enter an integer between 0 to 10: ");
Scanner input = new Scanner(System.in);
int hundred = value % 100;
int tens = value % 10;
if (hundred - tens == 10) {
return "th";
}
switch (tens) {
case 1:
return "st";
case 2:
return "nd";
case 3:
return "rd";
default:
return "th";
}
public static void main(String[] args) {
Ordinals number = new Ordinals();
for (int i = 1; i <= 10; i++) {
String st = number.Ordinals(i);
System.out.println(i + " = " + i + st);
}
}
}
In my opinion it would be better to move Scanner to main:
public static void main(String[] args) {
Ordinals number = new Ordinals();
Scanner input = new Scanner(System.in);
while(true){
System.out.println("Enter an integer between 0 to 10: ");
int i = input.nextInt();
System.out.println(i+number.Ordinals(i));
}
}
and then add to Ordinals:
int value = i;
Method will be independent form input type.
Add value = input.nextInt() under the line creating Scanner.

find binary representation in array

i need to make a switch statement that can use the appropriate conversion method. here is my code
public class ExerciseTwo
{
public static void main (Strings[] args)
{
Scanner input = new scanner(system.in);
String[] binary = { "0","1","2","3","4","5","6","7","8"};
for (c = 0; c < array.length; counter++)
binary[] = input.nextInt();
System.out.println("Enter number between 0 and 8");
number = input.nextInt();
system.out.printf("the number", "number_given", "is", "binaryVersion", "binary");
}
}
I'm sorry, but the description wasn't very clear to me. Are you simply trying to convert the input value (between 0 and 8) into a binary format (as in 2 -> 10, 7 -> 111) using a switch statement? If so, this code will work. If not, can you clarify the question for me?
Thanks!
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Enter number between 0 and 8");
int number = input.nextInt();
int binaryRepresentation = -1;
switch (number)
{
case 0:
binaryRepresentation = 0;
break;
case 1:
binaryRepresentation = 1;
break;
case 2:
binaryRepresentation = 10;
break;
case 3:
binaryRepresentation = 11;
break;
case 4:
binaryRepresentation = 100;
break;
case 5:
binaryRepresentation = 101;
break;
case 6:
binaryRepresentation = 110;
break;
case 7:
binaryRepresentation = 111;
break;
case 8:
binaryRepresentation = 1000;
break;
}
System.out.printf("the number " + number + " is " + binaryRepresentation + " in binary (-1 means invalid input)");
}
Do your home work yourself , Look at the http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html switch case definition. If you really want good solution for binary representation then look at API documentation of the Integer class
http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html?is-external=true
Using the API doc is one of the first things you need to learn as a Java programmer.

Categories

Resources