Outputting more numbers than 8-bit in Binary Numbers - java

Trying to learn Java (free time) and stuck on why this is outputting more variables than I want. I would like for it to just print out 8-bit. I've tried putting in &255, but not doing anything to get rid of the trailing numbers.
Example:
The sum is:0000111110
Scanner sn = new Scanner(System.in);
int arr[] = new int[10];
int i,m,n,sum,carry=0;
System.out.print("Enter 8-bit signed binary number:");
int n1 = sn.nextInt();
System.out.print("Enter another binary number:");
int n2 = sn.nextInt();
for(i=arr.length-1;i>=0;i--){
m=n1%10;
n=n2%10;
n1=n1/10;
n2=n2/10;
sum=m+n+carry;
if(sum==1)
{
arr[i]=1;
carry=0;
}
else if(sum==2)
{
arr[i]=0;
carry=1;
}
else if(sum==3)
{
arr[i]=1;
carry=1;
}
else{
arr[i]=m+n+carry&255;
}
}
System.out.printf("The sum is:");
for(i=0;i<arr.length;i++) {
System.out.print(arr[i]);
}
System.out.println("");
}

The reason you get leading zeros, is because you are forcing the program to calculate 10 bits, and printing 10 bits (int arr[] = new int[10]). To avoid calculating/printing extra bits, you could change the condition of the for loop, and keep track of how many bits the sum has:
Scanner sn = new Scanner(System.in);
int arr[] = new int[10];
int m,n,sum,carry = 0, nBits = 0; //Declare nBits, number of bits the final sum has
System.out.print("Enter 8-bit signed binary number:");
int n1 = sn.nextInt();
System.out.print("Enter another binary number:");
int n2 = sn.nextInt();
for(int i = arr.length-1 ; (n1|n2|carry) != 0 ; i--, nBits++) {
m=n1%10;
n=n2%10;
n1=n1/10;
n2=n2/10;
sum=m+n+carry;
if(sum==1) {
arr[i]=1;
carry=0;
}
else if(sum==2) {
arr[i]=0;
carry=1;
}
else if(sum==3) {
arr[i]=1;
carry=1;
}
else {
arr[i]=m+n+carry&255;
}
}
System.out.printf("The sum is:");
for(int i = arr.length-nBits ; i < arr.length ; i++) {
System.out.print(arr[i]);
}
System.out.println();
}
The condition was changed to (n1|n2|carry) != 0, in other words, while any of the three variables is not equal to zero, iterating nBits at each cycle.

Related

Lucky number with User Input

I'm facing troubles solving the following question: I suppose to get the user to input a number and check if it is a lucky number. A lucky number is the sum of squares of even-positioned digit (starting from the second position) is a multiple of 7.
Following is the example of my codes, when i run the program it will stuck at user input, please advise how do i get it to run:
public class Tester {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Input a number: ");
int number = scanner.nextInt();
int count = 0;
while(number!=0) {
number/=10;
++count;
}
int[] array = new int[count];
int sum = 0;
for (int i=0; i<count; i++) {
array[i] = scanner.nextInt();
}
for (int i=0; i<count; i++) {
if(array[i]%2==0) {
sum+=(array[i]*array[i]);
}
else {
continue;
}
}
if (sum%7==0) {
System.out.println("The number: " +number+ "is a Lucky number");
}
else {
System.out.println("Oops! Not a Lucky number");
}
scanner.close();
}
}
I believe the culprit is the below loop:
for (int i=0; i<count; i++) {
array[i] = scanner.nextInt();
}
I think your intention was to get each of the digits into an array. However, you are getting an input from the scanner (which in this case is the user input) for count number of times.
While there are several ways of getting the number of digits and each digit into an array. I'm going to give you two ways. Also, I see no validations on the input integer (such as negative numbers, etc.) and I am going to ignore them right now.
Approach 1: Your for loop corrected
You just get the ith digit of the number using a formula.
for (int i=1; i<=count; i++) {
array[i] = (int) (number / Math.pow(10, count-i)) % 10;
}
Approach 2: Converting the numbers to String and back using streams
List<Integer> digits = Arrays.toStream(number.toString().split("")).map(
digitChar -> Integer.parseInt(digitChar)
).collect(Collectors.toList());
Note:
You need to import the classes java.util.Arrays and java.util.stream.Collectors
If you want even positioned digits,then you can directly get it in while loop.
while(number!=0) {
if(count%2 !=0){
int value = number %10; // even positioned values
// Do whatever you need to do with this value
}
number/=10;
++count;
}
If you want to convert the number into an digit array,then first find number of digits using log function and then store it array in reverse order.
int noOfDigits =(int) Math.floor(Math.log10(number)+1); // Finding No of digits
int[] array = new int[noOfDigits];
while(--noOfDigits>=0){
array[noOfDigits] = number/10; // storing every digits in reverse order
number%=10;
}
I don't know below code will be helpful for your core logic,yet I record this too.
If you want Sum of Squares of even positioned digits in number which is represented as array, then you can use below code.
int sum = 0;
for (int i=1; i<array.length; i+=2) {
sum += array[i] * array[i];
}
if (sum%7==0) {
// print number is lucky
}
else {
// print number is not lucky
}
If I understand your description correctly, here's a program that does what you want:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Input a number: ");
System.out.flush();
int number = scanner.nextInt();
int count = 0;
int n = number;
int sum = 0;
while(n!=0) {
int d = n % 10;
n/=10;
++count;
if (count % 2 == 0) {
System.out.printf("sum = %d + %d^2 = %d\n", sum, d, sum + d * d);
sum += d * d;
}
}
if (sum%7==0) {
System.out.printf("The number: %d is a Lucky number (%d = 7 * %d)", number, sum, sum / 7);
}
else {
System.out.println("Oops! Not a Lucky number");
}
scanner.close();
}
A lucky result:
Input a number: 123456
sum = 0 + 5^2 = 25
sum = 25 + 3^2 = 34
sum = 34 + 1^2 = 35
The number: 123456 is a Lucky number (35 = 7 * 5)

how swap between two array values?

When user enter number 1 smaller than number 2 swap does not work,
but when number 1 is larger than number 2 it works. I don't understand why this is occurring. I would appreciate some suggestions or help.
package javaapplication36;
public class JavaApplication36 {
static Scanner s = new Scanner(System.in);
// main method
public static void main(String[] args) {
int[] arr = new int[10];
input(arr);
System.out.println("Enter n1 :");
int n1 = s.nextInt();
System.out.println("Enter n2 : ");
int n2 = s.nextInt();
display(arr);
int temp = 0;
int index_a = index(arr, n1);
int index_b = index(arr, n2);
if (index(arr, n1) != -1 && index(arr, n2) != -1) {
temp = arr[index_a];
arr[index_a] = arr[index_b];
arr[index_b] = temp;
}
for (int i : arr) {
System.out.print(i + " ");
}
System.out.println();
}
public static void display(int[] arr) {
for (int i : arr) {
System.out.print(i + " ");
}
System.out.println();
}
public static void input(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.println("Enter number : " + (i + 1));
arr[i] = s.nextInt();
}
}
public static int index(int[] arr, int n) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == n)
return i;
}
return -1;
}
}
I tried this and could not find anything wrong. To make debugging this easier I recommend you populate your array using random numbers.
Create an instance of Random
Random rand = new Random();
And assign the output to your array variable.
arr = rand.ints(10,1,15).toArray();
The arguments to rand.ints are.
10 - the number of elements
1 - the start of the range of numbers
15 - the end of the range (not including that number)
So that call would generate 10 numbers from 1 to 14 inclusive.
One possibility for any problems could be duplicate numbers in your array and finding the correct one to swap. But I was unable to reproduce the error.

How do I check if the values that I enter in an array are squared as the array continues?

This is my first time using this and I'm having a bit of trouble with arrays. I need to check if the values in an array that the user enters are continuously being squared such as {2, 4, 16, 256}. Checking if num[1] = num[0] * num[0], num[2] = num[1] * num[1] and so on. Any help would be appreciated.
import java.util.Scanner;
public class PS6Square {
public static void main (String [] args){
Scanner scan = new Scanner(System.in);
System.out.println("How many values would you like to enter?");
String input = scan.next();
int array = Integer.parseInt(input);
int num[] = new int[array];
int i = 0;
boolean result = false;
for(i = 0; i < num.length; i++)
{
System.out.print("Enter a value:\t");
num[i] = scan.nextInt();
if(num[i] == num[i] * num[i])
{
result = true;
}
}
System.out.println("\nThe result is:\t" + result);
}
}
This question has already been asked. Try the search function next time.
But here is a solution:
double sqrt = Math.sqrt(int_to_test);
int x = (int) sqrt;
if(Math.pow(sqrt,2) == Math.pow(x,2)){
//it is a perfect square
}

Finding the minimum of all numbers that are positive in java

I'm having trouble to ignore the negative numbers in finding the minimum of given numbers. here is my code to print the minimum number taking 10 inputs from the user in java. (I'm a fresher student and new in java. if you find any mistake then please help me to figure it out)
Scanner k = new Scanner (System.in);
int x, y, min;
System.out.println ("enter a number");
x = k.nextInt();
min = x;
for (int count=1; count < 10; count++) {
System.out.println ("enter a number");
y = k.nextInt;
if (y < min) {
min = y;
}
}
System.out.println (min);
That was my code to find the minimum number. But I want to find the minimum of all positive numbers. if the user enters negative number then I want to ignore that number.
Help me to make the code of finding the minimum number ignoring negative numbers.
if(y<min&&y>=0)
Is that what you mean?
private static Scanner k = new Scanner (System.in);
public static void main(String[] args) {
int min=getNumber(false);
for (int count=1; count<10; count++) {
int y=getNumber(true);
if(y<min&&y>=0)
min=y;
}
System.out.println(min);
}
private static int getNumber(boolean allowNegative) {
System.out.println("Please enter an integer:");
int n=0;
try {
n=Integer.parseInt(k.nextLine());
} catch(NumberFormatException nfe) {
System.err.println("Input must be an integer...");
return getNumber(allowNegative);
}
if(allowNegative) {
return n;
} else {
if(n<0) {
System.out.println("You cannot start with a negative number...");
return getNumber(allowNegative);
} else {
return n;
}
}
}
Check not only if the next number is smaller than your current minimum, but also if it is greater than (or equal) 0:
if (y<min && y >= 0){
instead of
if (y<min){
You also have to make sure the first number is not negative.
It's better if you store your all input number in an int array. If I assume the array containing all number is - array[] then look the code -
public class FindMinimumExceptNegative{
public static void main(String[] args){
int[] array = {-100, -4, 33, 45, 67, 2, -4, 56, 87, 234, 98, 24, 98, 56, 87, -10};
System.out.println("Minimum :" +findMinimumExceptNegative(array));
}
public static int findMinimumExceptNegative(int[] a){
int minimum = 0;
for(int i=0; i<a.length; i++){
if(a[i]>=0){
minimum = a[i];
break;
}
}
for(int i=1; i<a.length; i++){
if(minimum > a[i] && a[i]>=0){
minimum = a[i];
}
}
return minimum;
}
}
Scanner k=new Scanner (System.in);
int x,y,min;
min=0;
for (int count=1;count<=10;count++){
System.out.println ("enter a number");
y=k.nextInt;
if (y<min && y>=0){
min=y;
}
}
System.out.println (min);
Made a few changes. This
1) Ensures only 10 inputs are taken
2) The value of min defaults to 0 if only negative numbers are entered. In your earlier code, if the first number was negative, min would still be set.

How to swap the position of the numbers

I'm new to Java programming and I want to know how to swap the position of the highest number and the lowest number.
import java.util.*;
public class HighestandLowestNum
{
static Scanner data = new Scanner (System.in);
public static void main(String[]args)
{
int num [] = new int [10];
int i;
System.out.println("Enter 10 numbers: ");
for (i = 0; i < num.length; i++)
{
num [i] = data.nextInt();
Highest(num);
Lowest(num);
}
System.out.println("The highest number is: " + Highest(num));
System.out.println("The lowest number is: " + Lowest(num));
}
public static int Highest(int[] num)
{
int highest = num[0];
int i;
for (i = 1; i < num.length; i++)
{
if (num[i] > highest)
{
highest = num[i];
}
}
return highest;
}
public static int Lowest(int[] num)
{
int lowest = num[0];
int i;
for (i = 1; i < num.length; i++)
{
if (num[i] < lowest)
{
lowest = num[i];
}
}
return lowest;
}
}
This is my program. Please help me to fix my problem.
Your two functions Highest and Lowest return the value of the highest and lowest numbers. In order to swap them, you need to know the positions those values have within the array.
If you alter those functions or create new ones to return the index of the highest and lowest values, then you can swap them with what you've probably already seen before:
pseudocode:
temp = first
first = last
last = temp
To Swap the two numbers in the array, you need to know the numbers and their position as mentioned in the earlier answers. You can modify the two functions in such a way that they provide Numbers as well as their Position. One way to do this is to return an array instead of integer from the function. And in that array, information about the number and its position can be encapsulated. Ill show you what I mean in the code I am providing:
static Scanner data = new Scanner (System.in);
public static void main(String[]args)
{
int num []= new int [10];
int i;
System.out.println("Enter 10 numbers: ");
for (i = 0; i <num.length; i++)
{
num [i] = data.nextInt();
Highest(num);
Lowest(num);
}
System.out.print("The original array is");
for (i = 0; i <num.length; i++)
{
System.out.print(" "+num[i]);
}
System.out.println("");
int highest = Highest(num)[0];
int lowest = Lowest(num)[0];
int highestPosition = Highest(num)[1];
int lowestPosition = Lowest(num)[1];
System.out.println("The highest number is: " +highest+" at position "+highestPosition);
System.out.println("The lowest number is: " +lowest+" at position "+lowestPosition);
//Swap//
num[highestPosition] = lowest;
num[lowestPosition] = highest;
System.out.print("The new array is");
for (i = 0; i <num.length; i++)
{
System.out.print(" "+num[i]);
}
}
public static int[] Highest(int[] num)
{
int highest = num[0];
int i;
int index = 0;
int[] result = {highest,index};
for (i = 1; i <num.length;i++)
{
if (num[i] > highest)
{
highest = num[i];
index = i;
result[0] = highest;
result[1] = index;
}
}
return result;
}
public static int[] Lowest(int[] num)
{
int lowest = num[0];
int i;
int index = 0;
int[] result = {lowest,index};
for (i = 1; i <num.length;i++)
{
if (num[i] < lowest)
{
lowest = num[i];
index = i;
result[0] = lowest;
result[1] = index;
}
}
return result;
}
Try reading the modification in the Highest and Lowest functions and than go through the main code. Hope this helps.

Categories

Resources