How do I round my numbers of output += Math.pow(baseUno, powernumber)+ " "; to the nearest whole number?
They always give me an output of, for example, 1.0 or 2.0. How do you round these so that they would simply result as 1 and 2?
import javax.swing.*;
import java.text.*;
import java.util.*;
public class level7Module1
{
public static void main(String[] args)
{
String base, power, output = " "; //user inputs, and the output variable
double baseUno, powerUno, basenum = 0, powernum = 0; //user inputs parsed so they can be used in mathematical equations
DecimalFormat noDigits = new DecimalFormat("0");
// oneDigit.format(variablename)
base = JOptionPane.showInputDialog(null,"Enter your prefered base, a number between 1 and 14: \nPress 'q' to quit."); //User input
if (base.equals("q"))
{
JOptionPane.showMessageDialog(null,"Goodbye!");
System.exit(0); //quits
}
baseUno = Integer.parseInt(base);
// basenum = noDigits.format(baseUno);
if (baseUno <= 0)
{
JOptionPane.showMessageDialog(null,"Really? Why would you try to trick me? ):");
System.exit(0);
}
if (baseUno > 14)
{
JOptionPane.showMessageDialog(null,"That wasn't cool. Take some time to think about this \nand\nthen\ntry\nagain.\n\n\n\n\n\n\n\nJerk.");
System.exit(0);
}
//I chose 0 and 14 because on my monitor the combination of 14 and 14 filled up the entire screen, so I limited to things
//that would fit on my monitor :)
power = JOptionPane.showInputDialog(null, "How many numbers of this base would you like? Between 1 and 14 again, please.\nPress 'q' to quit.");
if (power.equals("q"))
{
JOptionPane.showMessageDialog(null,"Goodbye!");
System.exit(0);
}
powerUno = Integer.parseInt(power);
// powernum = noDigits.format(powerUno);
if (powerUno <= 0)
{
JOptionPane.showMessageDialog(null,"Really? Why would you try to trick me? ):");
System.exit(0);
}
if (powerUno > 14)
{
JOptionPane.showMessageDialog(null,"That wasn't cool. Take some time to think about this \nand\nthen\ntry\nagain.\n\n\n\n\n\n\n\nJerk.");
System.exit(0);
}
for (int powernumber=0; powernumber!=powerUno; powernumber++) //Set the number of powers done to 0, then until it's "powernum" input, it keeps going.
{
output += Math.pow(baseUno, powernumber)+ " "; //Output is the basenum to the power of powernum plus a space, then repeats condition above.
}
JOptionPane.showMessageDialog(null,"Your numbers are: " + output); //Giving the users their outputs
}
}
To the simplest approach change this line :
JOptionPane.showMessageDialog(null,"Your numbers are: " + output);
to
JOptionPane.showMessageDialog(null,"Your numbers are: " + (int)output);
just type caste the result to int
Related
I am working a Collatz Conjecture Calculator that allows the user to enter the numbers into the calculator however, I am unsure why I am not meeting the specified output. The follwing are the test cases I am unable to meet, but I am unsure how I am wrong because it seems it prints as expected
TESTS FAILED...
java.lang.AssertionError:
Expected: a string containing "Enter the starting number:\nEnter the upper limit:\n90...45...136...68...34!\nOperation performed 4 times, and the resulting number is 34.\nDo you want to continue the calculations 5 more times? (yes/no)\n34...17...52...26...13!\nOperation performed 8 times, and the resulting number is 13.\nDo you want to continue the calculations 5 more times? (yes/no)\nDo you want to use the calculator again? (yes/no)"
but: was "Welcome to Collatz Conjecture Calculator!
Calculate with upper limit
Calculate until the end
Enter the starting number:
Enter the upper limit:
90...45...136...68...34!
Operation performed 4 times, and the resulting number is 34.
Do you want to continue the calculations 5 more times? (yes/no)
34...17...52...26...13!
Operation performed 8 times, and the resulting number is 13.
Do you want to continue the calculations 5 more times? (yes/no)
Operation performed 8 times, and the resulting number is 13.
Do you want to use the calculator again? (yes/no)
Thanks for using Collatz Conjecture Calculator!
"
java.lang.AssertionError:
Expected: a string containing "Welcome to Collatz Conjecture Calculator!\n1. Calculate with upper limit\n2. Calculate until the end\nEnter the starting number:\nEnter the upper limit:\n100...50...25...76...38!\nOperation performed 4 times, and the resulting number is 38.\nDo you want to continue the calculations 5 more times? (yes/no)\nDo you want to use the calculator again? (yes/no)\n1. Calculate with upper limit\n2. Calculate until the end\nEnter the starting number:\nEnter the upper limit:\n60...30...15...46...23...70...35!\nOperation performed 6 times, and the resulting number is 35.\nDo you want to continue the calculations 7 more times? (yes/no)\nDo you want to use the calculator again? (yes/no)\nThanks for using Collatz Conjecture Calculator!"
but: was "Welcome to Collatz Conjecture Calculator!
Calculate with upper limit
Calculate until the end
Enter the starting number:
Enter the upper limit:
100...50...25...76...38!
Operation performed 4 times, and the resulting number is 38.
Do you want to continue the calculations 5 more times? (yes/no)
Operation performed 4 times, and the resulting number is 38.
Do you want to use the calculator again? (yes/no)
Calculate with upper limit
Calculate until the end
Enter the starting number:
Enter the upper limit:
60...30...15...46...23...70...35!
Operation performed 6 times, and the resulting number is 35.
Do you want to continue the calculations 7 more times? (yes/no)
Operation performed 6 times, and the resulting number is 35.
Do you want to use the calculator again? (yes/no)
Thanks for using Collatz Conjecture Calculator!
"
END OF TEST FAILURES
{
public static void main(String[] args) {
String welcome = "Welcome to Collatz Conjecture Calculator!";
String optionOne = "1. Calculate with upper limit";
String optionTwo = "2. Calculate until the end";
String initialNumPrompt = "Enter the starting number:";
String upperLimitPrompt = "Enter the upper limit:";
String result = "Operation performed %d times, and the resulting number is %d.";
String unfinishedPrompt = "Do you want to continue the calculations %d more times? (yes/no)";
String againPrompt = "Do you want to use the calculator again? (yes/no)";
String farewellPrompt = "Thanks for using Collatz Conjecture Calculator!";
Scanner scanner = new Scanner(System.in);
String userChoice = "yes";
System.out.println(welcome);
while (userChoice.equals("yes")) {
System.out.println(optionOne);
System.out.println(optionTwo);
int option = scanner.nextInt();
scanner.nextLine();
while (option != 1 && option != 2) {
System.out.println(optionOne);
System.out.println(optionTwo);
option = scanner.nextInt();
scanner.nextLine();
}
System.out.println(initialNumPrompt);
int number = scanner.nextInt();
scanner.nextLine();
int counter = 0;
if (option == 1) {
System.out.println(upperLimitPrompt);
int limit = scanner.nextInt() - 1;
scanner.nextLine();
while (number != 1 && counter < limit) {
System.out.print(number + "...");
if (number % 2 == 0) {
number /= 2;
} else {
number = 3 * number + 1;
}
counter++;
}
if (number == 1) {
System.out.println("1!");
} else {
System.out.println(number + "!");
String continueCalculation = "yes";
while (continueCalculation.equals("yes") && number != 1) {
System.out.printf(result, counter, number);
System.out.printf(unfinishedPrompt, limit + 1);
continueCalculation = scanner.next();
if (continueCalculation.equals("yes")) {
int i = 0;
while (i < limit && number != 1) {
System.out.print(number + "...");
if (number % 2 == 0) {
number /= 2;
} else {
number = 3 * number + 1;
}
counter++;
i++;
}
if (number == 1) {
System.out.println("1!");
} else {
System.out.println(number + "!");
}
}
}
}
} else {
while (number != 1) {
System.out.print(number + "...");
if (number % 2 == 0) {
number /= 2;
} else {
number = 3 * number + 1;
}
counter++;
}
System.out.println("1!");
}
System.out.printf(result , counter, number);
System.out.println(againPrompt);
userChoice = scanner.next();
}
System.out.println(farewellPrompt);
}
}
I made sure that everything was printed on a new line, however you do not see that reflected in my code because it did not solve the problem
I am having a problem with my program. When I compile and run my program everything runs great until it's time to display the guesses back to the user. when that happens the last guess always gets displayed as 0.
My assignment is to develop a program that simulates the high-low game. For each execution of the program, the game will generate a random number in the inclusive range of 1 to 100. The user will have up to 10 chances to guess the value. The program will keep track of all the user’s guesses in an array. For each guess, the program will tell the user if his/her guess was too high or too low. If the user is successful, the program will stop asking for guesses, display the list of guesses, and show a congratulatory message stating how many guesses he/she took. If the user does not guess the correct answer within 10 tries, the program will display the list of guesses and show him/her the correct value with a message stating that he/she was not successful. Regardless of the outcome, the program will give the user a chance to run the program again with a new random number.
This is what I have so far:
import java.util.Random;
import java.util.Scanner;
/**
*
* #author jose
*/
public class Assignment7
{
/*
*/
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int number;
String again = "y";
while (again.equalsIgnoreCase("y"))
{
int[] guesses = new int[10];
int tries = 0;
number = GetRandomNumber(1, 100);
System.out.println(number); // delete before submitting
int userGuess = GetUserGuess(1,100);
while (userGuess != number && tries < guesses.length - 1 )
{
guesses[tries] = userGuess;
LowOrHigh(number, userGuess);
userGuess = GetUserGuess(1, 100);
tries++;
}
if (tries != 10)
{
userGuess = guesses[tries];
tries++;
System.out.println("Congratulations! You were able to guess the correct number");
}
else
{
System.out.println("Sorry! You were not able to guess the correct number");
}
if (tries == 10)
{
System.out.println("Your guesses were incorrect");
System.out.print("You guessed: ");
for ( int i = 0; i < 10 ; i++)
{
System.out.print(guesses[i] + ", ");
}
System.out.println("The random number generated was " + number);
}
else
{
System.out.println("Well done! You were able to guess the "
+ "correct number in under 10 tries");
System.out.print("You guessed: ");
for ( int i = 0; i < tries; i++)
{
System.out.print(guesses[i] + " ");
}
System.out.println("The random number generated was "
+ number + ", it only took you " + tries + " tries.");
}
System.out.println("");
System.out.print("Do you wish to try again with a different "
+ "number? (Enter y or n ): ");
again = input.next();
System.out.println("");
}
}
/*
METHOD 1
Description
A method that generates the random number to be guessed returns the
random number to main. Two parameters are the two numbers needed to generate
the random number (1 and 100 in this case).
*/
public static int GetRandomNumber (int rangeLow, int rangeHigh)
{
Random gen = new Random();
int number;
number = gen.nextInt(rangeHigh) + rangeLow;
return number;
}
/*
METHOD 2
This method tells the user if the guess is too low or too high. It will have
2 parameters one for the random number and the second is the user guess.
*/
public static void LowOrHigh (int number, int userGuess )
{
if (userGuess > number )
{
System.out.println("The value that you guessed is too high, "
+"Try guessing a lower number. ");
System.out.println("");
}
else if (userGuess < number )
{
System.out.println("The value that you guessed is too low, "
+"Try guessing a higher number. ");
System.out.println("");
}
}
/*
METHOD 3
This method will get the user guess. It has 2 parameters which will be the
valid range the user should guess between (in this case 1 and 100). It will
return the users guess as an integer. This method should validate that the
users guess is between the two parameters.
*/
public static int GetUserGuess(int rangeLow, int rangeHigh)
{
Scanner scan = new Scanner(System.in);
int userGuess;
System.out.print("Enter a number between " + rangeLow + " and " + rangeHigh + ": ");
userGuess = scan.nextInt();
while (userGuess > rangeHigh || userGuess < rangeLow)
{
System.out.println("The number given was not within the range, Try again ");
System.out.println("");
System.out.print("Enter a number between " + rangeLow + " and " + rangeHigh + ": ");
userGuess = scan.nextInt();
}
return userGuess;
}
}
I'm sorry if its obvious im still pretty new to programming.
Whenever you store a guess, you always store it in guesses[tries], and then immediately afterwards, you increment tries. Your while condition then checks if tries is less than guess.length - 1.
More generally, to program you need to know how to debug. Debugging is generally the act of following along with the code and checking what it actually does vs. what you wanted it to do. You can use a debugger for this, alternatively, you can add a boatload of System.out statements to follow along.
Do that, and you'll find the error in your logic. I've already given you quite a sizable hint in the first paragraph ;)
So I am currently working on a lab for class. I'll attach the lab below:
For this lab, you will use a series of nested if-else or if-else-if statements in order to convert a Roman Numeral number into its String word form. The numerals we are concerned with are I, II, III, IV, V, VI, VII, VIII, which coincide with One, Two, Three, Four, Five, Six, Seven, Eight. Numbers outside of this range are denied – you must tell the user that they are denied as input.
Your code must not fall for inputs like ‘I am the best roman numeral, ‘IIIlikefish’, or ‘VIII is delicious.’ Those inputs should be denied just like an input outside of I to VIII would be
What are possible ways to avoid falling for fake inputs?
Also, I currently have 8 different if statements, is there a faster way to do this?
import java.util.Scanner;
public class RomanNumeralChecker {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String romanNum;
System.out.println("Please enter a Roman Numeral between the values 1 and 8:");
romanNum = keyboard.next();
if (romanNum.equalsIgnoreCase("I")){
System.out.println(romanNum + " represents the number \"One\"");
}
else if (romanNum.equalsIgnoreCase("II")){
System.out.println(romanNum + " represents the number \"Two\"");
}
else if (romanNum.equalsIgnoreCase("III")){
System.out.println(romanNum + " represents the number \"Three\"");
}
else if (romanNum.equalsIgnoreCase("IV")){
System.out.println(romanNum + " represents the number \"Four\"");
}
else if (romanNum.equalsIgnoreCase("V")){
System.out.println(romanNum + " represents the number \"Five\"");
}
else if (romanNum.equalsIgnoreCase("VI")){
System.out.println(romanNum + " represents the number \"Six\"");
}
else if (romanNum.equalsIgnoreCase("VII")){
System.out.println(romanNum + " represents the number \"Seven\"");
}
else if (romanNum.equalsIgnoreCase("VIII")){
System.out.println(romanNum + " represents the number \"Eight\"");
}
else {
System.out.println("Sorry, but " + romanNum + " is out of the desired range.");
}
}
}
Your code is fine for what you need it to do. There are ways to check for valid entry other than what you have implemented but they may be a bit more involved. Professors tend to become upset (Maybe mines was just a jerk) when student do more than what is required for a coding lab.
In the code shown by #nakano531, there's no way that a "trick input" will work. If it what they input, literally does not match the HashMap, it will prompt them that they have entered an invalid answer. ( Don't have the necessary reputation points to say this under his answer, but I wanted to let you know)
Your code is using
romanNum = keyboard.next();
This will return first word from the given input.But you should use .
romanNum = keyboard.nextLine();
Which will read the entire String provided by the use like the ones( ‘I am the best roman numeral, ‘IIIlikefish’, or ‘VIII is delicious.’) you mentioned.
i Hope this will help you.
https://stackoverflow.com/help/someone-answers
public class answer {
public static void main (String[]args) {
Scanner sc = new Scanner(System.in);
String a0 = sc.nextLine();
String[]a1 = {"I","II","III","IV","V","VI","VII","VIII"};
String[]a2 = {"One","Two","Three","Four","Five","Six","Seven","Eight"};
for(int i=0;i<a1.length;i++) {
if(a0.equals(a1[i])) {
System.out.println(a0+" represent "+a2[i]);
}
else {
System.out.println("You Type smth wrong");
}
}
}
}
Okay, this is where we are now. The issue is I can't get the JOption windows to pop up after taking the users input.
public class RomanNumeralChecker {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String romanNum;
JOptionPane.showInputDialog(null,"Please enter a Roman Numeral between the values 1 and 8: ");
romanNum = keyboard.nextLine();
if (romanNum.charAt(0) == 'I') {
if (romanNum.equalsIgnoreCase("I"))
JOptionPane.showMessageDialog(null,romanNum + " represents the number \"One\"");
if (romanNum.equalsIgnoreCase("II"))
JOptionPane.showMessageDialog(null,romanNum + " represents the number \"Two\"");
if (romanNum.equalsIgnoreCase("III"))
JOptionPane.showMessageDialog(null,romanNum + " represents the number \"Three\"");
if (romanNum.equalsIgnoreCase("IV"))
JOptionPane.showMessageDialog(null,romanNum + " represents the number \"Four\"");
}
else if (romanNum.charAt(0) == 'V') {
if (romanNum.equalsIgnoreCase("V"))
JOptionPane.showMessageDialog(null,romanNum + " represents the number \"Five\"");
if (romanNum.equalsIgnoreCase("VI"))
JOptionPane.showMessageDialog(null,romanNum + " represents the number \"Six\"");
if (romanNum.equalsIgnoreCase("VII"))
JOptionPane.showMessageDialog(null,romanNum + " represents the number \"Seven\"");
if (romanNum.equalsIgnoreCase("VIII"))
JOptionPane.showMessageDialog(null,romanNum + " represents the number \"Eight\"");
}
else {
JOptionPane.showMessageDialog(null,"Not in valid range.");
}
}
}
You can reduce the number of if statement by using Map.
import java.util.Scanner;
import java.util.*;
public class RomanNumeralChecker {
public static void main(String[] args) {
Map<String, String> m = new HashMap<String, String>();
m.put("I", "One");
m.put("II", "Two");
m.put("III", "Three");
m.put("IV", "Four");
m.put("V", "Five");
m.put("VI", "Six");
m.put("VII", "Seven");
m.put("VIII", "Eight");
System.out.println("Please enter a Roman Numeral between the values 1 and 8:");
Scanner keyboard = new Scanner(System.in);
String romanNum = keyboard.next();
String num = m.get(romanNum);
if (num != null) {
System.out.println(romanNum + " represents the number \"" + num + "\"");
} else {
System.out.println("Sorry, but " + romanNum + " is out of the desired range.");
}
}
}
Hello my task is to write a program that selects a random number between 1 and 5 and asks the user to guess the number. Then I must display a message that indicates the difference between the random number and the users guess. I then must display another message that displays the random number and the Boolean value true or false depending on whether the user's guess equals the random number. I have got the first part of the assignment done, where the user guesses a number and the computer generates a random number between 1 and 5, but I don't have a clue on how to make it display how close or far off they were or how to use a Boolean to show if the guess was equal to the number or not. I have left code of what I have so far. Thanks for the help and sorry if there is anything wrong with this post.
package randomguessmatch;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class RandomGuessMatch
{
public static void main(String[] args)
{
int random = 1 + (int)(Math.random() * 5);
Scanner input = new Scanner(System.in);
JOptionPane.showInputDialog(null,"Enter a number between 1 and 5: ");
JOptionPane.showMessageDialog(null,"The number is: " + random);
}
}
I need the first message to read something like "You were 3 numbers off." and the second message needs to read something like "You guessed the number 3 correctly" or "You did not guess the number 3 correctly."
Take the absolute value of the entered number subtracted by the random number.
Something like:
package randomguessmatch;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class RandomGuessMatch
{
public static void main(String[] args)
{
int random = 1 + (int)(Math.random() * 5);
Scanner input = new Scanner(System.in);
JOptionPane.showInputDialog(null,"Enter a number between 1 and 5: ");
JOptionPane.showMessageDialog(null, "You were " + Math.abs(random - parseInt(input)) + " away");
JOptionPane.showMessageDialog(null,"The number is: " + random);
}
}
Based on Zachary McGee's answer:
public static void main(String[] args)
{
int random = 1 + (int)(Math.random() * 5);
String input = JOptionPane.showInputDialog(null,"Enter a number between 1 and 5: ");
if(Integer.parseInt(input) == random)
JOptionPane.showMessageDialog(null, "You guessed correctly!");
else
JOptionPane.showMessageDialog(null, "You were " + Math.abs(random - Integer.parseInt(input)) + " away");
JOptionPane.showMessageDialog(null,"The number is: " + random);
}
If you have any questions to the code, feel free to ask :)
I'm trying to write a simple program that will ask for the user to enter a number in-between 1 and 10, then display the number. Now I have gotten part to work where if the number is outside of the range it asks again, but I can't seem to get it to ask again if anything aside from a number is inputted, such as % or hello.
The source code: (Cut out the top)
public static void main(String[] args){
int number; //For holding the number
String stringInput; //For holding the string values until converted
//------------------//
//Introducing the user
JOptionPane.showMessageDialog(null, "This is a program that will ask \n"
+ "you to enter a number in-between \n"
+ "1-10, if the number is not within \n"
+ "the parameters, the program will repeat.");
//---------------------//
//Get input from the user
stringInput = JOptionPane.showInputDialog("Enter number.");
number = Integer.parseInt(stringInput);
//-----------------//
//Checking the number
while (number > 10 || number < 0){
stringInput = JOptionPane.showInputDialog("That number is not within the \n"
+ "allowed range! Enter another number.");
number = Integer.parseInt(stringInput);
}
//-------------------//
//Displaying the number
JOptionPane.showMessageDialog(null, "The number you chose is "
+ number
+ ".");
//-------------//
//Closing it down
System.exit(0);
}
The main problem is the:
number = Integer.parseInt(stringInput);
I can't seem to convert the data values properly. I already thought of something like using an if statement to determine if the number is an integer, but I couldn't figure out how to check. I wish I could do:
if (number == Integer)
As you can see I am still extremely new to Java, any help is appreciated, thanks for taking the time to read.
You need to surround the call to Integer.parseInt() with a try/catch block to detect invalid input, like:
try {
number = Integer.parseInt(stringInput);
} catch (NumberFormatException e) {
// Not a number, display error message...
}
Here is a solution:
String errorMessage = "";
do {
// Show input dialog with current error message, if any
String stringInput = JOptionPane.showInputDialog(errorMessage + "Enter number.");
try {
int number = Integer.parseInt(stringInput);
if (number > 10 || number < 0) {
errorMessage = "That number is not within the \n" + "allowed range!\n";
} else {
JOptionPane
.showMessageDialog(null, "The number you chose is " + number + ".");
errorMessage = ""; // no more error
}
} catch (NumberFormatException e) {
// The typed text was not an integer
errorMessage = "The text you typed is not a number.\n";
}
} while (!errorMessage.isEmpty());
I'm trying to write a simple program that will ask for the user to
enter a number in-between 1 and 10
please to read Oracle tutorial How to use Dialogs - JOptionPane Features, then code should be very short and simple, without parsing an Integer from String
.
import java.awt.EventQueue;
import javax.swing.Icon;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
public class MyOptionPane {
public MyOptionPane() {
Icon errorIcon = UIManager.getIcon("OptionPane.errorIcon");
Object[] possibilities = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Integer i = (Integer) JOptionPane.showOptionDialog(null,
null, "ShowInputDialog",
JOptionPane.PLAIN_MESSAGE, 1, errorIcon, possibilities, 0);
// or
Integer ii = (Integer) JOptionPane.showInputDialog(null,
"Select number:\n\from JComboBox", "ShowInputDialog",
JOptionPane.PLAIN_MESSAGE, errorIcon, possibilities, "Numbers");
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
MyOptionPane mOP = new MyOptionPane();
}
});
}
}