I am trying to write a program that takes an integer value (n) from the user, checks that it is greater than 0 and less than 30. If this is the case it calls my catalan numbers method and substitutes n in. If the inputted number is less than 0 or greater than 30 it should throw and IllegalArgumentException.
There doesn't seem to be a problem with the catalan numbers method, but there are when I try and call the catalan numbers method and input 'n' into it. All the problems are confined to the switch statement, where it will not accept the functions 'n.equals("quit"), (n>30), (n < 0), and it won't call my catalan numbers method.
Here is my code so far:
public class Exercise_3 {
public static long catalan(int n) throws IllegalArgumentException {
int res = 0;
// Base case
if (n <=1) {
return 1;
}
for (int i = 0; i < n; i++) {
res += catalan(i) * catalan( n - i - 1);
}
return res;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Exercise_3 cn = new Exercise_3();
System.out.println("Please enter an integer greater than 0 and less than 30 or type 'quit' to exit.");
boolean n = scan.nextBoolean(); {
switch(n) {
if (n.equals("quit")) {
break;
}
else
case (n > 30):
throw IllegalArgumentException;
break;
case (n < 0):
throw IllegalArgumentException;
break;
case (0 < n <= 30):
int i = cn(n);
break;
}
System.out.println(i);
}
}
}
If anybody has any solutions to this I would be very grateful.
Your approach in using switch is, sorry for that, completely wrong. This is no JavaScript where you can pass the result of a Promise to a boolean. If you want to use Java, you have to learn a totally different thinking in solving problems. Switch is the worst choice to your problem. Try it with nested If-Statements instead.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter an integer greater than 0 and less than 30 or type 'quit' to exit.");
String input = scan.next();
if(!input.equals("quit")) {
int number = Integer.parseInt(input);
if(number < 0 || number > 30) {
throw new IllegalArgumentException("number out of range");
}
else {
int i = catalan(number);
System.out.println(i);
}
}
}
Related
Given a sequence of natural numbers. For each number of the sequence output even if the number is even, otherwise, odd. If the number is equal to 0, the program must stop reading and processing numbers.
class Main {
public static void main(String... args) {
// put your code here
Scanner scanner = new Scanner(System.in);
//int max = 0;
int number = 0;
while (scanner.hasNext()) {
number = scanner.nextInt();
if (number % 2 != 0) {
System.out.println("Odd");
continue;
} else if (number % 2 == 0) {
System.out.println("even");
break;
}
}
}
}
I have the following problem:
I canĀ“t input a sequence of natural numbers, each number in a new line (see please the attachment. I can only input 2 numbers...
Failed test #1 of 9. Wrong answer
This is a sample test from the problem statement!
Test input:
1
2
3
4
0
Correct output:
odd
even
odd
even
Your code output:
Odd
even
You should not break the condition when the number is even.
There should be another condition to check if number = 0
public static void main(String[] args) {
// put your code here
Scanner scanner = new Scanner(System.in);
int number = 0;
while (scanner.hasNext()) {
number = scanner.nextInt();
if(number == 0) {
break;
}
else if (number % 2 == 0) {
System.out.println("even");
} else {
System.out.println("odd");
}
}
}
public static void main(String... args) {
Scanner scan = new Scanner(System.in);
while (true) {
int num = scan.nextInt();
if (num == 0)
break;
System.out.println(num % 2 == 0 ? "even" : "odd");
}
}
I think that you have a typo in your code :)
Please, refactor the line:
System.out.println("Odd");
to
System.out.println("odd");
Also, you may not call the loop controls (break, continue) at all:
public static void main(String... args) {
Scanner scanner = new Scanner(System.in);
int number = 0;
while ((number = scanner.nextInt()) != 0) {
if (number % 2 != 0) {
System.out.println("odd");
} else {
System.out.println("even");
}
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int number = 0;
System.out.println("Start putting numbers");
while (scanner.hasNext()) {
number = scanner.nextInt();
if (number % 2 != 0) {
System.out.println("Odd");
continue;
} else if (number % 2 == 0){
System.out.println("even");
}
if(number == 0)
break;
}
}
}
}
I've been trying practiceIt problems and expand them a little - and I'm stuck.
The code will give results in as many stars as it's necessary, but I do not know how to make user decide the value for n.
I've tried adding to both methods (main/starString) those code lines:
"Scanner input = new.Scanner(System.in);
int n = input.next();" [also input.nextInt]
but the code will note allow any input from console. Not to mention I've got no idea where shoud I add second println command to actually print result from this code...
help me please
import java.util.*;
public class printStars {
public static void main(String[]args) {
System.out.println("choose number and I wil show you 2^number stars");
}
public static String starString(int n) {
if (n < 0) {
throw new IllegalArgumentException();
} else if (n == 0) {
return "*";
} else {
return starString(n - 1) + starString(n - 1);
}
}
}
Do it as follows:
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Choose number and I wil show you 2^number stars: ");
System.out.println(starString(in.nextInt()));
}
public static String starString(int n) {
if (n < 0) {
throw new IllegalArgumentException();
} else if (n == 0) {
return "*";
} else {
return starString(n - 1) + starString(n - 1);
}
}
}
A sample run:
Choose number and I wil show you 2^number stars: 5
********************************
You should also be checking the input before you enter the method. Here is one approach that allows for improper input and reprompts the user to enter the correct value. This way, no exceptions need be caught.
Scanner in = new Scanner(System.in);
String prompt = "Choose number (or a char to end) \nand I will show you 2^number stars: ";
System.out.print(prompt);
while (in.hasNextInt()) {
int n = in.nextInt();
if (n > 0) {
System.out.println(starString(n));
} else {
System.out.print("Input must be greater than 0, try again: ");
continue;
}
System.out.print(prompt);
}
System.out.println("Bye!");
public static String starString(int n) {
if (n == 0) {
return "*";
} else {
return starString(n - 1) + starString(n - 1);
}
}
I wrote a code about primes and would hear your opinion or any suggestions how i can improve my code. I'm a beginner in Java.
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
boolean a;
System.out.println("Please enter a number: ");
int zahl = s.nextInt();
if(zahl <= 0) {
System.out.println("Please enter a positive number without zero.");
return;
}
a = true;
for (int i = 2; i < zahl; i++) {
if (zahl % i == 0) {
a = false;
}
}
if (a == true) {
System.out.println("Is Prim");
}
if (a==false){
System.out.println("Not a prim");
}
}
The easiest thing to do is the following
Instead of
for (int i = 2; i < zahl; i++) {
if (zahl % i == 0) {
a = false;
}
}
change the for loop the
for (int i = 2; i < Math.sqrt(zahl); i++)
If no numbers up to the square root divide zahl, then no numbers beyond the square root will divide it either (they would have been the result of earlier divisions).
Also, for outputing the answer you could do:
System.out.println(zahl + " is " + ((a) ? "prime"
: "not prime"));
That's using the ternary operator ?:
some hints :
You do
System.out.println("Please enter a positive number without zero.");
return;
the println suggests the user can enter a new value, but no, in that case better to say the number was invalid so you exit
When you do a = false; it is useless to continue, no chance for a to be back true
It is useless to try to divide by more than sqrt the number
It is necessary to try to divide by 2 but not by an other even number, so add 2 to i rather than 1
If if (a == true) false it is useless to check if (a==false)
Your code is good. I have made three small improvements:
The input asks at once (and not only after a bad input) for a
positive int.
The input is repeated until correct.
The for loop runs only up to sqrt(zahl) which is sufficient.
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
boolean a;
int zahl = 0;
while (zahl <= 0) {
System.out.println("Please enter a positive int without zero.");
zahl = s.nextInt();
}
a = true;
for (int i = 2; i <= Math.sqrt(zahl); i++) {
if (zahl % i == 0) {
a = false;
break;
}
}
if (a == true) {
System.out.println("Is Prim");
} else {
System.out.println("Not a prim");
}
}
How do i prevent negative numbers from being returned by this method?
I have tried setting the while loop to
(n < 0 && n != 0)
to no avail.
Here is my code for the method currently:
public int getNumber() {
int n = 1;
while(n < 2 && n != 0) {
if(n < 0) {
System.out.print("Error, please enter a valid number greater than 0(0 to exit): ");
scan.next();
n = scan.nextInt();
}
try {
System.out.print("Enter the upper bound(0 to exit): ");
n = scan.nextInt();
break;
}
catch(java.util.InputMismatchException e) {
System.out.print("Error, please enter a valid number greater than 0(0 to exit): ");
scan.next();
continue;
}
}
return n;
}
I have also tried to put my if statement inside the try block like this:
public int getNumber() {
int n = 1;
while(n < 2 && n != 0) {
try {
System.out.print("Enter the upper bound(0 to exit): ");
n = scan.nextInt();
if(n < 0) {
System.out.print("Error, please enter a valid number greater than 0(0 to exit): ");
scan.next();
n = scan.nextInt();
}
break;
}
catch(java.util.InputMismatchException e) {
System.out.print("Error, please enter a valid number greater than 0(0 to exit): ");
scan.next();
continue;
}
}
return n;
}
When i put the if statement inside the try block, i started to input negative numbers consecutively to test. It worked for the first time i entered a negative number, then gave me a blank scanner input line, and then finally allowed a negative number to return, which in turn screws the rest of my program up. Please help, im a first semester student in java. Thank you.
You input a negative number, then it goes into your n<0 if and you put in another one and then break out of the loop.
Try changing your if to:
while(n < 0)
Do not use while loop condition for validating input. Your loop condition does not give your program a chance to accept and check the number before making a decision to keep or to reject the entered value. As the result, your program starts prompting end-users with an error message even before they typed anything.
You should not call nextInt without first checking if the Scanner is ready to give you an int by calling hasNextInt.
Finally, you need a rejection loop to throw away non-integer input until hasNextInt succeeds. This is usually done with a nested while loop, which prints an error prompt, and throws away the entered value.
The overall skeleton for reading and validating an int looks like this:
System.err.println("Enter a number between 0 and 5, inclusive");
int res = -1;
while (true) {
while (!scan.hasNextInt()) {
System.err.println("Incorrect input. Please enter a number between 0 and 5, inclusive");
scan.nextLine(); // Discard junk entries
}
res = scan.nextInt();
if (res >= 0 && res <= 5) {
break;
}
System.err.println("Invalid number. Please enter a number between 0 and 5, inclusive");
}
// When you reach this point, res is between 0 and 5, inclusive
couldn't you just check for 'hasNextInt', then test the input.
int n = 0;
System.out.println("Enter a number between 0 and 5);
while (scan.hasNextInt()) {
n = scan.nextInt();
if (n >= 0 && n <= 5) {
break;
}else{
//prompt error message or handle however you wish
}
}
return n;
likewise you could also force with an unsigned integer.
Final code to not return negative integers or strings:
public int getNumber() {
System.out.print("Enter the upper bound(0 to exit): ");
int nums = 1;
while(true) {
while(!scan.hasNextInt()) {
System.out.print("Error. Please enter a valid integer greater than 1(0 to exit): ");
scan.nextLine();
}
nums = scan.nextInt();
if(nums > 2 || nums == 0) {
break;
} else {
System.out.print("Error. Please enter a valid integer greater than 1(0 to exit): ");
scan.nextLine();
}
}
return nums;
}
Thanks a million you guys!
I have to write a program which asks a user to input integers, but they have to be positive.
I'm pretty sure I have to use a loop, and don't think I'm allowed to use Math.abs().
What I've written right now looks quite messy though. Here is the code:
public class Q1{
public static void main(String[] args){
int num1, num2, num3;
while(true){
System.out.println("Input first integer.");
num1 = TextIO.getInt();
if(num1 > 0)
break;
System.out.println("Integer isn't positive. Try again");
}
while(true){
System.out.println("Input second integer.");
num2 = TextIO.getInt();
if(num2 > 0)
break;
System.out.println("Integer isn't positive. Try again");
}
while(true){
System.out.println("Input third integer.");
num3 = TextIO.getInt();
if(num3 > 0)
break;
System.out.println("Integer isn't positive. Try again");
}
....
}
}
I've basically just done separate while loops for each integer to test if the integer is positive because when I use one loop I can't get it to run properly. Is there a way of just using one loop that will still work but looks much neater?
You can move that loop inside another method:
public int readPositiveInt() {
int num = 0;
int attempt = 0;
int maxAttempt = 3;
// Allow only maxAttempt to enter correct input.
while(true && attempt < maxAttempt) {
num = TextIO.getInt();
if(num > 0)
break;
System.out.println("Integer isn't positive. Try again");
++attempt;
}
return num;
}
And then call this method where ever you are having a loop currently.
Make sure TextIO, whatever it is, is available to this method.
Also, you should better enforce a maximum number of attempt, as you might go into an infinite loop, if user keeps on entering negative numbers.
You can wrap your while loop inside a for loop and put your integers in an array:
int[] nums = new int[] {-1, -1, -1};
for (int i = 0; i < 3; i++) {
while(nums[i] <= 0)
nums[i] = TextIO.getInt();
}
When programming you try and achieve 3 objectives: making your code, readable, intuitive and maintainable.
I would suggest you create a method you can reuse. The method in your case would look something like this:
public int readPositiveInt(String message) {
int num = 0;
boolean exitLoop = false;
while(!exitLoop){
System.out.println(message);
num = TextIO.getInt();
if(num > 0) {
exitLoop = true;
// I don't like to break from a while(true), I personally find it messy
}
else {
System.out.println("Integer isn't positive. Try again");
}
}
return num;
}
Instead of creating variables like, num1, num2, num3 ... simply create an int array and store all values in there. If you are not sure how many numbers you would like to store, I suggest you use an implementation of a List, like the ArrayList.
I hope this helps.
Something like this perhaps?
public class Q1{
public static void main(String[] args){
int[] input_integers = new int[3]; //create an array of however many integers you need
int i = 0; // initiate your counter
while(i<input_integers.length){ // you will loop through until all integers are set
System.out.println("Input integer number "+ (1+i)); // computers count from 0, humans from 1
input_integers[i] = TextIO.getInt();
if(input_integers[i] < 0) // check if it is not positive
System.out.println("Integer isn't positive. Try again");
else { // if it is, increment your counter and get the next integer
i++;
}
}
}
}
Hope this helps
** This code was not tested
Here is a solution with a single while loop and using no array(it can be done). But, you can see that it's not upto the expectation. Such an implementation is always inefficient and is discouraged. So better use an array or separate method like others are suggesting.
int i=0;
while (i < 3) {
int tmp = 0;
switch (i) {
case 0:
num1 = tmp = TextIO.getInt();
System.out.println("Input first integer.");
break;
case 1:
num2 = tmp = TextIO.getInt();
System.out.println("Input second integer.");
break;
case 2:
num3 = tmp = TextIO.getInt();
System.out.println("Input Third integer.");
break;
}
if (tmp < 0) {
System.out.println("Integer isn't positive. Try again");
} else {
i++;
}
}