how can i find even and odd number between any number? - java

i was making a program as a training for my learning in java which can view even and odd numbers between any numbers that the user have entered , the problem that if i entered an even number at start it would show me the message
you haven't entered an even number
i just want him to view this message at first if the user have entered an odd number at start
public static void main(String[] args) {
isevennumber(1, 5);
}
public static void isevennumber(int startwith, int endwith) {
for (int i = startwith; i <= endwith; i++) {
if (i % 2 == 0) {
System.out.println("you have entered an even number which is " + i);
} else {
System.out.println("you haven't entered an even number");
}
}
}
the output is
you haven't entered an even number
you have entered an even number which is 2
you haven't entered an even number
you have entered an even number which is 4
you haven't entered an even number
sorry for any mistake , this is my first post here

The problem here is that every time in your loop that the number isn't odd it will print you haven't entered an even number.
You can try like this:
public static void main(String[] args) {
isevennumber(1, 5);
}
public static void isevennumber(int startwith, int endwith) {
List<Integer> evenNumbers = new ArrayList();
for (int i = startwith; i <= endwith; i++) {
if (i % 2 == 0) {
evenNumbers.add(i);
}
}
if (evenNumbers.isEmpty()) {
System.out.println("you haven't entered an even number");
return;
}
System.out.println("you have entered the following even numbers " + evenNumbers);
}
This will print out:
you have entered the following even numbers [2, 4]

Just add one more if to check whether this is first iteration or not:
public static void isevennumber(int startwith, int endwith) {
for (int i = startwith; i <= endwith; i++) {
if (i % 2 == 0)
System.out.println("you have entered an even number which is " + i);
else if (i == startwith)
System.out.println("you haven't entered an even number");
}
}

You are missing one step, problem here is that every time in your loop that the number isn't odd it will print you haven't entered an even number.
Below is the correct solution for you.
public static void isevennumber(int startwith, int endwith) {
for (int i = startwith; i <= endwith; i++)
{
if (i % 2 == 0)
{
System.out.println("you have entered an even number which is " + i);
}
else if (i == startwith)
{
System.out.println("you haven't entered an even number");
}
}
}

Related

I want to write a program that allows the user to guess a number between 0 and 100 in 7 attempts. I don't know why is this not working

public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int rnd = (int)(Math.random() * 101);
System.out.println("The program is going to give a number that is between 0 and 100 (including them). You can guess it by pressing Run.");
System.out.println("Enter your number:");
int num = scan.nextInt();
for (int count = 1; count <= 7; count++) {
while (num != rnd) {
if (num < rnd) {
System.out.println("Your guess is too low.");
}
if (num > rnd) {
System.out.println("Your guess is too high.");
}
if ((Math.abs(rnd - num) == 1) || (Math.abs(rnd - num) == 2)) {
System.out.println("But your guess is VERY close.");
}
num = scan.nextInt();
}
System.out.println("You got it right!");
}
System.out.println("You should guess it in 7 tries.");
}
}
So I used two loops and just nested them. Is that how it works for this? Right now the code is like starting with for loop and if that is true it goes to the while loop part where the guessing number takes place. Can this be fixed with just moving some codes and fixing minor areas around?
What you should do in a situation like this is do the code manually. Literally. Grab a piece of paper and pretend you're a computer. It's a good exercise, and it will help you figure out your problem.
The problem is your inner loop. It loops until they guess correctly regardless of the number of attempts. Then you force them to do it 6 more times with the outer loop.
You really only need 1 loop. I would have a single loop like this:
int attempts = 0;
int num = 0;
do {
num = scan.nextInt();
... most of the if code from your inner loop but not another scan.nextInt
} while (++attempts < 7 && num != rnd);
// and here you look at num == rnd to see if success or failures
I think you should rebuild you code to make it more clear.
Split the title (with description of the task)
Split main loop where you read user input and check it with expected number
Split output of the final result, where you print the result.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
final int rnd = new Random().nextInt(101);
final int maxAttempts = 7;
System.out.println("The program is going to give a number that is between 0 and 100 (including them).");
System.out.println("You can guess it within maximum " + maxAttempts + " attempts by pressing Run.");
boolean success = false;
for (int attempt = 1; attempt <= maxAttempts && !success; attempt++) {
System.out.format("(%s of %s) Enter your number: ", attempt, maxAttempts);
int num = scan.nextInt();
if (num == rnd)
success = true;
else {
System.out.print("Your guess is too " + (num > rnd ? "high" : "low") + '.');
System.out.println(Math.abs(rnd - num) <= 2 ? " But it's VERY close." : "");
}
}
System.out.println(success ? "You got it right!" : "Bad luck this time. Buy.");
}
import java.util.Scanner;
class Main {
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int rnd = (int) (Math.random() * 101);
System.out.println("The program is going to give a number that is between 0 and 100 (including them). You can guess it by pressing Run.");
System.out.println("Enter your number:");
int num = scan.nextInt();
for(int count = 1; count <= 7; count++)
{
if (num < rnd)
{
System.out.println("Your guess is too low.");
}
else if (num > rnd)
{
System.out.println("Your guess is too high.");
}
else if ((Math.abs(rnd - num) == 1) || (Math.abs(rnd - num) == 2))
{
System.out.println("But your guess is VERY close.");
}
else
System.out.println("You got it right!");
System.out.println("Enter Next number: ");
num = scan.nextInt();
}
}
}
It should work Fine.Basically Your reasoning wass wrong because You are putting a while loop inside a for loop. What you want to do is you want only 7 iteration.In those 7 iterations you are checking the conditions based on user Input.

How can I ask the user to re-enter their choice?

I know how to display an Error message if the user enters a number below 10 or higher than 999 but how can I code to make sure the program doesn't end after the users enter a number below 10 or higher than 999 and give them a second chance to enter their valid input over and over again until they give a correct input.
import java.util.Scanner;
public class Ex1{
public static void main(String args[]){
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter an integer between 10 and 999: ");
int number = input.nextInt();
int lastDigit = number % 10;
int remainingNumber = number / 10;
int secondLastDigit = remainingNumber % 10;
remainingNumber = remainingNumber / 10;
int thirdLastDigit = remainingNumber % 10;
int sum = lastDigit + secondLastDigit + thirdLastDigit;
if(number<10 || number>999){
System.out.println("Error!: ");
}else{
System.out.println("The sum of all digits in " +number + " is " + sum);
}
}
}
You will need to use a loop, which basically, well, loops around your code until a certain condition is met.
A simple way to do this is with a do/while loop. For the example below, I will use what's called an "infinite loop." That is, it will continue to loop forever unless something breaks it up.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int num;
// Start a loop that will continue until the user enters a number between 1 and 10
while (true) {
System.out.println("Please enter a number between 1 - 10:");
num = scanner.nextInt();
if (num < 1 || num > 10) {
System.out.println("Error: Number is not between 1 and 10!\n");
} else {
// Exit the while loop, since we have a valid number
break;
}
}
System.out.println("Number entered is " + num);
}
}
Another method, as suggested by MadProgrammer, is to use a do/while loop. For this example, I've also added some validation to ensure the user enters a valid integer, thus avoiding some Exceptions:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int num;
// Start the loop
do {
System.out.println("Please enter a number between 1 - 10:");
try {
// Attempt to capture the integer entered by the user. If the entry was not numeric, show
// an appropriate error message.
num = Integer.parseInt(scanner.nextLine());
} catch (NumberFormatException e) {
System.out.println("Error: Please enter only numeric characters!");
num = -1;
// Skip the rest of the loop and return to the beginning
continue;
}
// We have a valid integer input; let's make sure it's within the range we wanted.
if (num < 1 || num > 10) {
System.out.println("Error: Number is not between 1 and 10!\n");
}
// Keep repeating this code until the user enters a number between 1 and 10
} while (num < 1 || num > 10);
System.out.println("Number entered is " + num);
}
}
Try this, i just include the while loop in your code it will work fine.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int number = askInput(input);
while(number<10 || number>999) {
System.out.println("Sorry Try again !");
number = askInput(input);
}
int lastDigit = number % 10;
int remainingNumber = number / 10;
int secondLastDigit = remainingNumber % 10;
remainingNumber = remainingNumber / 10;
int thirdLastDigit = remainingNumber % 10;
int sum = lastDigit + secondLastDigit + thirdLastDigit;
if(number<10 || number>999){
System.out.println("Error!: ");
}else{
System.out.println("The sum of all digits in " +number + " is " + sum);
}
}
private static int askInput(Scanner input) {
int number = input.nextInt();
return number;
}

Letter guessing game Java

I have been working on a java guessing game for letters (a-z)! However i have created the game perfectly by using the number 1-26, but i cannot figure out how to convert each integer to a letter ie a = 1, b = 2,....z = 26!
I want the user to try and guess the letter and not the number, but i cannot workout how to do this!
(I know how to generate a random character but i cant implement and link it to each integer within the game correctly)
Random r = new Random();
char targetLetter = (char)(r.nextInt(26) + 'a');
Any help would be greatly appreciated! And i can display my code if it is needed
public class Stack {
public static void main(String[] args) {
Random rand = new Random(); //This is were the computer selects the Target
int guess;
int numGuesses = 0;
int Target;
String userName;
String playagain;
boolean play = true;
int session = 0;
int sessions = 0;
int bestScore = 0;
Scanner consoleIn = new Scanner(System.in);
Scanner name = new Scanner(System.in);
System.out.println("Hello! Please enter your name:\n"); //This is were the user enters his/her name
userName = name.nextLine();
System.out.println("Hello " + userName + " :) Welcome to the game!\n");
while (play = true) {
session++;
Target = rand.nextInt(26) + 1;
System.out.println("Guess a number between 1 and 26? You will have 5 attempts to guess the correct number"); //This is where the computer asks the user to guess the number and how many guesses they will have
do {
guess = consoleIn.nextInt();
numGuesses++;
if (guess > 26)
System.out.println("Error! Above MAXIMUM range");
else if (guess <= 0)
System.out.println("Error! Below MINIMUM range");
else if (guess > Target)
System.out.println("Sorry! Your guess was too high! :)"); //This is to help the player get to the answer
else if (guess < Target)
System.out.println("Sorry! Your guess was too low! :)"); //This is to help the player get to the answer
} while (guess != Target && numGuesses < 5);
if (guess == Target) {
System.out.println("Congratulations " + userName + ", it took you " + numGuesses + " attempts to guess correctly!"); //This tells the player that they got the correct answer and how many attempts it took
sessions++;
} else {
System.out.println("Sorry " + userName + ", You've used up all of your guesses! The correct answer was " + Target + "!"); //This tells the player that they failed to find the number and then tells them what the correct answer
}
{
Scanner answer = new Scanner(System.in);
System.out.println("Would you like another GO " + userName + "? [Y/N]");//This asks the player if they would like to play again
playagain = answer.nextLine();
if (playagain.equalsIgnoreCase("Y")) {//This is what happens if the player opts to play again
play = true;
numGuesses = 0;
} else if (playagain.equalsIgnoreCase("N")) {//This is what happens if the player opts to exit the game
play = false;
System.out.println("Thanks for playing " + userName + "! :) Please come back soon!");
System.out.println("You had " + session + " Goes");
System.out.println("The number of times you guessed correctly: " + sessions + "");
break;
}
}
}
}
}
use arrays of characters
char[] chars = ['A','B','C'...];
and use the random numbers to map to each character
char targetLetter = chars[r.nextInt(26)];
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
System.out.println("Guess the Letter");
String myLetter=scan.nextLine();
//get the letter of myLetter variable then convert to Uppercase
char enteredLetter=Character.toUpperCase(myLetter.charAt(0));
//26 only because the characters array starts with index 0
char[] characters ={'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
//I had created a parrallel array symbolizing int value of each letter
int[] range={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26};
//this variable convert user input to one of the array element of range
int userInputToInt=0;
//this variable is for knowing what int[] range array element must the value of userInputToInt fall
int userInputControlLoop=0;
char randomLetter=characters[(int)(Math.random()*26)];
// get the random input of computer convert it to int
int computerInputToInt=0;
//this loop is for getting the int value of randomLetter input by the computer
for(int i=0;i<characters.length;++i)
{
if(randomLetter==characters[i])
{
computerInputToInt=range[i];
}
}
//this loop is for getting the int value of user inputted letter
for(char i:characters)
{
if(enteredLetter==i)
{
userInputToInt=range[userInputControlLoop];
}
++userInputControlLoop;
}
//test the entered letter of user
if(enteredLetter==randomLetter)
{
System.out.println("Correct Guess");
System.out.println("The letter is:"+randomLetter);
}
//test the entered letter of user if greater than computer input
else if(userInputToInt>computerInputToInt)
{
System.out.println("Incorrect Guess");
System.out.println("The letter is too high");
System.out.println("The letter is:"+randomLetter);
}
//test the entered letter of user if lesser than computer input
else if(userInputToInt<computerInputToInt)
{
System.out.println("Incorrect Guess");
System.out.println("The letter is too low");
System.out.println("The letter is:"+randomLetter);
}
}
Use the same method that you do for your random characters. Assuming you have your guessed character as an int variable called "guess", and it has value 1-26 corresponding A-Z:
Random r = new Random();
char targetLetter = (char)(r.nextInt(26) + 'a');
...
int guess = ...
char guessChar = (char)guess + 'a';
if (guessChar == targetLetter) {
System.out.println("Correct!");
} else {
System.out.println("Guess again!")
}
You can implement it in this approach :
1- Create a String alphabet with the characters that you want.
2- declare the size of alphabet as n variable which will control the random generator range.
3- alphabet.charAt(random.nextInt(n)) is a random char from the alphabet.
program code will be :
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int n = alphabet.length();
Random r = new Random();
System.out.println(alphabet.charAt(r.nextInt(n)));
hope will help solve your problem.
public class Picnic1 {
// RULE 0: This code is provided as a working example.
// This rule tests for whether a word starts with the letter 'b' (allowed to the picnic).
public static boolean rule0(char[] array) {
if (array[0] == 'b') {
return true;
}
else {
return false;
}
// itemMessage:
// Return message about whether a particular item is allowed to the picnic.
public static String item ( double[] a){
// This code works, providing output like these examples:
// "banana: true"
// "collie: false"
// It needs to be replaced with a more suitable output.
// Instead it should return, for example:
// "Yes, you can bring a banana to the picnic."
// "No, you cannot bring a collie to the picnic."
if (a[0] == 'b') {
System.out.println("Yes, you can bring a" + 'a' + "to the picnic");
}
else if (a[0] != 'b') {
System.out.print("No, you can not bring a " + 'a' + "to the picnic");
}
}
}
}

Prime Factoring in Java - Intro Programming

Original: So for my intro to programming class, we have to find the prime factors of a range of numbers that the user inputs (i.e. 59-65). The issue with a lot of the solutions here is that they use things that we haven't discussed in class like arrays, continue, etc. It's a pretty basic class. As for the requirements, we have to use a primeFact method/function that we call in the first for loop. She instructed us to use a while and for loop in the method to get the prime factors but everytime I think I have something, it doesn't come out right. Any help is really appreciated and my code is below. I really only need help with the method portion with the algorithm for finding the factors.
Edit: Here is the final solution that I turned in. It works and will give all prime factors of all numbers in a given range of numbers.
import java.util.Scanner;
public class PrimeFact {
public static void main(String[] args) {
int start, stop;
//Get input
Scanner input = new Scanner(System.in);
System.out.println("Please enter then two values with the lower value first");
start = input.nextInt();
stop = input.nextInt();
input.close();
//Displays for the start of the loop
System.out.println("Starting value (at least two digits): "+start);
System.out.println("Ending value (at least two digits): "+stop);
System.out.println("Prime factors for numbers between "+start+" and "+stop);
//Loop for the prime factors
for (int num = start; num <= stop; num++) {
primeFact(num);
}
}
// Method for Prime Factoring
public static void primeFact(int num) {
int divisor = 2;
System.out.print(num+" = ");
while (num>1) {
if ((num%divisor) == 0) {
System.out.print(divisor+" x ");
num=num/divisor;
} else {
divisor++;
}
}
System.out.print("1");
System.out.println();
}
}
public static void primeFact(int num) {
System.out.print(num+" = ");
for(int i=2;i<num;i++)
{
if(num%i==0)
{
if(isPrime(i))
{
System.out.println("Prime Factor for "+num+" is:"+i);
}
}
}
if(num==2)
System.out.println("Prime Factor for "+num+" is:"+num);
}
static boolean isPrime(int num){
for(int i=2;i<num;i++)
{
if(num%i==0)
{
return false;
}
}
return true;
}
//if u want use while replace the for loop like
public static void primeFact(int num) {
System.out.print(num+" = ");
int i=2;
while(i<num)
{
if(num%i==0)
{
if(isPrime(i))
{
System.out.println("Prime Factor for "+num+" is:"+i);
}
}
i=i+1;
}
if(num==2)
System.out.println("Prime Factor for "+num+" is:"+num);
}
static boolean isPrime(int num){
int i=2;
while(i<num)
{
if(num%i==0)
{
return false;
}
i=i+1;
}
return true;
}
you're method is pretty close to a solution. but your while loop is invalid.
remember it should be like this:
while(<boolean statement>){
//code here
}
I will reference the variable we are checking "primality" for as "num"
here's how to check for factors with a while loop:
//remember, num is given to us in the parameters of primeFact(int num).
boolean isPrime = true; //we are optimistic.
//we start at 2 because everything is divisible by one
int posFact = 2; //short for "possible factor"
while(posFact < num){ //this will start at 2, and go to 1 less than num
if(num % posFact == 0){ // "%" gives us remainder
isPrime = false; // we now know it's not prime
System.out.println("The number " + posFact + " is a factor of " + num + ".");
}
posFact++; //increments posFact up by 1
}
if(isPrime){ //This will only be true if the number is prime
System.out.println("The number " + num + " is prime!");
}
We can do the exact same thing with a for loop:
//remember, num is given to us in the parameters.
boolean isPrime = true; //we are optimistic.
for(int posFact = 2; posFact < num; posFact++){ //posFact's initialization and incrementation was moved here.
if(num % posFact == 0){ // "%" gives us remainder
isPrime = false; // we now know it's not prime
System.out.println("The number " + posFact + " is a factor of " + num + ".");
}
}
if(isPrime){ //This will only be true if the number is prime
System.out.println("The number " + num + " is prime!");
}

Finding Error in Digit Counting Loop

We have as an exercise the task of finding errors in the following loop. The task of the loop is to output the number of digits of a number before the ".", i.e. "32782.12" would be equal to 5. Now so far, I really do not see any error. The only thing that is the case is that an input = 0 would not lead to a correct answer - do you have me any hint?
public class countingDigits {
public static void main(String[] args) {
double number = 88888888.99;
for(int digits=0; digits<6; ++digits) {
if (number*number < 1) {
System.out.println("The number has " + digits + " digits");
break;
}
number /= 10;
}
}
}
Is is not unusual to handle the special cases separately:
0
-0 (where applicable...)
maximum value of datatype (Double.MAX_VALUE)
minimum value of datatype (Double.MIN_VALUE)
etc.
So I'd handle 0 this way:
if(number==0.0 ) {
return 1;
}
public void countingDigits {
public static void main(String[] args){
double number = 88888888.99;
if (number == 0){
System.out.println("The number has 1 digits");
}else {
for(int digits=0; digits<20; ++digits) {
if (number < 1) {
System.out.println("The number has " + digits + " digits");
break;
}
number /= 10;
}
}
}

Categories