I am have a program which prints off the fibonacci sequence up to a given input. The user puts in a number and it prints out the sequence up to that many numbers.
ex: input = 4 prints 1 1 2 3
I want to limit the program to only allowing an input 1-16. The way I have it now will print the sequence an then prints the error message? Any suggestions? Thank you
public class FibonacciGenerator
{
private int fibonacci = 1;
public FibonacciGenerator()
{
}
public int Fibonacci(int number)
{
if(number == 1 || number == 2)
{
return 1;
}
else if (number > 16)
{
System.out.println("Error must select 1-16");
}
else
{
int fib1=1, fib2=1;
for(int count= 3; count < 17 && count <= number; count++)
{
fibonacci = fib1 + fib2;
fib1 = fib2;
fib2 = fibonacci;
}
}
return fibonacci;
}
}
Here is my main method:
import java.util.Scanner;
public class FibonacciPrinter
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter an integer 1-16: ");
int input = in.nextInt();
FibonacciGenerator newNumber = new FibonacciGenerator();
System.out.println("Fibonacci sequence up to " + input + " places.");
for(int fibCount = 1; fibCount <= input; fibCount++)
{
int sequence = newNumber.Fibonacci(fibCount);
System.out.print(sequence);
}
}
}
As a recommendation don't make your methods or variables start with capital letter, capital letter is used by convention for Classes only.
Also, you should validate input variable before passing it to your method.
I mean:
if (input > 16 || input < 1) {
System.out.println("Enter a number between 1-16");
}
else {
for(int fibCount = 1; fibCount <= input; fibCount++)
{
int sequence = newNumber.Fibonacci(fibCount);
System.out.print(sequence);
}
}
In your Fibonacci function, your first line should be an if statement to see if the number is greater than 16. If it is, then you can throw an error.
Below is what it should be:
public int Fibonacci(int number) {
if (number > 16 || number < 1) throw new IllegalArgumentException("Error. Must select 1-16.");
// Rest of the code
}
In your Fibonacci function, for number not equal to 1 and 2. The return statement return fibonacci; will always be called. That's why the error message is printed with the sequence.
To avoid this, you can use #Frakcool method to validate variable input before passing it to Fibonacci function. Alternatively, you may use do-while loop to do this (force the user to retry).
do{
System.out.print("Enter an integer 1-16: ");
input = in.nextInt();
if (input<1 || input>16)
System.out.println("Error. Must select within 1-16.");
}while(input<1 || input>FibonacciGenerator.upper_limit);
Some other suggestion:
Make your methods and variables name start with a lower case letter
To avoid repeat calculation (for-loop in Fibonacci method), use integer array to store the fibonacci values and pass integer array instead of integer (for small input number such as 16). Another way is to set two more global variables to store the last and second last calculated values.
Make upper limit (and/or lower limit) as a global variable for better maintenance
public static int upper_limit = 16;
and get it in other class as
FibonacciGenerator.upper_limit
Related
I'm trying to learn java, and I can't seem to understand recursion. I can understand how recursion can be used to add and do other basic math operations but how can recursion be used to reverse manipulate integers and individual integer digits.
example:
a method takes a single positive integer argument and displays its base five equivalent. 231 returns 1411 but the code below returns 1141. how would I reverse the order of integers put out?
public void base5(int n){
int rem=n%5;
int vis=n/5;
if(n!=0){
// System.out.print(rem/*+"|"*/);
//
// rem=(rem+rem)*10;
// System.out.print("\n||"+n+"||\n");
System.out.print(rem);
base5(vis);
}
else{
return;
}
}
The algorithm for getting individual digits of an integer, from right to left, is well known. See How to get the separate digits of an int number?.
I won't "explain" recursion, but I'll give you one possible solution for first problem:
a method takes a single positive integer and displays it with commas
inserted every three digits
import java.util.Scanner;
class Main {
public static void main( String [] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your positive integer: ");
long number = sc.nextLong();
String result = addCommas(number);
System.out.println(result);
}
public static String addCommas(long num) {
return addCommas(num, 1);
}
public static String addCommas(long num, int counter) {
if (num == 0) {
return ""; // base case ends recursion
}
else {
long digit = num % 10;
num = num / 10;
String comma = (counter%3==0 && num>0) ? "," : "";
// recursive call below because we call addCommas() again
return addCommas(num, counter+1) + comma + digit;
}
}
}
Here's a compact solution to the second problem:
a method takes a single positive integer and displays the result of
reversing its digits
public static String reverseDigits(long num) {
if (num == 0) {
return "";
}
else {
return String.valueOf(num % 10) + reverseDigits(num / 10);
}
}
I am trying to work out how to create an input validation where it won't let you enter the same number twice as well as being inside a range of numbers and that nothing can be entered unless it's an integer. I am currently creating a lottery program and I am unsure how to do this. Any help would be much appreciated. My number range validation works but the other two validations do not. I attempted the non duplicate number validation and i'm unsure how to do the numbers only validation. Can someone show me how to structure this please.
This method is in my Player class
public void choose() {
int temp = 0;
for (int i = 0; i<6; i++) {
System.out.println("Enter enter a number between 1 & 59");
temp = keyboard.nextInt();
keyboard.nextLine();
while ((temp<1) || (temp>59)) {
System.out.println("You entered an invalid number, please enter a number between 1 and 59");
temp = keyboard.nextInt();
keyboard.nextLine();
}
if (i > 0) {
while(temp == numbers[i-1]) {
System.out.println("Please enter a different number as you have already entered this");
temp = keyboard.nextInt();
keyboard.nextLine();
}
}
numbers[i] = temp;
}
}
Do it as follows:
import java.util.Arrays;
import java.util.Scanner;
public class Main {
static int[] numbers = new int[6];
static Scanner keyboard = new Scanner(System.in);
public static void main(String args[]) {
// Test
choose();
System.out.println(Arrays.toString(numbers));
}
static void choose() {
int temp;
boolean valid;
for (int i = 0; i < 6; i++) {
// Check if the integer is in the range of 1 to 59
do {
valid = true;
System.out.print("Enter in an integer (from 1 to 59): ");
temp = keyboard.nextInt();
if (temp < 1 || temp > 59) {
System.out.println("Error: Invalid integer.");
valid = false;
}
for (int j = 0; j < i; j++) {
if (numbers[j] == temp) {
System.out.println("Please enter a different number as you have already entered this");
valid = false;
break;
}
}
numbers[i] = temp;
} while (!valid); // Loop back if the integer is not in the range of 1 to 100
}
}
}
A sample run:
Enter in an integer (from 1 to 59): 100
Error: Invalid integer.
Enter in an integer (from 1 to 59): -1
Error: Invalid integer.
Enter in an integer (from 1 to 59): 20
Enter in an integer (from 1 to 59): 0
Error: Invalid integer.
Enter in an integer (from 1 to 59): 4
Enter in an integer (from 1 to 59): 5
Enter in an integer (from 1 to 59): 20
Please enter a different number as you have already entered this
Enter in an integer (from 1 to 59): 25
Enter in an integer (from 1 to 59): 6
Enter in an integer (from 1 to 59): 23
[20, 4, 5, 25, 6, 23]
For testing a value is present in the numbers array use Arrays.asList(numbers).contains(temp)
May better if you use an ArrayList for storing numbers.
I would rewrite the method recursively to avoid multiple loops.
If you are not familiar with recursively methods it is basically a method that calls itself inside the method. By using clever parameters you can use a recursively method as a loop. For example
void loop(int index) {
if(index == 10) {
return; //End loop
}
System.out.println(index);
loop(index++);
}
by calling loop(1) the numbers 1 to 9 will be printed.
In your case the recursively method could look something like
public void choose(int nbrOfchoices, List<Integer> taken) {
if(nbrOfChoices < 0) {
return; //Terminate the recursively loop
}
System.out.println("Enter enter a number between 1 and 59");
try {
int temp = keyboard.nextInt(); //Scanner.nextInt throws InputMismatchException if the next token does not matches the Integer regular expression
} catch(InputMismatchException e) {
System.out.println("You need to enter an integer");
choose(nbrOfChoices, taken);
return;
}
if (value < 1 || value >= 59) { //Number not in interval
System.out.println("The number " + temp + " is not between 1 and 59.");
choose(nbrOfChoices, taken);
return;
}
if (taken.contains(temp)) { //Number already taken
System.out.println("The number " + temp + " has already been entered.");
choose(nbrOfChoices, taken);
return;
}
taken.add(temp);
choose(nbrOfChoices--, taken);
}
Now you start the recursively method by calling choose(yourNumberOfchoices, yourArrayList taken). You can also easily add two additonal parameters if you want to be able to change your number interval.
What you want to do is use recursion so you can ask them to provide input again. You can define choices instead of 6. You can define maxExclusive instead 59 (60 in this case). You can keep track of chosen as a Set of Integer values since Sets can only contain unique non-null values. At the end of each choose call we call choose again with 1 less choice remaining instead of a for loop. At the start of each method call, we check if choices is < 0, if so, we prevent execution.
public void choose(Scanner keyboard, int choices, int maxExclusive, Set<Integer> chosen) {
if (choices <= 0) {
return;
}
System.out.println("Enter enter a number between 1 & " + (maxExclusive - 1));
int value = keyboard.nextInt();
keyboard.nextLine();
if (value < 1 || value >= maxExclusive) {
System.out.println("You entered an invalid number.");
choose(keyboard, choices, maxExclusive, chosen);
return;
}
if (chosen.contains(value)) {
System.out.println("You already entered this number.");
choose(keyboard, choices, maxExclusive, chosen);
return;
}
chosen.add(value);
choose(keyboard, --choices, maxExclusive, chosen);
}
choose(new Scanner(System.in), 6, 60, new HashSet<>());
I hope it will help , upvote if yes
import java.util.ArrayList;
import java.util.Scanner;
public class Test {
private ArrayList<String> choose() {
Scanner scanner = new Scanner(System.in);
ArrayList<String> alreadyEntered = new ArrayList<>(6); // using six because your loop indicated me that you're taking six digits
for(int i = 0 ; i < 6 ; ++i){ // ++i is more efficient than i++
System.out.println("Enter a number between 1 & 59");
String digit;
digit = scanner.nextLine().trim();
if(digit.matches("[1-5][0-9]|[0-9]" && !alreadyEntered.contains(digit))// it checks if it is a number as well as if it is in range as well if it is not already entered, to understand this learn about regular expressions
alreadyEntered.add(digit);
else {
System.out.println("Invalid input, try again");
--i;
}
}
return alreadyEntered // return or do whatever with the numbers as i am using return type in method definition i am returning
}
scanner.close();
}
using arraylist of string just to make things easy otherwise i would have to to some parsing from integer to string and string to integer
The point of this program is to take a three digit number from the command line and then reversing it. After that it is supposed to subtract the reverse from the original number and add the original to the reversed.
This is supposed to only take numbers that are three digits and the first digit of the number has to be greater than the last so that it is not negative when the numbers are subtracted.
The code compiles correctly but when I put a number in the command line prints out the line "Enter a three digit number, with the first digit larger than the third" only.
What it is supposed to print out like
$ java Rev 351
Reverse and subtract:
351
153 -
---
198
Reverse and add:
198
891 +
---
1089
This is my code:
public class Rev
{
public static void main(String[] args)
{
int num = 0;
for (int i = 0; i < args.length; i++)
{
System.out.println("Enter a three digit number, with the first digit larger than the third");
num = Integer.parseInt(args[i]);
reverseNum(num);
subtractNum(num);
addNum(num);
}
}
static boolean checkDigits(int number) // checks if numbers are correct
{
int reverse = reverseNum(number);
if(number > reverse)
{
throw new Error("Reverse number needs to be less than the original number!");
}
else
{
return true;
}
}
static int reverseNum(int number) //reverses number
{
int reverse = 0;
int r = 0;
while (number != 0)
{
if(number < 1000 || number > 99)
{
r = number % 10;
reverse = (reverse*10) + r;
number = number/10;
}
}
return reverse;
}
static void subtractNum(int number) // subtracts
{
int reverse = reverseNum(number);
int total = number - reverse;
System.out.println("Reverse and subtract: ");
System.out.println(number);
System.out.println(reverse + " - ");
System.out.println("---");
System.out.println(total);
System.out.println();
number = total;
}
static void addNum(int number) // adds
{
int reverse = reverseNum(number);
int total = number + reverse;
System.out.println("Reverse and add: ");
System.out.println(number);
System.out.println(reverse + " + ");
System.out.println("---");
System.out.println(total);
number = total;
}
}
public static void main(String[] args)
{
int num = 0;
for (int i = 0; i < args.length; i++)
{
System.out.println("Enter a three digit number, with the first digit larger than the third");
num = Integer.parseInt(args[i]);
reverseNum(num);
subtractNum(num);
addNum(num);
}
}
So the args variable is the command line argument. So if you're compiling via command line, you would call something like java Rev.class 321 where 321 is your 3 digit number. If you want to use the Java console to take inputs, use a Scanner.
To take inputs, use something like this:
Scanner sc = new Scanner(System.in);
num = sc.nextInt();
You're never actually getting a number from the input. You need to do this in your main():
public static void main(String[] args)
{
int num = 0;
for (int i = 0; i < args.length; i++)
{
System.out.println("Enter a three digit number, with the first digit larger than the third");
try (Scanner s = new Scanner(System.in)){
num = s.nextInt();
}
reverseNum(num);
subtractNum(num);
addNum(num);
}
}
The Scanner reads the main input stream (from the keyboard). Otherwise, when you pass in the argument on the command line, it hasn't yet asked you for the input, and prints out the request for input.
Your other problem is that you don't call checkDigits() after getting your number, so you should probably do a while loop using it until you get a number you'll accept, like this:
public static void main(String[] args)
{
int num = -1;
while (num < 0 || !checkDigits(num)){
System.out.println("Enter a three digit number, with the first digit larger than the third");
try (Scanner s = new Scanner(System.in)){
num = s.nextInt();
}
}
reverseNum(num);
subtractNum(num);
addNum(num);
}
Also, your other methods are incorrect in that they are acting on an input parameter (which is possible for objects but not primitives, and is bad practice in any case).
Instead write them as functions which take in values and return them, then modify your main again to look like this:
public static void main(String[] args)
{
int num = Integer.parseInt(args[0]);
if (checkDigits(num)){
num = subtractNum(num);
addNum(num);
} else {
System.out.println("Enter only a three digit number, with the first digit larger than the third");
}
}
I am in the process of creating of a Lottery Program using Java via BlueJ and I am having trouble with the user inputted numbers and the number being generated by the program (up to and including 1-49), I need the numbers that are entered by the user to not be duplicate i.e. the user cannot enter 1 and 1.
I am not really sure how to get the numbers to not be duplicate i was thinking of using an Array but im not sure what type or where to begin im rather new to the whole programming thing.
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class JavaApplication8 {
public static void main(String[] args) {
Scanner user_input = new Scanner (System.in);
Scanner keyIn = new Scanner(System.in);
int[] LotteryNumbers = new int[6];
int input;
int count = 0;
System.out.print("Welcome to my lottery program which takes\nyour lottery numbers and compares\nthem to this weeks lottery numbers!");
System.out.print("\n\nPress the enter key to continue");
keyIn.nextLine();
for (int i = 0; i < LotteryNumbers.length; i++)
{
count ++;
System.out.println("Enter your five Lottery Numbers now " + count + " (must be between 1 and 49): ");
input = Integer.parseInt(user_input.next());
if (input < 1 || input > 49)
{
while (input < 1 || input > 49)
{
System.out.println("Invalid number entered! \nPlease enter lottery number (between 1 and 49) " + count);
input = Integer.parseInt(user_input.next());
if (input >= 1 || input <= 49)
{
LotteryNumbers[i] = input;
}
}
}
else
{
LotteryNumbers[i] = input;
}
}
System.out.println("Thank you for your numbers.\nThe system will now check if you have any matching numbers");
System.out.print("Press the enter key to continue");
keyIn.nextLine();
Random randNumGenerator = new Random();
StringBuilder output = new StringBuilder();
int[] ActLotteryNumbers = new int[6];
for (int j = 0; j < ActLotteryNumbers.length; j++)
{
int roll = randNumGenerator.nextInt(49);
ActLotteryNumbers[j] = roll;
}
System.out.println(Arrays.toString(ActLotteryNumbers));
int counter = 0;
for (int i = 0; i < LotteryNumbers.length; i++)
{
for (int j = 0; j < ActLotteryNumbers.length; j++)
{
if (LotteryNumbers[i] == ActLotteryNumbers [j])
{
counter ++;
System.out.println("The numbers that match up are: \n" + LotteryNumbers[i]);
}
}
}
if (counter == 0)
{
System.out.println("You had no matching numbers this week ... Try Again next week!");
}
}
}
As "fge" mentioned, use Set to add all the values that you are getting from the user.
Get the user inputs and add it to Set.
Use a Iterator to check the user entered values and generated random numbers.
Set myset = new HashSet();
myset.add(user_input1);
myset.add(user_input1);
To retrive use the iterator'
Iterator iterator = myset.iterator();
while(iterator.hasNext(){
int value= iterator.next();
if(randomValue==value)
//do your logic here
}
I am assuming this is for a school project/lab? (This is due to the JavaApplication8 class name) If that is the case, what the instructor is most likely looking for is a contains method.
For a contains method you write a method that takes an integer and checks to see if it is already in your LotteryNumbers array and returns a boolean. It would return true if it is in the array, false if it is not in it. This method would be called before inserting the number into LotteryNumbers. You could use your count variable that doesn't appear to be used anywhere else as the limit on your loop in the contains method to avoid checking uninitialized entries.
If there is no restriction on type, the set idea suggested by others works and is more efficient, it just depends on what you are supposed to be using for your requirements.
Additionally, the logic you use should most likely be applied to ActLotteryNumbers as well. If you can't have duplicates incoming, you shouldn't have duplicate values in the comparing array. Lottery isn't fair in real life, but not that unfair ;-)
First step should be checking your restrictions on this project.
The program is designed for the user to enter a series of numbers until the user enters the sentinel which i set to the value of 0. After the user enters the sentinel the program is supposed to print the highest number and the second highest number in that list. The trouble I'm having is where I expect the second highest number to be it prints 0 instead.
Is there a more elegant way of solving this problem by using the ?: operator? Is it possible?
import acm.program.*;
public class LargestAndSecondLargest extends ConsoleProgram {
public void run() {
int a = 0;
int b = 0;
while (true) {
int value = readInt(" ?: ");
if (value == SENTINEL) break;
if (value > a) {
a = value;
}
else if (value > b) {
b = value;
}
}
println("the largest value is " + a);
println("the second largest number is" + b);
}
private static final int SENTINEL = 0;
}
There are two issues:
The second comparison is wrong.
When you encounter a new highest number, you need to shift the previous highest number into the second-highest slot. Otherwise the sequence 1, 2, 3 would produce 3 and 1 as the two highest numbers.
else if ( b > value )
The above else if condition should be: -
else if ( value > b )
Else, your b will never get changed, if you are entering only positive numbers, and hence the 2nd largest value will be 0.
Also see 2nd requirement in #NPE's answer that is necessarily required.
insert the values into an array. Sort the array then assign the top two values from the array into your output. if only one value is given depending on requirements set them both to the same value or one to 0.
Here my solution (that you can adapt with your superclass):
public class LargeAndSecondLargest {
public static void main(String[] args) {
new LargeAndSecondLargest().run("1 2 2");
}
public void run(String input) {
final int SENTINEL = 0;
int currVal;
Scanner scanner = new Scanner(input);
List<Integer> numbers = new ArrayList<>();
while (scanner.hasNextInt() && ((currVal = scanner.nextInt()) != SENTINEL)) {
numbers.add(currVal);
}
printFirstAndSecondLargest(numbers);
}
private void printFirstAndSecondLargest(List<Integer> numbers) {
Collections.sort(numbers, Collections.reverseOrder());
System.out.println("the largest value is " + numbers.get(0));
System.out.println("the second largest number is " + numbers.get(1));
}
}