not getting what's wrong with my code - java

public class DigitRange {
public static void main(String[] args) {
String numberstr = args[0];
int numberint = Integer.parseInt(args[0]);
int large=0;
int small=0;
System.out.println("range of " +numberint + " = "+ Range(numberstr,numberint,large,small));
}
public static int Range (String numberstr, int numberint,int large,int small){
for(int i=1;i<=numberstr.length();i++){
int digit = numberint % 10;
numberint = numberint/10;
large = Math.max(digit, large) ;
small = Math.min(digit, small);
}
int range = large - small + 1;
return range; //giving me 9
}
}
What is wrong with my code ? I am having a problem with returning the correct value from my method Range. I am returning the value 9 when i should be returning the value 6. I believe i have a logic error there.
NEW problem:
public class DigitRange {
public static void main(String[] args) {
String numberstr = args[0];
int numberint = Integer.parseInt(args[0]);
int max=0;
int min=9;
System.out.println("range of " + numberstr + " = "+ Range(numberstr,numberint,max,min));
}
//finds and returns the range
public static int Range (String numberstr, int numberint,int max,int min){
if(numberint<0){
Math.abs(numberint);
for(int i=1;i<=numberstr.length()-1;i++){
int digit = numberint % 10;
numberint = numberint/10;
max = Math.max(digit, max) ;
min = Math.min(digit, min);
}
}
if(numberint>0){
for(int i=1;i<=numberstr.length();i++){
int digit = numberint % 10;
numberint = numberint/10;
max = Math.max(digit, max) ;
min = Math.min(digit, min) ;
}
int range = max - min + 1;
return range;
}
}
}
How can i get the max and min out of the scope of if{} ?

You are looking for the smallest and largest digit in the number passed as argument to your code and the difference + 1 is your range, right?
Probably small should be initialized to 9.

Related

How to write a strong number function in Java

enter image description hereI am trying to solve this question:
a) Write a method with the following header that takes an integer n and
returns the value of n! (pronounced n factorial) computed as follows:
public static int factorial(int n)
Note that 0! = 1 and n! = n * (n-1) * (n-2)*.....*1.
Example: factorial(4) will return 24 which is = 4*3*2*1.
b) Write a method with the following header that takes an integer x and
returns true if x is a Strong number. Otherwise, it returns false.
public static boolean isStrongNumber(int x)
Note that the isStrongNumber method should call the factorial method to compute the factorial of
each digit in x.
public static int factorial(int n) {
int f =1;
for (int i = 1; i <=n; i++)
f=f*i;
return f;
}
public static boolean isStrongNumber(int x) {
int temp = x;
int z;
int q = 0;
int sum = 0;
while (temp > 0) {
x = x % 10;
z = factorial(x);
q += z;
if (q == temp) {
System.out.print(q + " ");
return true;
}
}
}
This is my answer, but I get an error every time I try to run it.
You did not return boolean value at end of the isStrongNumber method
public static int factorial(int n) {
int result = 1;
for (int i = 2; i <= n; i++) {
result *= i;
}
return result;
}
public static boolean isStrongNumber(int num) {
int originalNum = num;
int sum = 0;
while (num > 0) {
sum += factorial(num % 10);
num /= 10;
}
return sum == originalNum;
}
, main function
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int number = Integer.parseInt(scanner.nextLine());
Set<Integer> set = new TreeSet<>();
for (int i = 1; i <= number; i++) {
if (isStrongNumber(i)) {
set.add(i);
}
}
System.out.println("The Strong numbers between 1 and " + number + " are:");
System.out.println(set);
scanner.close();
}
, output for input 100000
Enter a positive integer: 100000
The Strong numbers between 1 and 100000 are:
[1, 2, 145, 40585]
This cannot compile as it lacks a return statement outside the while loop. In fact, you cant be sure to go inside the loop even once if x<=0 for exmaple. You should add return false outside the loop at the end of the method. Also if you get an error and write a question on StackOverflow, copy the error message it's very helpful.

can't find the solution

public class BinaryToDecimal{
public static void main(String[]args){
int binary = 101011101;
int d = 10;
int l = 1;
for (int j=1;j<=8;j++){
int r = (binary/d%10)*l;
int k = r;
int z = r + k;
d*=10;
l*=2;
}
System.out.println("The binary number " + binary + " is equivalent to "+ z +" in decimal."); // z here is out of scope of for
}
}
I need to finish this assignment using only the for loop, but I can't find a working code... This is the best i did.
Here is a pretty simple algorithm using the 2^x logic.
What it is basically doing is :
If we encounter 1 in the binary variable, we add 2^(Position of the 1) to the decimal variable
class MyClass{
public static void main(String[] args) {
int bin = 101;
String binary = String.valueOf(bin);
int decimal = 0;
for (int i = 0 ; i < binary.length() ; i++){
if (binary.charAt(i) == '1'){
decimal += Math.pow(2, binary.length() - i - 1);
}
}
System.out.println(decimal);
}
}
public class BinaryToDecimal{
public static void main(String[]args){
int binary = 101011101;
int powerOfTen = 10;
int powerOfTwo = 1;
int Decimal = 0;
for (int j=1;j<=8;j++){
int splitAnswer = (binary/powerOfTen%10)*powerOfTwo;
int old = splitAnswer;
Decimal = splitAnswer + old;
powerOfTen*=10;
powerOfTwo*=2;
}
System.out.println("The binary number " + binary + " is equivalent to "+ Decimal +" in decimal.");
}
}

I can't find max and min

I want to create program read more than 10 numbers from the user and find the maximum number and minimum number then print all the numbers from the user.
This is my program, but I don't know how can I find the maximum number and minimum number:
import java.io.*;
public class ass3 {
public static void main (String [] args) throws IOException
{
int times , num1 ;
int max , min;
System.out.print("How many numbers you want to enter?\n*moer than five number");
times=IOClass.getInt();
if (times>5) {
for(int i = 0;i<times;i++){
System.out.println("please type the "+i+ "number");
num1=IOClass.getInt();
}
}
}
}
If you initialize the min and max like this:
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
You can check whether the new number is smaller than min or bigger than max, and change them if needed:
int num = ...;
if (num < min) {
min = num;
}
if (num > max) {
max = num;
}
This is my solution, hope it helps:
import java.util.Scanner;
public class Test
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("How many numbers you want to enter?\nThe number must be grater than 5");
int times = in.nextInt();
if (times > 5)
{
int[] numbers = new int[times];
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for(int i = 0; i < times; i++)
{
System.out.println("Please type the " + i + " number:");
int number = in.nextInt();
numbers[i] = number;
if(number < min)
{
min = number;
}
if(number > max)
{
max = number;
}
}
System.out.println("Max: " + max);
System.out.println("Min: " + min);
}
in.close();
}
}

Arrays, check the smallest, largest, and the average in java

Im having some trouble on getting my methods to work, I believe I am doing something wrong in the main method to call the others. I am not sure if I need an if, while, or for statement. Can anyone help, I really appreciate it. Here is my program...
public static void main(String[] args) throws IOException {
Scanner kb = new Scanner(System.in);
final int MAX = 100;
int [] myarray = new int [MAX];
int fillsize, total = 0, num;
int smallest = 0, largest = 0;
fillsize = fillarray (myarray, MAX);
printarray (myarray, fillsize);
num = kb.nextInt();
int small = num;
int large = num;
total = Average(total, num);
if(smallest (num, smallest))
{
small = num;
}
if(largest(num, largest))
{
large = num;
}
System.out.println("The smallest value is: " + smallest);
System.out.println("The largest value is: " + largest);
System.out.println("The average is: " + total);
prw.close();
}
public static int fillarray (int[] num, int MYMAX){
Random gen = new Random();
int retval = 0;
int randomnum;
for(int count = 0; count <= 30; count++){
randomnum = gen.nextInt(150);
num [count] = randomnum;
System.out.println(randomnum);
retval++;
}
System.out.println("The return value is: " + retval);
return (retval);
}
public static void printarray (int[] num, int fillsize){
for (int counts = 0; counts < fillsize; counts++){
System.out.println("For the position ["+counts+"] the value is " + num[counts]);
}
return;
}
public static boolean smallest (int num1, int num2){
boolean returnValue;
if (num2 < num1){
returnValue = true;
}
else {
returnValue = false;
}
return (returnValue);
}
public static boolean largest (int number1, int number2){
boolean returnVal;
if (number1 > number2){
returnVal = true;
}
else{
returnVal = false;
}
return (returnVal);
}
public static int Average (int avg, int sum){
int retVal;
retVal = avg + sum;
return(retVal);
}
What am I doing wrong?
I suspect the problem is you set smallest and largest both to num which makes your if redundant.
Try setting them both to 0.
Also you have variables and methods with the same name which isn't recommended. (confusing).

Count of most occurring digit... Find the digit that occurs most in a given number

the following s the code to
Find the number of occurrences of a given digit in a number.wat shall i do in order to Find the digit that occurs most in a given number.(should i create array and save those values and then compare)
can anyone please help me ..
import java.util.*;
public class NumOccurenceDigit
{
public static void main(String[] args)
{
Scanner s= new Scanner(System.in);
System.out.println("Enter a Valid Digit.(contaioning only numerals)");
int number = s.nextInt();
String numberStr = Integer.toString(number);
int numLength = numberStr.length();
System.out.println("Enter numer to find its occurence");
int noToFindOccurance = s.nextInt();
String noToFindOccuranceStr = Integer.toString(noToFindOccurance);
char noToFindOccuranceChar=noToFindOccuranceStr.charAt(0);
int count = 0;
char firstChar = 0;
int i = numLength-1;
recFunNumOccurenceDigit(firstChar,count,i,noToFindOccuranceChar,numberStr);
}
static void recFunNumOccurenceDigit(char firstChar,int count,int i,char noToFindOccuranceChar,String numberStr)
{
if(i >= 0)
{
firstChar = numberStr.charAt(i);
if(firstChar == noToFindOccuranceChar)
//if(a.compareTo(noToFindOccuranceStr) == 0)
{
count++;
}
i--;
recFunNumOccurenceDigit(firstChar,count,i,noToFindOccuranceChar,numberStr);
}
else
{
System.out.println("The number of occurance of the "+noToFindOccuranceChar+" is :"+count);
System.exit(0);
}
}
}
/*
* Enter a Valid Digit.(contaioning only numerals)
456456
Enter numer to find its occurence
4
The number of occurance of the 4 is :2*/
O(n)
keep int digits[] = new int[10];
every time encounter with digit i increase value of digits[i]++
the return the max of digits array and its index. that's all.
Here is my Java code:
public static int countMaxOccurence(String s) {
int digits[] = new int[10];
for (int i = 0; i < s.length(); i++) {
int j = s.charAt(i) - 48;
digits[j]++;
}
int digit = 0;
int count = digits[0];
for (int i = 1; i < 10; i++) {
if (digits[i] > count) {
count = digits[i];
digit = i;
}
}
System.out.println("digit = " + digit + " count= " + count);
return digit;
}
and here are some tests
System.out.println(countMaxOccurence("12365444433212"));
System.out.println(countMaxOccurence("1111111"));
declare a count[] array
and change your find function to something like
//for (i = 1 to n)
{
count[numberStr.charAt(i)]++;
}
then find the largest item in count[]
public class Demo{
public static void main(String[] args) {
System.out.println("Result: " + maxOccurDigit(327277));
}
public static int maxOccurDigit(int n) {
int maxCount = 0;
int maxNumber = 0;
if (n < 0) {
n = n * (-1);
}
for (int i = 0; i <= 9; i++) {
int num = n;
int count = 0;
while (num > 0) {
if (num % 10 == i) {
count++;
}
num = num / 10;
}
if (count > maxCount) {
maxCount = count;
maxNumber = i;
} else if (count == maxCount) {
maxNumber = -1;
}
}
return maxNumber;
}}
The above code returns the digit that occur the most in a given number. If there is no such digit, it will return -1 (i.e.if there are 2 or more digits that occurs same number of times then -1 is returned. For e.g. if 323277 is passed then result is -1). Also if a number with single digit is passed then number itself is returned back. For e.g. if number 5 is passed then result is 5.

Categories