Finding Error in Digit Counting Loop - java

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;
}
}
}

Related

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;
}

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

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

required int found no argument reason actual and formal argument lists differ in length

import java.lang.Math;
import javax.swing.JOptionPane;
public class IntegerNumber
{
//declaring main variable used throughout the whole code
public static void main(String[] args)
{
//declare variable
int menuNumber;
String input = JOptionPane.showInputDialog("Select What You want to do: \n1: Calculate the total of the squares of the first inputted natural numbers. \n 2: Get the mean of the first N odd natural numbers. \n 3: Determine if the inputted number is a prime number. \n 4: Return a Fibonacci number. \n 5: Exit Program.");
menuNumber = Integer.parseInt(input);
if (menuNumber == 1)
{
TotalSquares();
}
else if (menuNumber == 2)
{
OddNumberMean();
}
else if (menuNumber == 3)
{
PrimeNumber();
}
else if (menuNumber == 4)
{
FibonacciNumber();
}
else if (menuNumber == 5)
{
System.exit(0);
}
}
public static double TotalSquares()
{
int N;
double total;
int k;
String input = JOptionPane.showInputDialog("Enter a number between 1 and 20 to find the total squared numbers of");
N = Integer.parseInt(input);
total = 0;
for(k=1; k<=N; k++);
total +=(k*k);
return total;
System.out.println("Your total is = " + total);
}
public static double OddNumberMean()
{
int N;
int i;
String input = JOptionPane.showInputDialog("Enter a number between 1 and 50 to find the mean of the odd numbers");
N = Integer.parseInt(input);
double total = 0;
for(i=0;i<=N; i++);
{ total+= 2*i +1;};
System.out.println("The mean is = " + (total/N));
}
public static double PrimeNumber()
{
int N;
int g;
String input = JOptionPane.showInputDialog("Enter a number between 2 and 200, determine whether or not the number is prime");
N = Integer.parseInt(input);
for (g = 2; g<N; g++)
{
if (N % g == 0)
{
System.out.println("The number is not prime");
}
}
System.out.println("The number is prime");
}
public static int FibonacciNumber(int N)
{
String input = JOptionPane.showInputDialog("Compute and return a Fibonacci number");
N = Integer.parseInt(input);
if (N==0)
return 0;
else if(N==1)
return 1;
else
return FibonacciNumber(N-1) + FibonacciNumber(N-2);
}
}
I keep getting this error:
IntegerNumber.java:33: error: method FibonacciNumber in class
IntegerNumber cannot be applied to given types;
FibonacciNumber();
^ required: int found: no arguments reason: actual and formal
argument lists differ in length
and I can not find a way to fix it. Any help appreciated as I can't seem to find the answer on other posts.
Replace
public static int FibonacciNumber(int N)
{
...
N = Integer.parseInt(input);
with
public static int FibonacciNumber()
{
...
int N = Integer.parseInt(input);
You called FibonacciNumber() without parameters, whereas the original method declaration wanted a parameter int N.
Furthermore for methods, fields and variables use an initial small letter: fibonacciNumber, n.

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

How to initiate Min/Max loops with scanner

In this problem, I need to ask the user to input the number of integers they will put in. Then, they will manually input each number. Finally, the program counts the sum and max of all even inputs.
I am having trouble with initiating the value. If I set them to zero, there would be an issue if all the numbers were negative even numbers.
import java.util.*;
public class Exercise07 {
public static void main(String[] args) {
Scanner thing = new Scanner(System.in);
evenSumMax(thing);
}
private static void evenSumMax(Scanner stuff) {
System.out.print("How many integers?");
int times = stuff.nextInt();
int evenSum = 0;
int evenMax = 0;
System.out.println("Number 1 : ");
int value = stuff.nextInt();
if (value % 2 == 0) {
evenSum += value;
evenMax = value;
}
for (int i = 2 ; i <= times; i++) {
System.out.print("Number " + i + " : ");
value = stuff.nextInt();
if (value % 2 == 0) { // if even
evenSum += value;
if (evenMax < value) {
evenMax = value;
}
}
}
System.out.println("Even sum = " + evenSum + ", even max = " + evenMax);
}
}
Set evenMax to the minimum possible number Integer.MIN_VALUE

Categories