Using void parameters - java

There is something that I tried to fix over and over and I couldn't.
So the program asks a user for 3 numbers a then asks for the percentage they want to add then these numbers goes to a void method:
So its like this:
public static void main(String[] args) {
System.out.print("Number 1: ");
X1 = s.nextLong();
System.out.print("Number 2: ");
W1 = s.nextLong();
System.out.print("Number 3: ");
Z1 = s.nextLong();
System.out.print("Percentage 1: ");
int a = s.nextInt();
System.out.print("Percentage 2: ");
int b = s.nextInt();
System.out.print("Percentage 3: ");
int c = s.nextInt();
Number(a,b,c);
}
public static void Number(int a, int b, int c)
{
X1 = (long) (X1*(a/100 + 1));
W1 = (long) (W1*(b/100 + 1));
Z1 = (long) (Z1*(c/100 + 1));
}
But if I try to type the results the numbers don't change.
Note: X1,W1 and Z1 are all used as static long
And thanks in advance.

Unless a,b,c >= 100, the expression
a/100
will be 0. Hence
something * (a/100 +1)
is
something * 1

You are dividing the integer parameters by the integer 100 using--you guessed it--integer arithmetic which results in 0 for any value less than 100. Use 100.0 to force floating point precision.
X1 = (long) (X1*(a / 100.0 + 1.0));
...

Divide your number by 100.0 in the Number method.

Related

Separating numbers using %

I am trying to get 3 numbers separated by a space after user's input. I can get the first number and the last one dividing by 10, but I really have no idea how to get the middle number
I tried to take the remainder of the first two numbers and then divide them by ten, but IDEA says that the answer is always zero
public static void main(String[] args) {
System.out.println("Input the number");
int number = read.nextInt();
int a = number%10;
int b = (number%10)/10; // the answer is always 0
int c = number / 100;
System.out.println(c + " " + b + " " + a);
}
Anything modulo 10 will return a result in the range of 0 to 9, and (integer) dividing that by 10 will return 0. You need to reverse the order - first divide the 10 to remove the last digit, and then take the remainder from 10 to keep the middle digit:
int b = (number / 10) % 10;
I suggest using this instead of %. Because you can split and get any digit of number using this code:
int x=158;
char[] xValueInString = Integer.toString(x).toCharArray();
for(int i=0; i<xValueInString.length; i++){
System.out.println(xValueInString[i]);
}
You missed scanner in your code, add Scanner before reading number, try this with little change
public static void main(String[] args) {
System.out.println("Input the number");
Scanner read = new Scanner(System.in);
int number = read.nextInt();
int a = number%10;
int b = (number/10)%10; // the answer is always 0
int c = number/100;
System.out.println(c + " " + b + " " + a);
}

How to check a division as a int and float at the same time?

i have a question that goes with:
In Java, if we divide two integers, the result is another integer, but the result might not be correct. For example, 4/2 = 2, but 5/2 = 2.5 but in Java the result would be 2 when both 5 and 2 values are stored as integer values. The program should check if the numbers the result of the division is the same when the values are both integers and when they are floats.
So that I spend over 1 hour to figure this q but i have a problem with the ending part. What it meant in this part: "The program should check if the numbers the result of the division is the same when the values are both integers and when they are floats."
import java.util.Scanner;
class StartUp2{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Please type the first number that you want be devided: ");
int a = sc.nextInt();
float b = a;
System.out.println("Please type another number that you want to devide with:");
int c = sc.nextInt();
float d = c;
}
}
Do the division once with variables declared as int and once with float. Then compare the results.
int a = 42;
int b = 5;
float result = a/b;
float a = 42.0f;
float b = 5.0f;
float result = a/b;
Or as a self-contained function:
void compareDivision(final int a, final int b) {
float intResult = a/b;
float floatResult = (float)a/(float)b; // cast to float
if (intResult != floatResult) {
System.out.println("Results are different: " + intResult + " != " + floatResult);
}
}
Building on the code from your updated question:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please type the first number that you want be divided: ");
int a = sc.nextInt();
float b = a;
System.out.println("Please type another number that you want to divide with:");
int c = sc.nextInt();
float d = c;
float intResult = a/c;
float floatResult = b/d;
if (intResult != floatResult) {
System.out.println("Results are different: " + intResult + " != " + floatResult);
}
}
If you were to divide integers 5/2, then you would end up with 2.
Reverse the operation, multiply the result by the divisor, 2 * 2, and you end up with 4. Therefore your program should return false since it didn't equal the dividend, 5.

How to speed up the efficiency of my code?

Essentially I'm trying to create a program that counts up the sum of the digits of the number, but every time a number that is over 1000 pops up, the digits don't add up correctly. I can't use % or division or multiplication in this program which makes it really hard imo. Requirements are that if the user inputs any integer, n, then I will have to be able to compute the sum of that number.
I've already tried doing x>=1000, x>=10000, and so forth a multitude of times but I realized that there must be some sort of way to do it faster without having to do it manually.
import java.util.Scanner;
public class Bonus {
public static void main(String[] args) {
int x;
int y=0;
int u=0;
Scanner s = new Scanner(System.in);
System.out.print("Enter the number:");
x = s.nextInt();
int sum = 0;
{
while(x >= 100) {
x = x - 100;
y = y + 1;
}
while(x>=10) {
x = x - 10;
u = u + 1;
}
sum = y + u + x;
System.out.println("The sum of the digits in your number is" + " " + sum);
}
}
}
So if I type in 1,000 it displays 10. And if I type in 100,000 it displays 100. Any help is appreciated
Convert the number to a string, then iterate through each character in the string, adding its integer value to your sum.
int sum = 0;
x = s.nextInt();
for(char c : Integer.toString(x).toCharArray()) {
sum += Character.getNumericValue(c);
}

Conversion from Base 10 to Base 2

I am trying to convert a number in base 10 to a number in base 2, but I have a problem. When I run the code, I get the base 2 number in the wrong order. For example, I input 54 and get 110110 instead of 011011, the correct value.
import java.util.Scanner;
public class DecimalToBinary
{
public static void main(String arg[]){
int quotient;
int remainder;
Scanner keyboard = new Scanner (System.in);
System.out.println("Please enter a decimal number:");
quotient = keyboard.nextInt();
do {
remainder = quotient % 2;
quotient = quotient / 2;
// String x = String.valueOf(remainder);
// System.out.print(x);
System.out.print (remainder);
} while (quotient != 0);
}
}
Java has a built-in method to do this:
Integer.toString(int i, int radix);
where
i is your base ten number, and
radix is the base you want it in, in your case, 2.
It will return a string in binary.
Another inbuilt java function for this is
Integer.toBinaryString(int num)
where num is the base 10 number you want to convert
Base 10 to Base 2 should Reverse output,I think you can use array,then reverse output array
public static void main(String arg[]){
int quotient;
int remainder;
List<Integer> arrayList=new ArrayList<Integer>();
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter a decimal number:");
quotient = keyboard.nextInt();
do {
remainder = quotient % 2;
quotient = quotient / 2;
// String x = String.valueOf(remainder);
// System.out.print(x);
// System.out.print (remainder);
arrayList.add(remainder);
} while (quotient != 0);
ListIterator<Integer> li;
for (li = arrayList.listIterator(); li.hasNext();) {// 将游标定位到列表结尾
li.next();
}
for (; li.hasPrevious();) {// 逆序输出列表中的元素
System.out.print(li.previous() + " ");
}
}
try this solution, its simple:
int quotient;
int remainder;
Scanner keyboard = new Scanner (System.in);
System.out.println("Please enter a decimal number:");
quotient = keyboard.nextInt();
Stack<Integer> s=new Stack<Integer>();
do {
remainder = quotient % 2;
quotient = quotient / 2;
s.add(remainder);
// String x = String.valueOf(remainder);
// System.out.print(x);
//System.out.print (remainder);
} while (quotient != 0);
while(!s.isEmpty()){
System.out.print(s.pop());
}
I was able to fix your code
public class CustomDecimalToBinary {
public static void Dec2Bin() {
int quotient;
int remainder;
Scanner keyboard = new Scanner (System.in);
System.out.println("Please enter a decimal number:");
quotient = keyboard.nextInt();
do {
remainder = quotient % 2;
// String x = String.valueOf(remainder);
// System.out.print(x);
System.out.print (remainder);
} while ((quotient /= 2) != 0);
}
}
Example output:
Please enter a decimal number:
54
011011
EDIT: It appears I solved the problem to get your desired output but your code produces the correct output...

Write a program which reads two non-negative integers 'x' and 'y' (where x < y) and then prints three random integers in the range x...y

import java.util.Scanner;
import java.util.Random;
public class Lab04b
{
public static void main(String []args)
{
Random generator = new Random ();
Scanner scan = new Scanner(System.in);
int num1;
int num2;
int num3;
System.out.println("Enter X:");
num1 = scan.nextInt();
System.out.println("Enter Y:");
num2 = scan.nextInt();
num3 = generator.nextInt(num2) + num1;
System.out.println("3 random integers in the range " + num1 + ".." + num2 + " are: " + num3);
}
}
I am stuck on how to get 3 random integers between the x and y range. Y being the biggest integer.
The trick is finding the difference between x and y. Here is what you need to do -
int diff = Math.abs(num1 - num2);
num3 = generator.nextInt(diff) + Math.min(num1, num2);
Just do it 3 times and you get your 3 numbers.
From the docs
nextInt(int n)
Returns a pseudorandom, uniformly distributed int value between 0
(inclusive) and the specified value (exclusive), drawn from this
random number generator's sequence.
so random.nextInt(Y) would give you numbers 0..Y, I guess you are missing how to get the lower bound correctly.
X + random.nextInt(Y-X) does the trick.
Read the documentation. The nextInt(n) function returns an Integer in [0, n). So, in your case, you can use the formula min + nextInt(max-min), which will give you a number in [min, max).
Random generator = new Random();
int max = (x >= y ? x : y);
int min = (x < y ? x : y);
int aRandomNumber = min + generator.nextInt(max-min);
Firstly have a loop which will run 3 times, to generate 3 random numbers(as you said you need 3 random numbers, but you're just generating only 1).
Next, the pattern you've used to generate a random number seems to be flawed. You can use the below type 1 pattern to accomplish that.
min + Math.random() * ((max - min) + 1));
Or this type 2 pattern
rand.nextInt((max - min) + 1) + min;
So you can do something like this:-
for (int i = 0; i < 3; i++) {
// Type 1
num3 = num1 + (int)(Math.random() * ((num2 - num1) + 1));
// Type 2
// num3 = generator.nextInt((num2 - num1) + 1) + num1;
System.out.println("3 random integers in the range " + num1 + ".." + num2 + " are: " + num3);
}
P.S:- You need to first determine the max and min, yourself. I've just given the pattern and a sample.
import java.util.Scanner;
public class GenerateRandomX_Y_numbers {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the numbers x and y: ");
int x = Math.abs(sc.nextInt()), y = Math.abs(sc.nextInt());//we need //non-negative integers, that is why we use here Math.abs. which means the //absolute value
print3RandomNumbers_between_x_and_y(x, y);
}
public static void print3RandomNumbers_between_x_and_y(int x, int y) {//here //I create a method with void type that takes two int inputs
boolean isTrue = (x < y);//according to our conditions X should less //than Y
if (isTrue) {//if the condition is true do => generate three int in the //range x .... y
int rand1 = (int) (Math.random() * (y - x) + 1);// y - x means our //range, we then multiply this substraction by Math.random()
int rand2 = (int) (Math.random() * (y - x) + 1);//the productof this //multiplication we cast to int type that is why we have
int rand3 = (int) (Math.random() * (y - x) + 1);//(int) before //(Math.random() * (y - x));
System.out.println("rand1 = " + rand1);//
System.out.println("rand2 = " + rand2);//
System.out.println("rand3 = " + rand3);//here print our result
} else
System.out.println("Error input: X should be less than Y. Try it again!");//if the condition is not true, i mean if x is not less than or equal //to Y, print this message
}
}

Categories

Resources