public static void main(String[] args) {
one();
System.out.println();
}
public static void one() {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number:");
int i = sc.nextInt();
for (int j=0; j<i; j++) {
System.out.println(fibonacci(j));
}
}
public static int fibonacci(int num){
if (num == 1) {
return 0;
}
else if (num == 2 || num == 3){
return 1;
}
else {
return fibonacci(num-1) + fibonacci(num-2);
}
}
When I run this will get Exception in thread "main" java.lang.StackOverflowError but if I change one() to
public static void one() {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number:");
int i = sc.nextInt();
System.out.println(fibonacci(j));
}
I wont get error, even I just enter 1, could I ask why?
You don't handle the case of num == 0, so when you call fibonacci(0) the recursion never ends, leading to StackOverflowError when the stack is full.
You can solve it by changing the range of your loop
for (int j=1; j<i; j++) {
System.out.println(fibonacci(j));
}
or by changing the stopping condition of your recursive method:
public static int fibonacci(int num) {
if (num <= 1) {
return 0;
}
else if (num == 2 || num == 3){
return 1;
}
else {
return fibonacci(num-1) + fibonacci(num-2);
}
}
That said, it would be much more efficient to store the intermediate results of fibonacci(i), and re-use them when calculating fibonacci(n) for n > i (instead of making unnecessary expansive recursive calls).
In the for-Statement you start with 0. This is the first Input to fibonacci-Funktion. Try:
public static void one() {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number:");
int i = sc.nextInt();
for (int j=1; j<i; j++) {
System.out.println(fibonacci(j));
}
I think you missed to handle the zero. Just try the following loop,
for (int j=1; j<=i; j++) {
System.out.println(fibonacci(j));
}
Related
i have a problem with a little java program.
I have to type a number between 1 and 10. This number represents the number of lines. For example: If you type 4, the following image is displayed.
o
oo
ooo
oooo
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
int number, count;
System.out.println("Write the number from 1 to 10");
Scanner teklatua = new Scanner(System.in);
String datu = teklatua.nextLine();
number = Integer.parseInt(datu);
if(number> 10 || number< 1)
{
System.out.println(number + " not between 1 and 10, choose again");
}
else
{
for (count=1; count<=number ; count++)
{
System.out.println("o");
for (count=1; count<=number; count++)
{
System.out.print("o");
}
}
}
}
}
Thanks!!
Edit:
Sorry, my problem was that the execution of the code gives me:
o
oooo
and I did not know how to solve it
I haven't seen the question. But I assume the problem is using of "count" variable as an iteration variable in two loops. To fix it just use another variable like:
public static void main(String args[])
{
Scanner teklatua = new Scanner(System.in);
int number = -1;
while (number> 10 || number< 1)
{
System.out.println("Choose a number between 1 and 10");
String datu = teklatua.nextLine();
number = Integer.parseInt(datu);
}
for (int i=0;i<number;i++)
{
for (int a =0;a<i+1;a++)
System.out.print("o");
System.out.println();
}
}
Consider using a helper method for the validation of the user's input:
import java.util.Scanner;
class Main {
private static int getIntegerInput(Scanner scanner, String prompt, int minValue, int maxValue) {
System.out.print(prompt);
int validInteger = -1;
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
validInteger = scanner.nextInt();
if (validInteger >= minValue && validInteger <= maxValue) {
break;
} else {
System.out.printf(
"Error: Please enter an integer between %d and %d inclusive%n", minValue, maxValue);
System.out.print(prompt);
}
} else {
System.out.printf(
"Error: Please enter an integer between %d and %d inclusive%n", minValue, maxValue);
System.out.print(prompt);
scanner.next();
}
}
return validInteger;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int minLines = 1, maxLines = 10;
String numLinesPrompt = "Please enter the number of lines: ";
int numLines = getIntegerInput(scanner, numLinesPrompt, minLines, maxLines);
for (int i = 0; i < numLines; i++) {
for (int j = 0; j <= i; j++) {
System.out.print('o');
}
System.out.println();
}
}
}
Example Usage:
Please enter the number of lines: 12
Error: Please enter an integer between 1 and 10 inclusive
Please enter the number of lines: -2
Error: Please enter an integer between 1 and 10 inclusive
Please enter the number of lines: a
Error: Please enter an integer between 1 and 10 inclusive
Please enter the number of lines: 5
o
oo
ooo
oooo
ooooo
You might want add another variable for the inner loop. Somthing like this:
....
for (int row = 1; row <= number; ++row) {
System.out.println("o");
for (int column = 1; column <= row; ++column) {
System.out.print("o");
}
}
....
The nested loops need to be updated:
the outer loop has a separate counter of lines i which also defines how many "o" are printed
the inner loop prints not more than i characters
upon ending the inner loop, new line is printed
for (int i = 1; i <= number; i++) {
for (count=1; count <= i; count++) {
System.out.print("o");
}
System.out.println();
}
Another approach could be to use String::repeat instead of inner loop:
for (count = 1; count <= number; count++) {
System.out.println("o".repeat(count));
}
your second forLoop is wrong
it should be something like
for(int j=1;j<=n;j++) {
for(int i=1; i<=j; i++) {
System.out.print("0");
}
System.out.println();
}
I am currently having an issue with a problem where my java index is out of bounds. The specific error is inside my binaryToDecimal method and is Index 32 out of bounds for length 32. I have tried to reorganize my code as in declaring the int binaryVal[] = new int[32]; as a global variable to fix the error but it does not work. How do I fix this issue?
import java.util.Scanner;
public class NumberConverter {
public static Scanner input = new Scanner(System.in);
static boolean success;
static String originalNum;
static int value = 0;
static int choice = 0;
static int intNum = 0;
static int remainder;
static char [] valueBinaryArray;
public static void main(String[] args) {
// TODO Auto-generated method stub
greeting();
getOriginalNumber();
getOutputType();
//checkValidInput();
if (value == 2 && choice == 3) {
decimalToHex();
}
else if (value == 3 && choice == 2) {
hexToDecimal();
}
else if (value == 2 && choice == 1) {
decimalToBinary();
}
else if (value == 1 && choice == 2) {
binaryToDecimal();
}
}
public static void greeting() {
System.out.println("Hello and welcome to the number systems converter");
System.out.println("Below you will be givin options as to what numbers you'd like to convert");
System.out.println("");
}
public static String getOriginalNumber() {
System.out.println("Enter a number:");
originalNum = input.next();
System.out.println("What type of number is this?");
System.out.println("");
System.out.println("1. Binary");
System.out.println("2. Decimal");
System.out.println("3. Hexadecimal");
value = input.nextInt();
return originalNum;
}
public static void getOutputType() {
System.out.println("Which number system would you like to convert to?");
System.out.println("");
System.out.println("1. Binary");
System.out.println("2. Decimal");
System.out.println("3. Hexadecimal");
choice = input.nextInt();
}
public static void checkValidInput() {
}
public static void decimalToHex() {
int intNum = Integer.valueOf(originalNum);
String str2 = "";
char hex[] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
while (choice > 0) {
remainder = intNum % 16;
str2 = hex[remainder] + str2;
intNum = intNum/16;
}
}
public static void hexToDecimal() {
int intNum = Integer.valueOf(originalNum);
int counter = 0;
String hexVal = "";
int digit;
while (choice > 0) {
digit = intNum % 16;
switch (digit) {
case 1:
hexVal+="F"; break;
case 2:
hexVal+="E"; break;
case 3:
hexVal+="D"; break;
case 4:
hexVal+="C"; break;
case 5:
hexVal+="B"; break;
case 6:
hexVal+="A"; break;
default:
hexVal+=Integer.toString(digit);
}
intNum = intNum/16;
}
for (counter = hexVal.length()-1; counter>=0; counter--)
System.out.print(hexVal.charAt(counter));
}
public static void decimalToBinary() {
int intNum = Integer.valueOf(originalNum);
int counter = 0;
int binaryVal[] = new int[32];
while (choice > 0) {
binaryVal[counter++] = intNum % 2;
intNum = intNum/2;
}
for (int i = counter-1; i >= 0; i--) {
System.out.println(binaryVal[i]);
}
}
public static void binaryToDecimal() {
int intNum = Integer.valueOf(originalNum);
int counter = 0;
int binaryVal[] = new int[32];
while (choice > 0) {
binaryVal[counter++] = intNum % 2;
intNum = intNum/2;
}
for (int i = counter-1; i >= 0; i--) {
System.out.print(binaryVal[i]);
}
}
}
If you have an array with 32 items the first one is index 0 and the last one is index 31. Trying to access the item at position 32 goes out of the range of the array which is why you get an array index out of bounds exception.
To see the output I would suggest maybe make the array 33 big instead of 32. It's not a proper fix but you should be able to see what it is doing.
If it still goes out of bounds I'd have a closer look at your while loop end condition.
so what is causing your error is your condition in your for statement. Currently, you are just checking if choice >= 0 the problem with this check is that it allows the for statement to go beyond the length of the array you have specified (32). In order to fix this error, you simply need to add another check to make sure the for loop cannot go beyond the length of the array you have specified. This can be done by adding this statement into your for loop: counter < binaryVal.length. This should prevent the for loop from going beyond the length of your array and you shouldn't run into any errors. Your final code for your binaryToDecimal method should look like this:
public static void binaryToDecimal() {
int intNum = Integer.valueOf(originalNum);
int counter = 0;
int binaryVal[] = new int[32];
while (choice > 0 && counter < binaryVal.length) {
binaryVal[counter++] = intNum % 2;
intNum = intNum/2;
}
for (int i = counter-1; i >= 0; i--) {
System.out.print(binaryVal[i]);
}
}
So my professor had us do an assignment that asks the user for 5 numbers that are valid (51-99) and unique (non-repeating). I just can't figure out why my nested for loop inside the while loop is not incrementing the i, I suspect it is the break; but without that the for loop keeps looping. Any help would be awesome. Thank you.
public static void main(String[] args) {
int[] userArray;
userArray = new int[5];
int real = 0;
System.out.println("Please print out 5 numbers between 50 and 100. ");
Scanner entry = new Scanner(System.in);
while (real < 5) {
int count = entry.nextInt();
boolean aCount = isValid(count);
if (aCount == true) {
for (int i =0; i < userArray.length; i++) {
userArray[i] = count;
real++;
break;
}
} else {
System.out.println("That is not a valid number.");
}
}
}
public static boolean isValid(int a) {
if (a > 50 && a < 100) {
return true;
} else {
return false;
}
}
I got it guys! I just had to remove the for loop and put this in:
userArray[i] = count;
i++;
real++;
Thank you schmidt73 and everyone that helped!
int i=0;
while (real < 5) {
int count = entry.nextInt();
boolean aCount = isValid(count);
if (aCount == true) {
userArray[i++] = count;
real++;
} else {
System.out.println("That is not a valid number.");
}
}
I guess this is what you are trying to do.
First, you also need to test if the array contains the value you are trying to add (in validate). You could do something like
public static boolean isValid(int[] arr, int real, int a) {
if (a > 50 && a < 100) {
for (int i = 0; i < real; i++) {
if (arr[i] == a) {
return false;
}
}
return true;
}
return false;
}
Then your main method might be written like
int[] userArray = new int[5];
int real = 0;
System.out.println("Please print out 5 numbers between 50 and 100. ");
Scanner entry = new Scanner(System.in);
while (real < 5) {
int count = entry.nextInt();
if (isValid(userArray, real, count)) {
userArray[real++] = count;
} else {
System.out.println("That is not a valid number.");
}
}
System.out.println("The array contains: " + Arrays.toString(userArray));
When I run this nothing prints, I am trying to print a message saying odd or even depending on what the user types.
import java.util.Scanner;
public class Questions {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Your number");
int number = input.nextInt();
for (int i = 0; i > 0; i = +2) {
if (number == i) {
System.out.println("even");
} else {
System.out.println("odd");
}
}
}
}
Your loop is never entered, because you initialize i with 0 and your first test is i > 0 (and you don't want a unary 2, = +2). I would also use formatted IO. Putting that together, I think you wanted something like
int number = input.nextInt();
for (int i = 0; i < number; i++) {
if ((i % 2) == 0) {
System.out.printf("%d even%n", i);
} else {
System.out.printf("%d odd%n", i);
}
}
If you're trying to avoid modulo (and use addition by 2) you could optimize with something like
int number = input.nextInt();
for (int i = 0; i < number; i += 2) {
System.out.printf("%d even%n", i);
System.out.printf("%d odd%n", i + 1);
}
Try this
import java.util.Scanner;
public class Questions {
public static void main (String[]args) {
Scanner input= new Scanner(System.in);
System.out.println("Your number");
int number = input.nextInt();
if(number % 2 == 0)
System.out.println("even");
}else {
System.out.println("odd");
}
}
may be you want to try this way...
if ((number % 2) ==0) {
System.out.println("even");
} else {
System.out.println("odd");
}
As you initialize i and the condition seems to be i>0 so it will always be false so for loop never executed
As #MadProgrammer stated in comments your loop never executed.
because i = 0, the loop is never executed ;)
I want to display the prime number required by the user. For example, if the user wants 3rd prime, I will display 5. I have the following java code.
import java.util.Scanner;
public class Prime {
private static Scanner scanner;
public static void main(String args[]) {
//get input till which prime number to be printed
// System.out.println("Enter which prime number to be printed: ");
// scanner = new Scanner(System.in);
// int limit = scanner.nextInt();
int count = 0;
int number = 2;
//System.out.println("Printing prime number from 1 to " + limit);
while(count<=3)
{
if(isPrime(number)){
count++;
// System.out.println(count);
}
number++;
}
if(count == 3)
System.out.println("10001 prime is "+number);
}
public static boolean isPrime(int number){
for(int i=2; i<number; i++){
if(number%i == 0){
return false;
}
}
return true;
}
}
When i run it, I am not able to gett any output. Where am i going wrong?
PS: For time being, I am running the loop only until 3.
You have while(count <= 3) so when you exit the loop, count == 4.
Therefore, your if(count == 3) is never entered and nothing is printed.
Anyways the better solution would be
public void calcPrime(int inp) {
ArrayList<Integer> arr = new ArrayList<Integer>();
arr.add(2);
arr.add(3);
int counter = 4;
while(arr.size() < inp) {
if(counter % 2 != 0 && counter%3 != 0) {
int temp = 4;
while(temp*temp <= counter) {
if(counter % temp == 0)
break;
temp ++;
}
if(temp*temp > counter) {
arr.add(counter);
}
}
counter++;
}
System.out.println("finish" +arr.get(inp-1));
}
}
Here is corrected code that works.
public class Main {
public static void main(String args[]) {
//Returns fourth prime number
System.out.println(getPrimeNumber(4));
}
public static int getPrimeNumber(int order) {
int currentOrder = 1;
int currentNumber = 1;
while (currentOrder < order) {
currentNumber++;
if (isPrime(currentNumber)) currentOrder++;
}
return currentNumber;
}
public static boolean isPrime(int number) {
for (int i = 2; i < number; i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
}
There was no need to start your counter at 0 and it mathematically wrong to start with number 2 ! Just begin with order and currentNumber initialized at 1 and if first prime number is what your user is looking for, no loop will be required !
Also, your loop condition after correct variable initialization was corrected from "<=" to "<".
That's all !