How do I manipulate an integer variable through two different while loops? - java

I am having trouble writing code that will execute through the one loop while it is odd and through another loop if it is even. Here is my code so far:
public class Sequence {
public static void main(String args[]) {
System.out.println("Please Enter an positive integer no more than 100: ");
Scanner input = new Scanner(System.in);
int initial = input.nextInt();
if (initial >= 100 || initial <= 0) {
System.out.println("The input is invalid");
}
if (initial % 2 == 0) {
while (initial % 2 == 0) {
System.out.print("[" + initial + "] ");
initial = initial / 2;
}
}
if (initial % 2 == 1) {
while (initial % 2 == 1) {
System.out.print("(" + initial + ") ");
initial = 6 * initial + 2;
}
}
}
}

Hope this code will help your need
private static int handleOddNo(int oddNo){
int initial = oddNo;
while (initial % 2 == 1) {
System.out.print("(" + initial + ") ");
initial = 6 * initial + 2;
if(initial == 1)
break;
}
return initial;
}
private static int handleEvenNo(int evenNo){
int initial = evenNo;
while (initial % 2 == 0) {
System.out.print("[" + initial + "] ");
initial = initial / 2;
if(initial == 1)
break;
}
return initial;
}
public static void main(String args[]) {
System.out.println("Welcome to The Sequence Generator");
System.out.println("---------------------------------");
System.out.println("Please Enter an positive integer no more than 100: ");
Scanner input = new Scanner(System.in);
int initial = input.nextInt();
if (initial >= 100 || initial <= 0) {
System.out.println("The input is invalid");
}
do{
if (initial % 2 == 0) {
initial = handleEvenNo(initial);
}else{
initial = handleOddNo(initial);
}
}while(initial != 1);
}

The problem can be illustrated with 5 as an input. Since this is odd, you completely skip the even case and then continue to calculate 6 * 5 + 2 which is 32. I assume that you now want to treat return to the even case and continue calculating. Note that this implies that you need a loop. In other words, you should put an if statement inside a while loop. Your current logic is the exact reverse of this.

Related

Java: How to get back to the main method after using other methods

I'm fairly new to Java and the problem I am having is that this code compiles, but does not run after the hexadecimal conversion; it instead just ends after the method hexCharToDecimal. I can't reuse method main and I'm not sure how to call the method intreverse and actually have it run. Is there a way to get back into main or do I have to call intreverse somewhere?
import java.util.Scanner;
public class Homework4 {
public static void main(String[]args) {
// Sum and average of a set of intergers entered by the user
// First we will declare some variables
int userInput = 1;
int positives = 0;
int negatives = 0;
int sum = 0;
int numCount = 0;
Scanner input = new Scanner(System.in);
// Will start a while loop that will stop when user enters 20 integers
while ((numCount <= 20)) {
System.out.println("Please enter a nonzero integer or enter 0 to finish ");
userInput = input.nextInt();
if (userInput == 0) {
break;
} else if (userInput > 0) {
positives += 1;
numCount += 1;
sum = sum + userInput;
} else if (userInput < 0) {
negatives += 1;
numCount += 1;
sum = sum + userInput;
} else
System.out.println("Error, please enter an integer");
continue;
}
double average = (sum / numCount);
System.out.println("The sum of the entered integers is " + sum);
System.out.println("The average of the enetered integers is " + average);
System.out.println("There are " + positives + " positive integers and " + negatives + " negative integers");
// Convert Hexadecimal number to decimal
// Ask the user to input a string of 5 digits or less in hex
System.out.println("Please enter a hexadecimal number of up to 5 characters");
String hex = input.next();
if (hex.length() <= 5) {
System.out.println(hex + " in decimal value is equal to " + hexToDecimal(hex.toUpperCase()));
} else {
System.out.println("Error: please enter a hex number of 5 digits or less");
}
}
// Now we will create the method to convert to decimal
public static int hexToDecimal(String hex) {
int decimal = 0;
for (int i = 0; i < hex.length(); i++) {
char hexcharacter = hex.charAt(i);
decimal = decimal * 16 + hexCharToDecimal(hexcharacter);
}
return decimal;
}
public static int hexCharToDecimal(char ch) {
if (ch >= 'A' && ch <= 'F') // check to see if there is any letters in the string
return 10 + ch - 'A';
else
return ch - '0';
}
// Print entered integer in reverse
public static void intreverse(String[]args) {
// Ask user for an integer to be reversed
Scanner input = new Scanner(System.in);
System.out.println("Please enter an integer to be reversed");
int number = input.nextInt();
reverse(number); // Method to be called
}
// Will now state our method
public static void reverse(int number) {
// use a while loop to get each digit
while (number > 0) {
System.out.print(number % 10);
number = number / 10;
}
}
}
if (hex.length() <= 5) {
System.out.println(hex + " in decimal value is equal to " + hexToDecimal(hex.toUpperCase()));
} else {
System.out.println("Error: please enter a hex number of 5 digits or less");
}
Will always run once because it is not enclosed in any sort of loop. If you want it to run again when the second case is called then enclose it in a while(true) loop and have a break statement in the first case where you want it to stop execution.

I am trying to make a program which accepts two numbers and finds the prime, even and odd numbers in between

I am trying to make a program which will accept a starting number and ending number (int) and find the prime, even and odd numbers in between. I am not able to set my if and else conditions properly. It would be great if someone could even tell me a simpler method.
package proj2;
import java.util.Scanner;
public class Proj2
{
public void number(int sn,int en)
{
if (sn <= en)
{
int number = 2;
if (sn > number && sn % number != 0)
{
System.out.println(sn + " : " + "Prime");
number++;
sn++;
number(sn++,en);
}
else if (sn % 2 == 0)
{
System.out.println(sn + " : " + "Even");
sn++;
number(sn++,en);
}
else
{
System.out.println(sn + " : " + "Odd");
sn++;
number(sn,en);
}
}
}
public static void main(String [] abc)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the starting number:");
int x = sc.nextInt();
System.out.println("Enter the ending number:");
int y = sc.nextInt();
Proj2 p = new Proj2();
p.number(x,y);
}
}
Being prime and odd are not mutually exclusive, your primality test is incorrect, and you are recursively calling number(). Instead use:
private boolean isPrime(int num){
// assuming positive ints
if( num <= 2 || num % 2 == 0)
return false;
for(int divisor = 3; divisor <= (int)Math.pow(num, 0.5); divisor+=2)
if( num % divisor == 0)
return false;
return true
}
public void number(int start, int end){
if( start <= end ){
for( int curr = start; curr <= end; curr++ ){
if( curr % 2 == 1 ) {
System.out.println(curr + " : Odd");
if(isPrime(curr))
System.out.println(curr + " : Prime");
} else System.out.println(curr + " : Even");
}
}

Java factorial format

My factorial method is working correctly although I would like to change the output from just outputting the number and the factorial result. For example I would like if the user enters 6 for the output to say 6 * 5 * 4 * 3 * 2 * 1 = 720, instead of factorial of 6 is: 720.
int count, number;//declared count as loop and number as user input
int fact = 1;//declared as 1
Scanner reader = new Scanner(System.in); // Reading from System.in
System.out.println("Please enter a number above 0:");
number = reader.nextInt(); // Scans the next token of the input as an int
System.out.println(number);//prints number the user input
if (number > 0) {
for (i = 1; i <= number; i++) {//loop
fact = fact * i;
}
System.out.println("Factorial of " + number + " is: " + fact);
}
else
{
System.out.println("Enter a number greater than 0");
}
}
create a string and store the numbers.
try something like this.
int count, number;//declared count as loop and number as user input
String s; //create a string
Scanner reader = new Scanner(System.in); // Reading from System.in
System.out.println("Please enter a number above 0:");
number = reader.nextInt(); // Scans the next token of the input as an int
int fact = number;//store the number retrieved
System.out.println(number);//prints number the user input
if (number > 0) {
s=String.valueOf(number);
for (int i = 1; i < number; i++) {//loop
fact = fact * i;
s = s +" * "+String.valueOf(number-i);
}
System.out.println(s+ " = " + fact);
}
else
{
System.out.println("Enter a number greater than 0");
}
Check out this recursive approach: (check negative numbers yourself :D)
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt();
System.out.println(getFactorialString(num, " = " + getFactorial(num)));
}
public static String getFactorialString(int num, String result) {
if (num == 0) return "0 => 1";
if (num == 1) {
result = "" + num + "" + result;
} else {
result = getFactorialString(num - 1, result);
result = "" + num + " x " + result;
}
return result;
}
public static int getFactorial(int num) {
if (num == 0) return 1;
return num * getFactorial(num - 1);
}

How can I finish writing this program using a while loop?

I'm having trouble finishing this program. I understand what the program is suppose to do, but I'm having trouble finishing it. I have my code posted below.
For this program I am required to determine if a number is a prime number. A part from this, I'm required to ask the user to enter a range (ex. 1-10) and display which numbers are prime and which are not.
This is what I have so far...
import java.util.Scanner;
public class PrimeNumbers
{
public static void main(String[]args)
{
//Create Scanner Object
Scanner input = new Scanner(System.in);
//Initialize variable
double num1, range;
//Prompt the user to enter in a number
do
{
System.out.println("Please enter in a number:");
num1 = input.nextDouble();
//Decision making
if(num1 % 2 == 0 || num1 % 3 == 0 || num1 % 4 == 0 || num1 % 5 == 0 || num1 % 6 == 0 || num1 % 7 ==0 || num1 % 8 ==0 || num1 % 9 == 0)
{
//Display message
System.out.println(num1 + " is not a prime number.");
System.out.println("Please enter a range: ");
range = input.nextInt();
if ()
}
else
//Display output
System.out.println(num1 + " is prime.");
}
while(num1 == -1);
{
System.out.println("This program has now ended.");
}
}
}
http://beginnersbook.com/2014/01/java-program-to-display-prime-numbers/
import java.util.Scanner;
class PrimeNumbers2
{
public static void main (String[] args)
{
Scanner scanner = new Scanner(System.in);
int i =0;
int num =0;
//Empty String
String primeNumbers = "";
System.out.println("Enter the value of n:");
int n = scanner.nextInt();
for (i = 1; i <= n; i++)
{
int counter=0;
for(num =i; num>=1; num--)
{
if(i%num==0)
{
counter = counter + 1;
}
}
if (counter ==2)
{
//Appended the Prime number to the String
primeNumbers = primeNumbers + i + " ";
}
}
System.out.println("Prime numbers from 1 to n are :");
System.out.println(primeNumbers);
}
}

How can I count the number of odd, evens, and zeros in a multiple digit number in Java?

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.");
}
}

Categories

Resources