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.
Related
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)
the program always outputs "Invalid". I've checked my code multiple times but cant find the error. I'm a beginner at java, your help will be appreciated.
I've looked for all possible errors and different codes of this questions but it still doesnt work
package cs50;
import java.util.*;
public class Credit {
int arr[];
static long credit_card;
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
System.out.println("Enter credit card number : ");
credit_card = sc.nextLong();
Credit obj = new Credit();
int count = (int)obj.countDigits();
obj.digitsToArray(count);
int sum = obj.sum(count);
obj.check(sum,count);
}
//count number of digits
long countDigits()
{
long n = credit_card;
int count = 0;
while(n>0)
{
n=n/10;
count++;
}
return count;
}
//store digits in an array
void digitsToArray(int count)
{
long m = credit_card;
arr = new int[count];
for (int i=count-1; i>=0; i--)
{
arr[i] = (int)m % 10;
m = m / 10;
}
}
//Calculate sum of digits
int sum(int count)
{
int sum = 0;
for (int i=count-2; i>=0; i=i-2)
{
int n = arr[i]*2;
if(n>9)
{
sum = sum + n%10 + (n/10 % 10);
}
else
sum = sum + n;
}
for (int i=count-1; i>=0; i=i-2)
{
int n = arr[i];
sum = sum + n;
}
return sum;
}
//Check credit card type
void check(int sum, int count)
{
if (sum%10 == 0)
{
if(count==15 && (arr[0]==3 && (arr[1]==4||arr[1]==7)))
{
System.out.println("AMEX");
}
else if(count==16)
{
if(arr[0]==5 && (arr[1]==1||arr[1]==2||arr[1]==3||arr[1]==4||arr[1]==5))
{
System.out.println("MasterCard");
}
else if(arr[0]==4)
{
System.out.println("Visa");
}
}
else if(count==13 && arr[0]==4)
{
System.out.println("Visa");
}
}
else
System.out.println("Invalid");
}
}
visa or mastercard number doesnt show expected outputs, always shows "Invalid".
In line with lexicore's suggestion, stepping through your code, your digitsToArray() method will need to be looked at in detail.
Providing the credit card number: 5105 1051 0510 5100
the digitsToArray() method sets the arr variable to: [5, 1, 0, 5, 1, 0, 5, 1, 0, 9, -1, -4, -9, 5, 8, 0] which doesn't seem right.
Check out the link that lexicore provided, it'll take you through why and how to use it.
So I'm trying to divide a number by 2 repeatedly until the sum hits 0.
For example, dividing 40 by two, it will be like this 20, 10, 5, 2, 1, 0, and it will print 6, because it divided 6 times.
The code I came up with is
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter A Number:");
try {
int i = sc.nextInt();
int j = i;
int k = j/2; //sum
while (k == 0) {
System.out.println(k);
k++;
}
}
finally {
System.out.println("done");
}
}
}
I know it's very wrong, but if someone can point me into the right direction, it would be greatly appreciated!
Maybe I missed something but the solution seems quite trivial:
int i = sc.nextInt();
int count = 0;
while (i > 0)
{
i /= 2;
count++;
}
I'm not sure what "until the sum hits 0" means.
This is not kinda "algorithmic" solution but you may achieve what you need using the following approach:
public static void main(String[] args) {
System.out.println("Enter A Number:");
Scanner sc = new Scanner(System.in);
System.out.println(Integer.SIZE-Integer.numberOfLeadingZeros(sc.nextInt()));
}
I've just recently started programming Java and I'm having a problem that's making me want to break things. It starting to get annoying, and I'm feeling pretty stupid right now.
The task is to write a program that asks for five numbers to be input into an array (yes, can't use a list) and to then calculate the average of the five numbers input.
Where am I going wrong?
My current code calculates the average after each input. I want to do that after they've all been inserted, otherwise what is the point?
All help is greatly appreciated, you believe me!
Here's the code:
import java.util.Scanner;
public class Uppg3 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] numbers = new int[5];
int sum = 0;
for (int i = 0; i < numbers.length; i++)
{
System.out.println("enter a number: ");
numbers[i] = input.nextInt();
sum = numbers[i];
}
double average = sum / 5;
System.out.println("Average is " + average);
input.close();
}
}
You ought to encapsulate such a thing in a method.
You can either process all the numbers at once by storing them in an array and passing them at the same time or keep a running tally and return it on request.
public class StatisticsUtils {
private double sum;
private int numValues;
public StatisticsUtils() {
this.sum = 0.0;
this.numValues = 0;
}
public void addValue(double value) {
this.sum += value;
++this.numValues;
}
public double getAverage() {
double average = 0.0;
if (this.numValues > 0) {
average = this.sum/this.numValues;
}
return average;
}
public static double getAverage(double [] values) {
double average = 0.0;
if ((values != null) && (values.length > 0)) {
for (double value : values) {
average += value;
}
average /= values.length;
}
return average;
}
}
Looking at this for loop
for (int i = 0; i < numbers.length; i++)
{
System.out.println("enter a number: ");
numbers[i] = input.nextInt();
sum = numbers[i];
}
You are adding it to the array just fine, but you keep setting the sum to whatever they enter. For example, if I enter 5 3 2, the array will have 5 3 2 in it, but the sum will be set to 2. If I only entered 5 3, it would be set to 3.
One solution would be to use +=, that way it adds that number to whatever the current value is (which you start at 0). It's also important to note that when you divide two integers (sum and 5), it will not give you a decimal. This can be solved by using 5.0 or casting sum to a double.
Your code is currently just assigning a different value to sum on every iteration of the loop. You need to change sum = numbers[i]; to sum += numbers[i]; (equivalent to sum = sum + numbers[i];). You'll also want to change int sum = 0; to double sum = 0 so that your answer has decimals.
Ok, it works with the "+=", love you Chris Phelps. That and changing:
int sum = 0;
to
double sum = 0;
To make the answer have a decimal. Thanks a lot you guys! A weight has been lifted of my chest :).
Code for calculating average of array input
package com.imedxs;
import java.util.Scanner;
public class Test {
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("for calculating average of array");
int n=0;
int b=sc.nextInt();
int[] numbers = new int[b];
int sum = 0;
for (int i = 0; i < b; i++)
{
System.out.println("enter a number: ");
numbers[i] = sc.nextInt();
sum += numbers[i];
n++;
}
double average = sum / n;
System.out.println("Average is " + average);
}
}
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
}