I am trying to add exceptions to a program i've already wrote. I need to write exceptions when the user tries to cheat on a number guess program for the higher and lower methods as well as add a try/catch on the game to display the error. I almost have it written correctly but and exception is thrown right before the last possible outcome. Attached is the class file i wrote along with the program to run the game.
Here is my class for the number guesser logic
public class NumberGuesser {
private int min, max, midpoint, origMin, origMax;
public NumberGuesser()
{
min = 1;
max = 100;
}
public NumberGuesser(int lowerBound, int upperBound)
{
min = lowerBound;
max = upperBound;
origMin = lowerBound;
origMax = upperBound;
}
public void setMin(int value)
{
min = value;
}
public void setMax(int value)
{
max = value;
}
public int getMin()
{
return min;
}
public int getMax()
{
return max;
}
public void higher()
{
min = getCurrentGuess() + 1;
if (min == max)
{
throw new IllegalStateException("No more possible outcomes");
}
}
public void lower()
{
max = getCurrentGuess() -1;
if (max == min)
{
throw new IllegalStateException("No more possible outcomes");
}
}
public int getCurrentGuess()
{
midpoint = (max + min) /2;
return midpoint;
}
public void reset()
{
min = origMin;
max = origMax;
}
}
Here is the program that runs the game.
import java.util.*;
public class GuessingProgram {
public static void main(String[] args) {
do
{
playOneGame();
}
while (shouldPlayAgain());
}
public static void playOneGame()
{
char input = 0;
Scanner keyboard = new Scanner(System.in);
NumberGuesser game = new NumberGuesser(1,100);
System.out.println("NUMBER GUESSER GAME");
System.out.println("-------------------");
System.out.println("Think of a number between 1 and 100");
while (input != 'c')
{
try
{
System.out.print("Is your number " + game.getCurrentGuess() + "?" +
" (h/l/c): ");
input = keyboard.next().charAt(0);
if (input == 'h' || input == 'H')
game.higher();
else if (input == 'l' || input == 'L')
game.lower();
else if (input == 'c' || input == 'C')
game.reset();
}
catch(IllegalStateException e)
{
System.out.println("Invalid input, You are cheating!!!");
}
}
}
public static boolean shouldPlayAgain()
{
Scanner keyboard = new Scanner(System.in);
System.out.print("Great! Do you want to play again? (y/n): ");
String input = keyboard.nextLine();
if (input.equalsIgnoreCase("y"))
return true;
else
return false;
}
}
Here is my output and the number its supposed to guess is 77
NUMBER GUESSER GAME
Think of a number between 1 and 100
Is your number 50? (h/l/c): h
Is your number 75? (h/l/c): h
Is your number 88? (h/l/c): l
Is your number 81? (h/l/c): l
Is your number 78? (h/l/c): l
Is your number 76? (h/l/c): h
Invalid input, You are cheating!!!
Is your number 77? (h/l/c):
If min and max reach the same value, that means you've found the correct value. I think you want to throw illegalStateException if you say the number is higher/lower after you found the correct value, it is, max < min.
Related
I'm new to coding and I'm required to have a return statement but I'm struggling on how to return the values of count from my while loop. I put a link of picture of what I'm getting plus my code is below.
Also I added a printout of "is factor of number " + count just so I can see what count is doing during the while loop. What I really want to do is return these values so when I hit run these values and only these values appear.
Here is my code:
package allFactors;
public class AllFactors {
public static void main(String[] args) {
System.out.println(printFactors(25));
}
public static int printFactors(int number) {
if (number < 1) {
System.out.println("Invalid Value ");
}
int count = 0;
while (count <= number) {
count++;
if (number % count == 0) {
System.out.println(count + " is factor of number ");
continue;
}
}
return count;
}
}
my CURRENT output is as follows:
1 is factor of number
5 is factor of number
25 is factor of number
26
i only put system.out.println(count + " is factor of number "); BECAUSE
i want to see what my count value is, NOW i dont want to return count; because that just gives me 26, i want to JUST return 1, 5 and 25. Because these numbers are all factors of 25; once i can do this i will delete my system.out.println(count + " is factor of number "); line of code because it is not necessary. I hope this question make sense
DESIRED OUTPUT
1
5
25
Here you want to return all the factors of the number :
So you can use the list to store all the factors and then return that list and print it, code is this -
package allFactors;
public class AllFactors {
public static void main(String[] args) {
printFactors(32).forEach(System.out::println);
}
public static List<Integer> printFactors(int number) {
if (number < 1) {
System.out.println("Invalid Value ");
}
List<Integer> all_factors = new ArrayList<>();
int count = 0;
while (count <= number) {
count++;
if (number % count == 0) {
all_factors.add(count);
System.out.println(count + " is factor of number ");
continue;
}
}
return all_factors;
}
}
return is like the output of your function. In the code you said return 0, so no matter what, it will only print 0. Change it to return count; is how you do it.
just return the count from the end of the method as follows
public static int printFactors(int number) {
if (number < 1) {
System.out.println("Invalid Value ");
}
int count = 0;
while (count <= number) {
count++;
if (number % count == 0) {
System.out.println(count + " is factor of number ");
continue;
}
}
return count;
}
if you want to return all values you need to use some collection please check below code
package allFactors;
import java.util.ArrayList;
import java.util.List;
public class AllFactors {
public static void main(String[] args) {
System.out.println(printFactors(32));
}
public static List<Integer> printFactors(int number) {
if (number < 1) {
System.out.println("Invalid Value ");
}
List<Integer> factors = new ArrayList<>();
int count = 0;
while (count <= number) {
count++;
if (number % count == 0) {
factors.add(count);
System.out.println(count + " is factor of number ");
}
}
return factors;
}
}
Need to write a program to calculate sum of all digits and then give results when the total sum vaue ends with 5 or 8.Please help correct this code!
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in= new Scanner(System.in);
int customerID = in.nextInt();
while(customerID > 0)
{
int Reminder = customerID % 10;
int sum = sum+ Reminder;
customerID = customerID / 10;
}
if(sum%5||sum%8)
{
System.out.println("Lucky Customer");
}else
{
System.out.println("Unlucky Customer");
}
if(sum <0)
{
System.out.println("Invalid Input");
}
}
}
instead of doing
if(sum%5||sum%8)
{
System.out.println("Lucky Customer");
}
where sum%8 will be true for the value 16 so you can try this
int rem=sum%10;
if(rem==5||rem==8)
{
System.out.println("Lucky Customer");
}
Apart from the fact that this code doesn't produce the error you've mentioned, there are other issues with the code. I've tried to address them instead.
public static void main(String[] args) {
Scanner in= new Scanner(System.in);
int customerID = in.nextInt();
int sum = 0;
// sum needs to be initialized outside the while loop
// or else you wouldn't be able to use it outside it
while(customerID > 0) {
int Reminder = customerID % 10;
sum = sum+ Reminder;
customerID = customerID / 10;
}
if(sum%5 == 0 || sum%8 == 0) {
//You cannot use int as a condition in if
System.out.println("Lucky Customer");
} else {
System.out.println("Unlucky Customer");
}
if(sum <0) {
System.out.println("Invalid Input");
}
}
This code throws this exception only if your input would contain a dot (e.g.: "3.0"). So either pass the int value (e.g.: "3") or use scanner.nextDouble() and then convert it to int.
Also look into Yash's answer, because your code has other problems too.
+never write variable names with capital letter ("Reminder")!!!!
Please correct your code to remove some compilation errors...
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in= new Scanner(System.in);
int customerID = in.nextInt();
int sum = 0;
while(customerID > 0) {
int Reminder = customerID % 10;
sum = sum + Reminder;
customerID = customerID / 10;
}
if(sum % 5 == 0 || sum % 8 == 0) {
System.out.println("Lucky Customer");
} else {
System.out.println("Unlucky Customer");
}
if(sum <0) {
System.out.println("Invalid Input");
}
}
}
I have created a program using Java that generates emirps by user input, but I need help on stopping the user when entering zero or a negative integer. I have tried many things but when I run the program with zero or a negative number it will go crazy and give me infinite amount of numbers. I would appreciate it if someone could help me on this.
Here is what I got so far...
import java.util.Scanner;
public class GenerateEmirps {
public static void main(String[] args) {
Scanner scanner = new Scanner (System.in);
System.out.print("Enter number of desired emirps: ");
int emrips = scanner.nextInt();
int count = 1;
for( int i = 2; ; i++){
if ((isPrime(i)) && (isPrime(reverseIt(i))) && (!isPalindrome(i))) {
System.out.print(i + " ");
if (count % 10 == 0) {
System.out.println();
}
if (count == emrips){
break;
}
count++;
}
}
}
public static boolean isPrime(int num){
for (int i = 2; i <=num / 2; i++){
if (num % i == 0) {
return false;
}
}
return true;
}
public static int reverseIt(int num){
int result = 0;
while (num != 0) {
int lastDigit = num % 10;
result = result * 10 + lastDigit;
num /= 10;
}
return result;
}
public static boolean isPalindrome(int num){
return num == reverseIt(num);
}
}
Solution:
You just need to test the input before you process it.
int emrips = scanner.nextInt();
if (emrips <= 0) { System.exit(0); }
Basically I need to write a program that takes user input up to and including 2^31 -1 in the form of an integer and returns the amount of odd, even, and zero numbers in the int. For example,
Input: 100
Output: 1 Odd, 0 Even, 2 Zeros // 1(Odd)0(Zero)0(Zero)
or
Input: 2034
Output: 1 Odd, 2 Even, 1 Zero // 2(Even)0(Zero)3(Odd)4(Even)
I'm pretty sure I'm over thinking it but I can't slow my brain down. Can anyone help?
This is the third iteration of the code, the first two were attempted with for loops.
import java.util.Scanner;
public class oddEvenZero
{
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
int value;
int evenCount = 0, oddCount = 0, zeroCount = 0;
System.out.print("Enter an integer: ");
value = scan.nextInt();
while (value > 0) {
value = value % 10;
if (value==0)
{
zeroCount++;
}
else if (value%2==0)
{
evenCount++;
}
else
{
oddCount++;
}
value = value / 10;
}
System.out.println();
System.out.printf("Even: %d Odd: %d Zero: %d", evenCount, oddCount, zeroCount);
}
}
Sorry, the code formatted weirdly in the textbox.
value = value % 10;
Probably the end-all-be-all of your problems.
If value is 2034, then value % 10 returns 4... and then assigns that value to value, you go through your if else block, then do 4/10 get 0, and exit the while loop without addressing the other 3 digits.
I suggest something more like this:
while (value > 0) {
if ((value%10)==0) {
zeroCount++;
}
else if (value%2==0) { //As per comment below...
evenCount++;
}
else {
oddCount++;
}
value /= 10;
}
Or, int thisDigit = value % 10, then replace value in your current if else block with thisDigit.
value = value % 10;
This statement will override your original value with a reminder i.e value % 10.
If value = 2034 and value % 10 = 4, then value = 4 which isn't what you want.
Instead use a temporary variable
int lastDigit = value % 10;
Then your code becomes;
while (value > 0) {
int lastDigit = value % 10;
if (lastDigit==0)
{
zeroCount++;
}
else if (lastDigit%2==0)
{
evenCount++;
}
else
{
oddCount++;
}
value = value / 10;
}
import java.util.Scanner;
public class oddEvenZero
{
public int[] convertStringArraytoIntArray(String[] sarray) throws Exception {
if (sarray != null)
{
int k= sarray.length-1;
int intarray[] = new int[k];
for (int i = 1; i < sarray.length; i++) {
intarray[i-1] = Integer.parseInt(sarray[i]);
}
return intarray;
}
return null;
}
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
String value;
System.out.print("Enter an integer: ");
value = scan.next();
String words[] = value.split("");
oddEvenZero obj = new oddEvenZero();
try{
int intarray[]= obj.convertStringArraytoIntArray(words);
int even_number =0;
int odd_number =0;
int zero_number =0;
for (int h: intarray)
{
if(h==0)
{
zero_number++;
}
else if(h%2==0)
{
even_number++;
}
else{
odd_number++;
}
}
System.out.println("even numbers are"+ even_number);
System.out.println("odd numbers are"+odd_number);
System.out.println("Zero numbers are"+zero_number);
}
catch(Exception ex)
{
System.out.println("Please enter number");
}
}
}
If some of you are still unable to figure this code out, I found this while searching around for a bit, and works just fine:
import java.util.*;
public class Java_1
{
public static void main (String[] args)
{
String string;
int zero = 0, odd = 0, even = 0, length, left = 0;
Scanner scan = new Scanner(System.in);
System.out.print ("Enter any positive number: ");
string = scan.next();
length = string.length();
while (left < length)
{
string.charAt(left);
if (string.charAt(left) == 0)
zero++;
else if (string.charAt(left) % 2 == 0)
even++;
else
odd++;
left++;
}
System.out.println ("There are: "+ zero + " zeros.");
System.out.println ("There are: "+ even + " even numbers.");
System.out.println ("There are: "+ odd + " odd numbers.");
}
}
I need to create a program in Java that determines if a number is prime.
The user should enter any number, and the program will determine if it's prime or not, and display "not prime" or "prime." My code now compiles and runs but it always says a number isn't prime even if it is.
import java.util.Scanner;
public class PrimeNumber
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int constant = 0;
int variable = 0;
System.out.println("Enter a Number to test if Prime or Not");
constant = input.nextInt();
variable = constant;
double answer = 0.0;
answer = testPrime(constant, variable);
System.out.println(+answer);
if (answer == 1)
{
System.out.println(+constant + " is a prime number.");
}
else
{
System.out.println(+constant + " is NOT a prime number.");
}
}
public static double testPrime(int number, int divide)
{
double prime = 0.0;
prime = number%divide;
if (prime > 0 && divide != number)
{
return testPrime(number, divide - 1);
}
else
{
return prime;
}
}
}
if (prime > 0 && divide != number)
This will never be true. Because your divide and number are always equal.
See that you have assigned variable=constant and that's what you pass to the method
constant = input.nextInt();
variable = constant;
answer = testPrime(constant, variable);
That said, you need go so complex to find out if a number is prime or not. Check the web for simple algorithms. See http://www.mkyong.com/java/how-to-determine-a-prime-number-in-java/ for example.
Not the answer as the OP wants recursion (homework I guess).
You need to only go till the square root of n to see if it has a divisor (divisor besides self will be < sqrt(n))
boolean isPrime(int n) {
if(n % 2 == 0)return false;
int till = (int)java.lang.Math.pow(n, 0.5); //(int)n / 2;
for(int i= 3;i<till;i+=2) {
if(n % i == 0)
return false;
}
return true;
}
I see you want recursion for this, so I converted tgkprog's answer to a recursive method (although his is definitely more efficient). Additionally, I think you may want to return a prime factor if the input isn't prime? I'm just speculating this judging from the OP's return value of a double instead of a boolean. Mine will return an int though, because returning a double is silly.
int isPrime(int n){ //starter function
if(n<=1) return n; //sanity check for weird inputs
if(n % 2 == 0) return 2; //2 is a prime factor
int start = (int)java.lang.Math.pow(n, 0.5);
return isPrime(n,start-(start%2)); //makes start odd if it wasn't already
}
int isPrime(int n, int testval){ //recursive function
if(testval<=1) return 1; //n is prime, return n since it has no prime factors
if(n % i == 0)
return i; //found a prime factor!
return isPrime(n,i-2);
}
with recursion
import java.util.Scanner;
public class PrimeRecursion
{
static int dbg;
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter non 0 if you want debug :");
dbg = input.nextInt();
long constant = 3;
long variable = 0;
while(true){
System.out.println("Enter a Number to test if Prime or Not (1 to exit)");
constant = input.nextLong();
if(constant < 3){
if(constant == 2){
System.out.println("2 is a special prime");
}
return;
}
if(constant % 2 == 0){
System.out.println(constant + " is NOT a prime number, even number.");
}else{
variable = (long)Math.pow(constant, 0.5);
variable = (variable % 2 == 1) ? variable : variable + 1;//odd number
double answer = 0.0;
answer = testPrime(constant, variable);
System.out.println("End answer : " + answer);
if (answer == 1){
System.out.println(+constant + " is a prime number. answer : " + answer);
}
else{
System.out.println(constant + " is NOT a prime number.answer : " + answer);
}
}
System.out.println();
}
}
static double testPrime(long number, long divide)
{
double prime = 0.0;
prime = (double)number / divide;
if(dbg > 0){
System.out.println("Debug number " + number + " | divide " + divide + " |prime : " + prime + " | Math.abs(prime) " + Math.abs(prime));
}
if (prime == ((long)prime))//whats the best way to do this?
{
//divided evenly
return divide;
}
else{
return testPrime(number, divide - 2);
}
}
}
the recursive function for me goes like-Correct me if i am wrong.Thank you.calling statement >Boolean b=isPrime(number,number-1);
recursive function-
void isPrime(int p,int d);
{
int prime=p%d;
if((p==0&&d>1)||p%2==0)
return true;//that the number is not prime
if(d==1)
return false;
else
return isPrime(p,d-2);//calls the function again
}
Well I am directly giving you all the code instead of writing snippet. Hope you all may like this one as I have tried my best to make it as simple as possible.
The code is :>
import java.util.*;
class Prime_Number
{
static int c=0;
public static void main(String args[])
{
int n,i,sq=0;
Scanner in=new Scanner(System.in);
Prime_Number ob=new Prime_Number();
System.out.print("Enter a no.:>");
n=in.nextInt();
i=n;
sq=(int)(Math.sqrt(n));//square root is been taken since a no. cannot have factors greater than its square root
int k=ob.prime_Chk(n,i,sq);
if(k==1)
{
System.out.println("Prime");
}
else
{
System.out.println("Non-Prime");
}
}
public int prime_Chk(int g,int i,int sq)
{
if(i==sq)
{
return c;
}
else
{
if(g%i==0)
{
c++;
}
i--;
return(prime_Chk(g,i,sq));
}
}
}
Well in the prime() I have taken int i , int sq and int g as arguments.Instead of those if you wish then you can take other variables also.
import java.util.Scanner;
public class HW8R_T03 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.print("Enter number: ");
int n = sc.nextInt();
int simple = prime(n,n-1);
System.out.println(simple==1 ? "prime" : "not prime");
}
static int prime(int x, int y){
int div = 1;
if (y==0 || y==1){
return div;
}
if (x%y==0){
div = y;
} else {
div = prime (x, --y);
}
return div;
}
}