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++;
}
}
Related
This is simple code but I am not able to figure out why it is accepting two lines of input:
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
String inputString = scan.nextLine();
int n = Integer.parseInt (inputString);
for (int i = 1; i <= n; ++i) {
inputString = scan.nextLine();
int num = Integer.parseInt (inputString);
System.out.println ("Checking prime of: " + num);
for (int j = 2; j*j < num; ++j) {
if (num % j == 0) {
System.out.println ("Not prime");
break;
}
}
System.out.println ("Prime");
}
}
}
Now when I run with the following input:
3
12
5
7
The program prints the following:
Checking prime of: 12
Not prime
Prime
Checking prime of: 5
Prime
Checking prime of: 7
Prime
Note the second Prime above when it has not consumed any input.
I must be making a simple mistake but not able to figure out what is wrong. If someone could point out what I am doing wrong that would be much appreciated.
This line is being printed always, every cycle.
System.out.println ("Prime");
Add a flag variable instead, inside your for 1st loop
boolean isPrime = true;
And inside your if:
if (num % j == 0) {
isPrime = false;
break;
}
Then have another condition
if (isPrime) {
System.out.println ("Prime");
} else {
System.out.println ("Not prime");
}
That's it
for (int j = 2; j*j < num; ++j) {
if (num % j == 0) {
System.out.println ("Not prime");
break;
}
}
System.out.println ("Prime");
The last line is called either way. You need to either initialize a flag to help you figure out if the loop ended early, or simply return whenever you print "Not prime".
You do a scan on the 2nd line of the main method, then again at the top of your loop. The first one consumes the first line of input, but all you do with it is parse it into an int, you don't check it and don't output anything for it.
import java.io.*;
import java.util.*;
class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
String inputString = scan.nextLine();
int n = Integer.parseInt (inputString);
a: for (int i = 1; i <= n; ++i) {
inputString = scan.nextLine();
int num = Integer.parseInt (inputString);
System.out.println ("Checking prime of: " + num);
for (int j = 2; j*j <= num; ++j) {
if (num % j == 0) {
System.out.println ("Not prime");
continue a;
}
}
System.out.println ("Prime");
}
}
}
here you have pay attention over two points.
1. about break statement
that is it will break u from innermost loop only and that is the reason "prime" is printed whether the number is prime or not . so use labelled loop concept as i have used with "continue" .
your logic in "for loop" of checking the number whether it is prime or not is little bit wrong correct it as i have corrected that for(int j=2;j*j<=num;++j)
that is "<=" should be used in place of "<" otherwise on input 9,25etc.it will show prime which is wrong
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);
}
}
}
I FIGURED EVERYTHING OUT TY FOR THE HELP
When I type in letters at attempt 1/4 it works fine and it continues, but once I type a letter at attempt 2/4 it just prints the message and the program stops. Also any tips on #2, I can only think of if(guess>=4 && guess<=16) else statement(not sure if this is correct)
When I execute the code -
Guess a number between 1 and 16.
Attempt 1 of 4: 8
You guessed 8
Too Low!
Attempt 2 of 4: a
Please enter an integer between 4-16
can't enter anything after
Problems: I have to make exception handlers if user types in a
1) non-numeric input
2) out of range input
3) Have to retain current guess amount
import java.util.InputMismatchException;
import java.util.Random;
import java.util.Scanner;
public class GuessingGame {
static final int limit = 4;
static final int maxInteger = 16;
public static void main(String[] args) {
Random rand = new Random();
int target = rand.nextInt(maxInteger) + 1;
int x = 1;
do{
try{
Scanner input = new Scanner(System.in);
System.out.printf("Guess a number between 1 and %d.\n", maxInteger);
int attempts = 1;
while (attempts <= limit) {
System.out.printf("Attempt %d of %d: ", attempts, limit);
int guess = input.nextInt();
System.out.printf("You guessed %d\n", guess);
if(guess > target) {
System.out.printf("Too High! \n");
}
else if(guess == target){
System.out.printf("The answer is %d, You win!", guess);
attempts = 20;
}
else{
System.out.printf("Too Low! \n");
}
attempts+=1;
x = 2;
}
if(attempts==5){
System.out.println("You lose!");
}
}
catch(InputMismatchException e){
System.out.printf("Please enter an integer between 4-16");
continue;
}
}while(x == 1);
}
}
You are checking while(x == 1); in the outer loop and from the inner loop you incremented the value of x by doing x = 2;. This will break the condition and you'll come out of the outer while loop.
You should be setting a valid condition for the outer while loop if you want to continue. Try something like while(x < 5);
Your code should look something like this:
do {
try {
...
/* Inner While */
while() {}
...
} catch () {
/* Exception Handling */
...
}
} while(x < 5); /* Decide a valid condition */
1) try moving your try catch block inside the inner loop so it only encloses
int guess = input.nextInt();
2) your idea for number 2 should work.
if(guess>=4 && guess<=16)
make sure this is the first if statement in your checks, then you don't have to change any of your other if statements.
3) make a variable outside both of the loops called guess, then instead of saying
int guess = input.nextInt();
just say
guess = input.nextInt();
The current guess wil be availble to you until you update it.
4) your variable x is confusing. Are you using it as a flag to end the outer loop? if that is the case make it a boolean
boolean flag = true;
then you can set the flag to false when you are ready to break out of the loop. change
x = 2;
to
flag = false;
also for the loop all change
while(x==1)
to
while(flag)
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!
Every time i try to compile my code i get a error about a missing return statement. Any ideas about whats wrong with my code?
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
So i fixed a couple of things, but now im getting an error where my variable 'result' might not have been initialized, any suggestions?
import javax.swing.JOptionPane;
import java.io.*;
public class facts
{
public static void main(String[]args)
{
String input;
int x;
char y,prime,perfect;
do{
input = JOptionPane.showInputDialog("Enter an integer");
x = Integer.parseInt(input);
if(x%2==0)
System.out.println("The integer is even - it is evenly divisible by 2");
else
System.out.println("The integer is not even - it is not evenly divisible by 2");
prime = isPrime(x);
if(prime == 't')
System.out.println("The integer is a prime number");
else
System.out.println("The integer is not a prime number");
perfect = isPerfect(x);
if(perfect == 't')
System.out.println("The integer is a perfect number");
else
System.out.println("The integer is not a perfect number");
input = JOptionPane.showInputDialog("Enter Y for another number, anything else to quit");
y = input.charAt(0);
}while(y=='Y');
System.out.println("Good Bye");
System.exit(0);
}
public static char isPrime(int x)
{
for(int y=2;y<x;y++)
{
if(x%y==0)
return 't';
else
return 'f';
}
}
public static char isPerfect(int x)
public static int triAng(int x)
{
int result,z,y = 1;
while(y<=x)
{
z=y*(y+1)/2;
y++;
System.out.println(z);
result = z;
}
return result;
}
You need to put return statements after your for loops and return a default char or null, in case the loops would not be entered. And in your isPerfect, even the if may not be entered.
For your variable 'result' might not have been initialized problem, the problem is that line:
int result,z,y = 1;
only the y variable is initialized to 1. As you might not enter the while loop, then the return statement would return result with it not having been initialized, so you need to explicitly specify a value to it (null or whatever integer).
If you want them all to be 1 you can do:
int result,z,y;
result = z = y = 1;
in your isPerfect method, you don't have a return statement for the case that the code does not enter if if(x%y==0) block.
For example, this code might not return if x <= 1 or if x%y is never 0:
public static char isPerfect(int x)
{
int y,z=0;
for(y=1;y<x;y++)
{
if(x%y==0)
{
z+=y;
if(z==x)
return 't';
else
return 'f';
}
}
}
In the isPrime and isPerfect methods, your code may not enter in the for loop. To adjust it, put a default return on the end of these methods or throw an exception.