Why can't I get Integer input on java? - java

This is my equation generator and the output of the code is always 'incorrect'. I think it's because I can't get the integer input from the user. All I want is to fix this code. If anyone has any idea, please tell me.
THE CODE:
package equasionGen;
import java.util.Random;
import java.util.*;
public class EquationGen {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("This will Generate you an Equasion with numbers ranging between 1-1000");
Random random = new Random();
for(int idx = 1; idx <= 1; ++idx);
int randomInt = random.nextInt(10);
Random random1 = new Random();
for(int idx = 1; idx <= 1; ++idx);
int randomInt1 = random.nextInt(10);
System.out.print(randomInt + " + " + randomInt1 + " = ");
Scanner josh = new Scanner(System.in);
int input = josh.nextInt();
if (josh.equals(randomInt + randomInt1)){
System.out.println("CORRECT!!!");
} else if (!josh.equals (randomInt + randomInt1)){
System.out.println("INCORRECT!!");
}
}
}

The .equals() method is used to compare Strings. For comparing Integers, you should use the "==" comparison operator instead. Also, you are trying to compare the Scanner object "josh" to an Integer of (randomInt + randomInt1). Instead compare the Integer input, which you named "input" to (randomInt + randomInt1).
It should be:
if (input == (randomInt + randomInt1)) { ... }
else { ... }
If you want to compare two Integers to see if they are not the same, you can use the "!=" operator instead of the "=="

Related

how to show the negative number factorial in this code

im trying to make a calculator and im was unable to continue because of some confusion in my codes. i was trying to make a factorial of a number, if its a positive number there is no error but every time i input a negative number it results to 1, here is my code .
import java.math.BigInteger;
import java.util.Scanner;
public class Factorial2 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = s.nextInt();
String fact = factorial(n);
System.out.println("Factorial is " + fact);
}
public static String factorial(int n) {
BigInteger fact = new BigInteger("1");
for (int i = 1; i <= n; i++) {
fact = fact.multiply(new BigInteger(i + ""));
}
return fact.toString();
}
}
i already tried making if statements but still it results to 1.i also want to make the negative factorial into a display text not the value of the negative factorial
You need to validate the input before the calculation, example:
public static String factorial(int n) {
if(n < 1) return "0";
BigInteger fact = new BigInteger("1");
for (int i = 1; i <= n; i++) {
fact = fact.multiply(new BigInteger(i + ""));
}
return fact.toString();
}
Of course you can define any default return value or throw an error:
if(n < 1) throw new RuntimeException("Input must be > 0");

Why does this loop not run properly

I am suppose to write a java program where I ask user how many math questions they want to answer and generate random questions based on their answer using any loop of choice and keep a count of how many they answered correct. I got it to generate the random math problem, but it only does it once it seems to be skipping the loop. Can anyone help?
import javax.swing.JOptionPane;
import java.util.Random;
import java.util.Scanner;
/**
*
* #author user
*/
public class MathQuiz {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Random obj = new Random();
int num1 = obj.nextInt(10);
int num2 = obj.nextInt(10);
int rand = num1 + num2;
String response = JOptionPane.showInputDialog(null,"How many problems would you like to solve?");
int ans = Integer.parseInt(response); // answer from question
String result= null;
int times = input.nextInt();
int counter = 0; //counts total math problems
while (counter != ans){
counter++;
JOptionPane.showInputDialog(num1 + "+" +num2);
if (ans == rand){
result= "Correct";
}else {
result= "Incorrect";
}
} JOptionPane.showMessageDialog(null, );
}
}
Here are the problems in your code:
You are not displaying the result after you compute the value.
Not generating the random numbers every time.
public class MathQuiz {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String response = JOptionPane.showInputDialog(null,"How many problems would you like to solve?");
int noOfTimes = Integer.parseInt(response); // answer from question
String result= null;
for (int counter = 0; counter < noOfTimes; counter++) {
Random obj = new Random();
int num1 = obj.nextInt(10);
int num2 = obj.nextInt(10);
int rand = num1 + num2;
int answer = Integer.parseInt(JOptionPane.showInputDialog(num1 + "+" +num2));
if (answer == rand){
result= "Correct";
}else {
result= "Incorrect";
}
JOptionPane.showMessageDialog(null, result);
}
}
}
The number you get inside of the loop should not be stored in the same variable as the one you use in your while(...) condition. In this case, you used ans. In the example below I have separate variables for the math answer and the number of times to iterate in the loop. Another problem you had is that you were not passing the result message to the showMessageDialog(..) method.
import javax.swing.JOptionPane;
import java.util.Random;
import java.util.Scanner;
public class MathQuiz {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Random obj = new Random();
String timesString = JOptionPane.showInputDialog(null,"How many problems would you like to solve?");
int timesInt = Integer.parseInt(timesString); // answer from question
int counter = 0; //counts total math problems
while (counter != timesInt) {
counter++;
int num1 = obj.nextInt(10);
int num2 = obj.nextInt(10);
int rand = num1 + num2;
String answerString = JOptionPane.showInputDialog(num1 + "+" +num2);
int answerInt = Integer.parseInt(answerString);
JOptionPane.showMessageDialog(null, answerInt == rand ? "Correct" : "Incorrect");
}
}
}

Java lottery simulation using Sets, not generating the correct number of random results or comparing Sets correctly

I have been programming a lottery simulation, with some help from questions I've been looking at on this site. I can't seem to get the program to display the correct number of results that I am requiring, and the two sets are not comparing correctly to say how many numbers have matched.
import java.util.Set;
import java.util.HashSet;
import java.util.Random;
import java.util.Scanner;
public class Lotto {
private static final int INPUT_SIZE = 6;
private static final int MIN_NUMBER_POSSIBLE = 1;
private static final int MAX_NUMBER_POSSIBLE = 10;
private Set<Integer> userNumbers = new HashSet<Integer>();
private Set<Integer> randomNumbers = new HashSet<Integer>();
public static void main(String[] args) {
Lotto c = new Lotto();
c.generateRandomNumbers();
System.out.println("Please choose " + INPUT_SIZE + " numbers from " + MIN_NUMBER_POSSIBLE + " to " + MAX_NUMBER_POSSIBLE + ", hit enter after each number.");
c.readUserNumbers();
if (c.doUserNumbersMatchRandomNumbers()) {
System.out.println("Congratulations, you have won!");
} else {
System.out.println("Not a winner, better luck next time.");
c.showRandomNumbersToUser();
}
}
private void generateRandomNumbers() {
Random random = new Random();
for (int i = 0; i < INPUT_SIZE; i++) {
randomNumbers.add(random.nextInt(MAX_NUMBER_POSSIBLE));
}
}
private void showRandomNumbersToUser() {
System.out.println("\nLotto numbers were : ");
for (Integer randomNumber : randomNumbers) {
System.out.println(randomNumber + "\t");
}
}
private void readUserNumbers() {
Scanner input = new Scanner(System.in);
int inputSize = 1;
while (input.hasNextInt() && inputSize < INPUT_SIZE) {
int numberChosen = input.nextInt();
if (numberChosen < MIN_NUMBER_POSSIBLE || numberChosen > MAX_NUMBER_POSSIBLE) {
System.out.println("Your number must be in " + MIN_NUMBER_POSSIBLE + " - " + MAX_NUMBER_POSSIBLE + " range.");
} else {
userNumbers.add(numberChosen);
inputSize++;
}
}
}
private boolean doUserNumbersMatchRandomNumbers() {
for (Integer userNumber : userNumbers) {
for (Integer randomNumber : randomNumbers) {
if (!randomNumbers.contains(userNumber)) {
return false;
}
}
printMatchingNumber(userNumber);
}
return true;
}
private void printMatchingNumber(int num) {
System.out.println("Your number, " + num + ", has been drawn.");
}
}
There 2 problems in your code:
1) In generateRandomNumbers you should take into account that the same random number could occur multiple times. So make sure that randomNumbers is really of INPUT_SIZE size in the end.
2) In doUserNumbersMatchRandomNumbers you iterate over randomNumbers but never use randomNumber.
You store your random numbers in a (Hash-)Set, One feature of Set as described in the API is that they do not contain duplicate values (by comparing them with their equals() method). Since the Random class may output the the same value multiple times you have less values in your Set.
The better approach for generating the random numbers would be to go with a while loop:
while (random.size() < INPUT_SIZE)
{
randomNumbers.add(random.nextInt(MAX_NUMBER_POSSIBLE));
}
keep in mind that this could result in an endless loop. Although it is very unlikely though. At least this loop does have varying execution times.

Java random number with length, restrictions, characters and letters

Hi I'm new to Java and I'm trying to generate a random number 11-digit random number. How do you do this in this format "[xxx]-xxx#AxAxx" where the x is digits 0-9 and the A is any upper case letter. The brackets, dashes, and hash must be in the correct position too. Also the restriction is the last two digits can't be 5 or 6 and the first digit can't be 0. What's the best way to do this? Do you have to use a string and a random class? Thanks.
FWIW, you can do this with no looping for bad value rejection or hacks to add leading zeros:
import static java.lang.String.format;
import java.util.Random;
class Generator {
Random random = new Random();
private int not5or6() {
int val = random.nextInt(8);
return val < 5 ? val : val + 2;
}
String randomKey() {
StringBuilder s = new StringBuilder();
s.append('[');
s.append(random.nextInt(900) + 100);
s.append("]-");
s.append(format("%03d", random.nextInt(1000)));
s.append('#');
s.append((char) ('A' + random.nextInt(26)));
s.append(random.nextInt(10));
s.append((char) ('A' + random.nextInt(26)));
s.append(not5or6());
s.append(not5or6());
return s.toString();
}
// Or if you you don't like StringBuilder, here's another way...
String randomKey2() {
return format("[%d]-%03d#%c%d%c%d%d",
random.nextInt(900) + 100,
random.nextInt(1000),
(char) ('A' + random.nextInt(26)),
random.nextInt(10),
(char) ('A' + random.nextInt(26)),
not5or6(),
not5or6());
}
public static void main(String[] args) {
Generator g = new Generator();
for (int i = 0; i < 100; i++) System.out.println(g.randomKey());
}
}
Not sure if there is an "easy" way to do this.
You can just call "nextInt()" on a random number generator for each part you want to generate and then put all the pieces together, for example...
import java.util.Random;
public class Rnd {
private static Random rnd = new Random();
public static void main(String[] args) {
for(int k = 0; k < 1000; k++) {
System.out.println(Rnd.generate());
}
}
private static String generate() {
// Generate all of the random parts of the desired pattern...
// First part, 000-999
String num1 = generateNumbers(1000);
// Second part, 000-999
String num2 = generateNumbers(1000);
// Third part A...Z
char char1 = generateChar();
// Forth part, 0-9
String num3 = generateNumbers(10);
// Fifth part A...Z
char char2 = generateChar();
// Sixth part, 00-99
String num4 = "56";
// Make sure last two numbers are not a 5 or 6
while(num4.contains("5") || num4.contains("6")) {
num4 = generateNumbers(100);
}
return "[" + num1 + "]-" + num2 + "#" + char1 + num3 + char2 + num4;
}
private static char generateChar() {
// Generate a number between 0 and 25 inclusive then add 'A' to it
return (char) (rnd.nextInt(26) + 'A');
}
private static String generateNumbers(int i) {
// Generates a random int between 0 (inclusive) and i (exclusive)
// (where i should be a power of 10 that is > 1)
// Add i to the generated random number, turn it into a string and then strip first character
// This will ensure a number like 3 will come out as 003 for i = 1000
return ("" + (rnd.nextInt(i) + i)).substring(1);
}
}
This outputs something like...
[745]-770#M6U88
[481]-779#N0N82
[182]-777#S2P08
[401]-219#H6O78
[032]-181#O8E82
[579]-949#I0S02
[025]-810#K2P39
[523]-663#L0I89
[560]-084#N5W01
[915]-767#F2A97
[059]-324#R0D79
etc.

From main method to subroutine

I wrote my code and it works completely, but I didn't write my own methods. The point of the assignment is to practice using subroutines and that's what I have to use. I read about making my own methods--A LOT. But I still can't wrap my mind around it.
Here's a piece of my code. Can you help me by explaining how I'd make my own method with it and call it?
public static void main(String[] args) {
//Display welcome message
System.out.println("Welcome to the Math Functions event!");
Scanner keyIn = new Scanner(System.in);
Scanner userInput;
System.out.print("Press the ENTER key to toss the dice.");
keyIn.nextLine();
//roll dice
Random rand = new Random();
int tries = 0;
int sum = 0;
while (sum != 7 && sum != 11) {
// roll the dice once
int roll1 = rand.nextInt(6) + 1;
int roll2 = rand.nextInt(6) + 1;
sum = roll1 + roll2;
System.out.println(roll1 + " + " + roll2 + " = " + sum);
tries++;
}
}
Any help would be greatly appreciated! Thank you!
Here is an example of a method giving you a random dice roll:
public static int rollDice()
{
Random rand = new Random();
int roll = rand.nextInt(6) + 1;
return roll;
}
You would call the function like this:
int roll = rollDice();
So it could be integrated in your program like this for example:
public static void main(String[] args) {
//Display welcome message
System.out.println("Welcome to the Math Functions event!");
Scanner keyIn = new Scanner(System.in);
Scanner userInput;
System.out.print("Press the ENTER key to toss the dice.");
keyIn.nextLine();
int tries = 0;
int sum = 0;
while (sum != 7 && sum != 11) {
// Here is where you call your newly created method
int roll1 = rollDice();
int roll2 = rollDice();
sum = roll1 + roll2;
System.out.println(roll1 + " + " + roll2 + " = " + sum);
tries++;
}
}
The idea is that you want to split up a complicated task into many smaller ones. This way it makes it much easier to debug. The above is just an example, but if you are performing an operation that you realise is repetitive, a function can never hurt.
Try to think about your function in the following way:
1. What does my function do?
2. What data should it provide me with?
3. What is the minimum my function requires to provide me with this data?
As for a function that counts the characters for a string as mentioned in the comments:
Your function counts the characters in a string.
The data that it provides you with is simply a number.
All you need to get this number is a string.
Given this information, we can come up with the following function protocol:
public static int countCharacters(String myString)
{
int count = myString.length();
return count;
}
The return type and value is an int as this is what it needs to provide you with, and myString is the only data the function needs to work. Thinking this way makes code much more maintainable, and you will be able to break up a complicated task into several very simple steps.

Categories

Resources