So, I'm supposed to write a program determining Ermips. I've got the rest figured out, but I'm not sure how to reverse the number correctly. I'm supposed to use an array to reverse it.
For example, the number 357.
I use the mod operator to take the last digit and put it in the first index of the array.
357%10 = 7
myArray[0] = 7
357/10 = 35 for a remainder
Use the remainder 35 to start over.
35%10 = 3
myArray[1] = 3
35/10 = 3 for a remainder
etc. ...
I need to basically loop this so I can do any length number to reverse it.
Then, after I have that array, display the array to produce the number in reverse....753.
public class Reverse {
public static void main(String[]args) {
int n = 357;
int MAX_NUMBERS = 20;
int currentNumber = 0;
int reverseNumber = 0;
int remain = 0;
int sum = 0;
int [] holdDigits = new int [MAX_NUMBERS];
int exp = holdDigits.length;
System.out.println("exp: " + exp);
int index = 0;
//sum array
int count = holdDigits.length;
while (count > 0){
holdDigits[index] = n%10;
System.out.println(index + "index: " + holdDigits[index]);
n = n/10;
System.out.println("remainder: " + n);
count--;
index++;
}
while (index < holdDigits.length){
reverseNumber += holdDigits[index]*Math.pow(10,count-exp);
index--;
System.out.println("sum so far: " + sum);
}
System.out.println("Number reversed: " + reverseNumber);
}//end of main
}//end of class
Totally figured it out now, thanks to Yogendra Singh !
Check it out:
public class Reverse2 {
public static void main(String[]args) {
int n = 76495;
int MAX_NUMBERS = 20;
int reverseNumber = 0;
int index = 0;
//declare an array to hold the digits while reversing
int [] holdDigits = new int [MAX_NUMBERS];
//the exponent is the number of spaced used in the array
int exp = holdDigits.length;
//while the number is greater than 0, use mod to put the right-most
//digit in index 0, divide the remaining number and increase the index
//to put it in the next open slot of the array.
while (n > 0){
holdDigits[index] = n%10;
n = n/10;
index++;
}
//decrease the index by one so it doesn't add the remaining zero as
//a placeholder in the number
index--;
//count is the index because below, you subtract it, making the display
//of the array reversed.
int count= index;
//while the index is greater than zero, by starting at the last filled
//slot of the array, the reverse number is added onto each time by
//multiplying the number times 10 to the power of whichever place it
//is which happens to be the index.
//EXAMPLE: to turn 7 into 700, multiply by 7x10^3
while (index >= 0 ){
reverseNumber += holdDigits[count-index]*Math.pow(10,index);
//lower the index to do the next number of the array
index--;
}
System.out.println("Reversed number: " + reverseNumber);
}//end of main
}//end of class
There are some issues in the code as below:
Run the first loop until remainder of division is 0
Count the digits found in the division process
Reduce the index by 1 after first loop as it is post incremented by one in the while loop
Sample corrected code could be as below:
int exp = holdDigits.length;
System.out.println("exp: " + exp);
int index = 0;
while (n > 0){
holdDigits[index] = n%10;
System.out.println(index + "index: " + holdDigits[index]);
n = n/10;
System.out.println("remainder: " + n);
index++;
}
index--;
int count= index;
while (index >=0 ){
reverseNumber += holdDigits[count-index]*Math.pow(10,index);
index--;
System.out.println("sum so far: " + sum);
}
i apology if already you have got an answer but this is an short way to get reverse number using array with for loop.
var val = prompt("enter number");
var New = val.split("");
var arr1 = [];
console.log(New);
for (i = New.length - 1; i >= 0; i--) {
arr1 += New[i] + ',';
} console.log(arr1);
Related
Here is the entire question:
"Write a program that reads an integer value and prints the average of all odd integers between 0 and the input value, inclusive. Print an error message if the input value is less than 0. Prompt accordingly."
I can't seem to figure out how to get the math to work out in the for loop. I'm having trouble setting it up so that the loop increments in odds. I've tried a million different things and nothing has worked.
public static void main(String[] args) {
int value;
int oddAvg = 0;
int count = 0;
Scanner scan = new Scanner(System.in);
System.out.print("Enter an integer: ");
value = scan.nextInt();
while (value < 0){
System.out.println("Error: Input should not be less than 0");
System.out.print("Enter an integer greater than 0: ");
value = scan.nextInt();
}
for(){
}
System.out.println("The average of odd integers between 0 and " + value + " is " + oddAvg);
}
}
A trivial approach could be to just iterate from zero to the target number and check whether each number is odd or even:
int sum = 0;
int count = 0;
for (int i = 0; i <= value; i++) {
if (i % 2 != 0) {
sum += i;
count++;
}
}
int avg = sum / count;
But this, of course, is inefficient. A slightly better approach would be to start from the first odd number, 1, and increment it by 2 in each iteration, so you'd be iterating over just the odd numbers:
double sum = 0;
int count = 0;
for (int i = 1; i <= value; i += 2) {
sum += i;
count++;
}
int avg = sum / count;
Or, if you want to really be mathematically sound, you can utilize the fact that the odd natural numbers in a given range are uniformly distributed. Since this distribution is symmetric, the average equals the mean, and you don't need a loop at all:
int start = 1;
int end = value;
if (value % 2 == 0) {
value--;
}
int avg = (end + start) / 2;
General comment:
In this specific case the average would be an int, so I used ints throughout my examples. In the general usecase, you should probably use doubles to avoid mistakes of using integer division.
Here's a solution to your problem!
public static void main(String[] args) {
int input = 25; //this is whatever value you're going up to.
int accumulator = 0; //keep track of the total sum
for (int i = 0; i < input; i++) {
if (i % 2 == 1) { //if odd
accumulator+=i; // add to the running total sum
}
}
System.out.println(accumulator/(input/2)); //print out the total/num of numbers
}
You can try this if interested in Java 8. It is naive approach implementation.
int val = 0;
final OptionalDouble average = IntStream.rangeClosed(0, val)
.filter(n -> n % 2 != 0)
.average();
System.out.println(average);
How can I apply string.format and printf to my output so that I can align it as per my assignment requirement?
I have 3 inputs to my method, 2 of which are char arrays which hold the two numbers, and an int array which holds their sum.
I have formatted the numbers and sum so that it is a string with appropriate commas interspersed. My task is to now align these outputs so that they always align themselves properly. The problem is I can't just set the column width to a specific number seeing as the inputs vary due to user input.
Ex: User inputs number1 and number2 (up to a max value of 30 digits), the program sums up the numbers and returns the total.
This is my code and current output:
import java.util.Scanner;
import java.util.Arrays;
public class Lab8{
public static void main(String[] args){
char[] num1 = {'9','2','3','8','7','4','8','6','7','2','9'};
char[] num2 = {'3','9','9','8','3','9','2','8','3','4','9','4','5','8'};
//getNumber("First Number: ");
//getNumber("Second Number: ");
//printArray(num1);
//System.out.println();
//printArray(num2);
int[] finalTotal = sumArrays(num1,num2);
//sumArrays(num1, num2);
printOutput(num1, num2, finalTotal);
}
//--------
/** Read a line of message from keyboard and return it as an array of char
#return: Array of characters
*/
public static char[] getNumber(String msg){
String myMessage;
System.out.print(msg);
Scanner input = new Scanner(System.in);
myMessage = input.nextLine();// Read a line of message
return myMessage.toCharArray();
}
public static int[] sumArrays(char[] num1, char[] num2){
int sum= 0, carry = 0, size = 0, min = 0;
if(num1.length > num2.length){
size = num1.length + 1;
min = num2.length;
}else{
size = num2.length + 1;
min = num1.length;
}
int[] sumArray = new int[size];
int i = num1.length-1;
int j = num2.length-1;
int k = size-1;
while(i >= 0 && j >=0){
sum = Character.getNumericValue(num1[i]) + Character.getNumericValue(num2[j]) + carry;
i--;
j--;
sumArray[k] = sum % 10;
sum = sum / 10;
carry = sum % 10;
k--;
}
while(i >= 0){
sum = Character.getNumericValue(num1[i]) + carry;
sumArray[k] = sum % 10;
sum = sum / 10;
carry = sum % 10;
i--;
k--;
}
while( j >= 0){
sum = Character.getNumericValue(num2[j]) + carry;
sumArray[k] = sum % 10;
sum = sum / 10;
carry = sum % 10;
j--;
k--;
}
sumArray[k] = carry;
int[] finalSum = new int[sumArray.length-1];
finalSum = printArray(sumArray);
return finalSum;
}
public static void printOutput(char[] num1, char[] num2, int[] sum){
char[] largest = new char[1];
char[] smallest = new char[1];
char[] tmp = new char[1];
if(num2.length > num1.length){
largest = num2;
smallest = num1;
}else{
largest = num1;
smallest = num2;
}
String number1 = formatString(largest);
String number2 = formatString(smallest);
String total = formatString(sum);
System.out.printf("%s%n", number1 + " +");
for(int i = 0; i < (number1.length() - number2.length()); i++){
System.out.print(" ");
}
System.out.printf("%s%n%s%n%s", number2, totalLine(sum),total);
}
public static String formatString(char[] num){
String formattedString = "";
for(int i = 0; i < num.length; i++){
if(i == 0){
formattedString = num[num.length-1-i] + formattedString;
continue;
}
if(i % 3 == 0){
formattedString = "," + formattedString;
}
formattedString = num[num.length-1-i] + formattedString;
}
return formattedString;
}
public static String totalLine(int[] num){
String totalLine = "";
for(int i = 0; i < num.length; i++){
totalLine = "- " + totalLine;
}
return totalLine;
}
public static String formatString(int[] num){
String formattedString = "";
for(int i = 0; i < num.length; i++){
if(i == 0){
formattedString = num[num.length-1-i] + formattedString;
continue;
}
if(i % 3 == 0){
formattedString = "," + formattedString;
}
formattedString = num[num.length-1-i] + formattedString;
}
return formattedString;
}
public static int[] printArray(int[] arr){
int[] sum = new int[arr.length-1];
if(arr[0] == 0){
for(int i = 1; i < arr.length; i++){
sum[i-1] = arr[i];
}
}else{
for(int i = 0; i < arr.length; i++){
sum[i] = arr[i];
}
}
return sum;
}
}
OUTPUT(wrong)
39,983,928,349,458 +
92,387,486,729
- - - - - - - - - - - - - -
40,076,315,836,187
OUTPUT(correct way)
39,983,928,349,458 +
92,387,486,729
--------------------
40,076,315,836,187
As you can see, my formatting is flawed. I'm totally unsure how to properly format this output so that it displays correctly every time even with differing number values. It should be formatted with the larger number above the smaller number and then a total line followed by the sum.
So after reading some more I realized what I was trying to achieve didn't necessarily require string formatting or printf statements. I ended up, like the previous comments and answer above suggested, just formatting the output with multiple print statements. It's definitely not the most beautiful code to look at but it gives me the exact output I was after.
This was the code that did the trick:
System.out.println(" " + number1 + " +");
for(int i = 0; i < (number1.length() - number2.length()); i++){
System.out.print(" ");
}
System.out.println(" " + number2);
System.out.print(" ");
for(int j = 0; j < ((number1.length() - number2.length())+ number2.length()+1); j++){
System.out.print("-");
}
System.out.println();
System.out.print(" " + total);
Based on your comments, it seems like the math is tripping you up. Let me see if I can help.
(You implied this was homework, so I'm not going to literally give you the code, but this should set you on the right path. I'm sure you can implement it yourself.)
The number of digits in a number is:
Math.floor(Math.log10(x)) + 1
(See this conversation for a proof.)
Use that to find the length of the answer. (This is always going to be the longest number or tied for the longest, since you're adding numbers together.) Make your line of ---s this long.
Append to the front of each line length of that line - length of the answer number of spaces.
(If you want to have a certain number of spaces as an indent on the whole problem, as you have in your example, then append length of line - length of answer + indent number of spaces to the front of each line instead.)
Append + (space and a plus) to the end of the first line, and (two spaces) to the other lines.
That should work!
You can use ArrayLists instead of char arrays to simplify math. But you have to adjust the code a bit. Here is the procedure.
Get two lines of inputs in to two array lists using getNumber() method. (let's call the B and C)
Take the sum to a third array list using the sum method.(Let's call A)
Find the sizes of array lists using size() method in arraylist.
Compare the sizes and get the difference between biggest array list and other two array lists seperately.(Largest would be A so get A-B and A-C). And store sizes B and C sizes for future use in two variables.
Add (A-B) number of whitespaces(" ") into B arraylist staring from 0 index using add(index,object) method in array list.(in add(index,object) method shifts the element currently at that position (if any) and any subsequent elements to the right)
Do the Same for the C array list as well as well.
Find the Array List highest value from B and C using the previously stored sizes and append that array list in to the formatted string first.(using a loop)
Then after "+" and "\n", append the second array list to the format string.
Finally append the array list containing sum(A) into the format string.
As we added whitespaces to make all arrays the same size, the formatted string should be well formated.
I'm trying to sort the digits of an integer of any length in ascending order without using Strings, arrays or recursion.
Example:
Input: 451467
Output: 144567
I have already figured out how to get each digit of the integer with modulus division:
int number = 4214;
while (number > 0) {
IO.println(number % 10);
number = number / 10;
}
but I don't know how to order the digits without an array.
Don't worry about the IO class; it's a custom class our professor gave us.
It's 4 lines, based on a for loop variant of your while loop with a little java 8 spice:
int number = 4214;
List<Integer> numbers = new LinkedList<>(); // a LinkedList is not backed by an array
for (int i = number; i > 0; i /= 10)
numbers.add(i % 10);
numbers.stream().sorted().forEach(System.out::println); // or for you forEach(IO::println)
There's actually a very simple algorithm, that uses only integers:
int number = 4214173;
int sorted = 0;
int digits = 10;
int sortedDigits = 1;
boolean first = true;
while (number > 0) {
int digit = number % 10;
if (!first) {
int tmp = sorted;
int toDivide = 1;
for (int i = 0; i < sortedDigits; i++) {
int tmpDigit = tmp % 10;
if (digit >= tmpDigit) {
sorted = sorted/toDivide*toDivide*10 + digit*toDivide + sorted % toDivide;
break;
} else if (i == sortedDigits-1) {
sorted = digit * digits + sorted;
}
tmp /= 10;
toDivide *= 10;
}
digits *= 10;
sortedDigits += 1;
} else {
sorted = digit;
}
first = false;
number = number / 10;
}
System.out.println(sorted);
it will print out 1123447.
The idea is simple:
you take the current digit of the number you want to sort(let's call it N)
you go through all digits in already sorted number(let's call it S)
if current digit in S is less than current digit in N, you just insert the digit in the current position in S. Otherwise, you just go to the next digit in S.
That version of the algorithm can sort in both asc in desc orders, you just have to change the condition.
Also, I suggest you to take a look at so-called Radix Sort, the solution here takes some ideas from radix sort, and I think the radix sort is the general case for that solution.
I assume you're allowed to use hashing.
public static void sortDigits(int x) {
Map<Integer, Integer> digitCounts = new HashMap<>();
while (x > 0) {
int digit = x % 10;
Integer currentCount = digitCounts.get(digit);
if (currentCount == null) {
currentCount = 0;
}
digitCounts.put(x % 10, currentCount + 1);
x = x / 10;
}
for (int i = 0; i < 10; i++) {
Integer count = digitCounts.get(i);
if (count == null) {
continue;
}
for (int j = 0; j < digitCounts.get(i); j++) {
System.out.print(i);
}
}
}
How to sort a number without use of array, string or sorting api? Well, you can sort a number with following simple steps (if too much to read then see the debugging output below to get an idea of how the sorting is done):
Get the last digit of the number using (digit = number % 10)
Divide number so last digit is gone (number /= 10)
Loop through digits of number (that does not have digit) and check if digit is smallest
If new smaller digit found then replace the digit = smallest digit and keep looking until end
At the end of the loop you have found the smallest digit, store it (store = (store * 10) + digit
Now that you know this is smallest digit, remove this digit from number and keep applying the above steps to remainder number and every time a smaller digit is found then add it to the store and remove digit from number (if digit is repeated in number, then remove them all and add them to store)
I provided a code with two while loops in the main method and one function. The function does nothing but, builds a new integer excluding the digit that is passed to for example I pass the function 451567 and 1 and the function returns me 45567 (in any order, doesn't matter). If this function is passed 451567 and 5 then, it finds both 5 digits in number and add them to store and return number without 5 digits (this avoid extra processing).
Debugging, to know how it sorts the integer:
Last digit is : 7 of number : 451567
Subchunk is 45156
Subchunk is 4515
Subchunk is 451
Subchunk is 45
Subchunk is 4
Smalled digit in 451567 is 1
Store is : 1
Remove 1 from 451567
Reduced number is : 76554
Last digit is : 4 of number : 76554
Subchunk is 7655
Subchunk is 765
Subchunk is 76
Subchunk is 7
Smalled digit in 76554 is 4
Store is : 14
Remove 4 from 76554
Reduced number is : 5567
Last digit is : 7 of number : 5567
Subchunk is 556
Subchunk is 55
Subchunk is 5
Smalled digit in 5567 is 5
Store is : 145
Remove 5 from 5567
Repeated min digit 5 found. Store is : 145
Repeated min digit 5 added to store. Updated store is : 1455
Reduced number is : 76
Last digit is : 6 of number : 76
Subchunk is 7
Smalled digit in 76 is 6
Store is : 14556
Remove 6 from 76
Reduced number is : 7
Last digit is : 7 of number : 7
Smalled digit in 7 is 7
Store is : 145567
Remove 7 from 7
Reduced number is : 0
Ascending order of 451567 is 145567
The sample code is as follow:
//stores our sorted number
static int store = 0;
public static void main(String []args){
int number = 451567;
int original = number;
while (number > 0) {
//digit by digit - get last most digit
int digit = number % 10;
System.out.println("Last digit is : " + digit + " of number : " + number);
//get the whole number minus the last most digit
int temp = number / 10;
//loop through number minus the last digit to compare
while(temp > 0) {
System.out.println("Subchunk is " + temp);
//get the last digit of this sub-number
int t = temp % 10;
//compare and find the lowest
//for sorting descending change condition to t > digit
if(t < digit)
digit = t;
//divide the number and keep loop until the smallest is found
temp = temp / 10;
}
System.out.println("Smalled digit in " + number + " is " + digit);
//add the smallest digit to store
store = (store * 10) + digit;
System.out.println("Store is : " + store);
//we found the smallest digit, we will remove that from number and find the
//next smallest digit and keep doing this until we find all the smallest
//digit in sub chunks of number, and keep adding the smallest digits to
//store
number = getReducedNumber(number, digit);
}
System.out.println("Ascending order of " + original + " is " + store);
}
/*
* A simple method that constructs a new number, excluding the digit that was found
* to b e smallest and added to the store. The new number gets returned so that
* smallest digit in the returned new number be found.
*/
public static int getReducedNumber(int number, int digit) {
System.out.println("Remove " + digit + " from " + number);
int newNumber = 0;
//flag to make sure we do not exclude repeated digits, in case there is 44
boolean repeatFlag = false;
while(number > 0) {
int t = number % 10;
//assume in loop one we found 1 as smallest, then we will not add one to the new number at all
if(t != digit) {
newNumber = (newNumber * 10) + t;
} else if(t == digit) {
if(repeatFlag) {
System.out.println("Repeated min digit " + t + "found. Store is : " + store);
store = (store * 10) + t;
System.out.println("Repeated min digit " + t + "added to store. Updated store is : " + store);
//we found another value that is equal to digit, add it straight to store, it is
//guaranteed to be minimum
} else {
//skip the digit because its added to the store, in main method, set flag so
// if there is repeated digit then this method add them directly to store
repeatFlag = true;
}
}
number /= 10;
}
System.out.println("Reduced number is : " + newNumber);
return newNumber;
}
}
My algorithm of doing it:
int ascending(int a)
{
int b = a;
int i = 1;
int length = (int)Math.log10(a) + 1; // getting the number of digits
for (int j = 0; j < length - 1; j++)
{
b = a;
i = 1;
while (b > 9)
{
int s = b % 10; // getting the last digit
int r = (b % 100) / 10; // getting the second last digit
if (s < r)
{
a = a + s * i * 10 - s * i - r * i * 10 + r * i; // switching the digits
}
b = a;
i = i * 10;
b = b / i; // removing the last digit from the number
}
}
return a;
}
Here is the simple solution :
public class SortDigits
{
public static void main(String[] args)
{
sortDigits(3413657);
}
public static void sortDigits(int num)
{
System.out.println("Number : " + num);
String number = Integer.toString(num);
int len = number.length(); // get length of the number
int[] digits = new int[len];
int i = 0;
while (num != 0)
{
int digit = num % 10;
digits[i++] = digit; // get all the digits
num = num / 10;
}
System.out.println("Digit before sorting: ");
for (int j : digits)
{
System.out.print(j + ",");
}
sort(digits);
System.out.println("\nDigit After sorting: ");
for (int j : digits)
{
System.out.print(j + ",");
}
}
//simple bubble sort
public static void sort(int[] arr)
{
for (int i = 0; i < arr.length - 1; i++)
for (int j = i + 1; j < arr.length; j++)
{
if (arr[i] > arr[j])
{
int tmp = arr[j];
arr[j] = arr[i];
arr[i] = tmp;
}
}
}
}
class SortDigits {
public static void main(String[] args) {
int inp=57437821;
int len=Integer.toString(inp).length();
int[] arr=new int[len];
for(int i=0;i<len;i++)
{
arr[i]=inp%10;
inp=inp/10;
}
Arrays.sort(arr);
int num=0;
for(int i=0;i<len;i++)
{
num=(num*10)+arr[i];
}
System.out.println(num);
}
}
Since the possible elements (i. e. digits) in a number are known (0 to 9) and few (10 in total), you can do this:
Print a 0 for every 0 in the number.
Print a 1 for every 1 in the number.
int number = 451467;
// the possible elements are known, 0 to 9
for (int i = 0; i <= 9; i++) {
int tempNumber = number;
while (tempNumber > 0) {
int digit = tempNumber % 10;
if (digit == i) {
IO.print(digit);
}
tempNumber = tempNumber / 10;
}
}
Scanner sc= new Scanner(System.in);
int n=sc.nextInt();
int length = 0;
long tem = 1;
while (tem <= n) {
length++;
tem *= 10;
}
int last=0;
int [] a=new int[length];
int i=0;
StringBuffer ans=new StringBuffer(4);
while(n!=0){
last=n%10;
a[i]=last;
n=n/10;
i++;
}
int l=a.length;
for(int j=0;j<l;j++){
for(int k=j;k<l;k++){
if(a[k]<a[j]){
int temp=a[k];
a[k]=a[j];
a[j]=temp;
}
}
}
for (int j :a) {
ans= ans.append(j);
}
int add=Integer.parseInt(ans.toString());
System.out.println(add);
For the input:
n=762941 ------->integer
We get output:
149267 ------->integer
import java.util.*;
class EZ
{
public static void main (String args [] )
{
Scanner sc = new Scanner (System.in);
System.out.println("Enter the number - ");
int a=sc.nextInt();
int b=0;
for (int i=9;i>=0;i--)
{
int c=a;
while (c>0)
{
int d=c%10;
if (d==i)
{
b=(b*10)+d;
}
c/=10;
}
}
System.out.println(b);
}
}
import java.util.Scanner;
public class asc_digits
{
public static void main(String args[]){
Scanner in= new Scanner(System.in);
System.out.println("number");
int n=in.nextInt();
int i, j, p, r;
for(i=0;i<10;i++)
{
p=n;
while(p!=0)
{
r = p%10;
if(r==i)
{
System.out.print(r);
}
p=p/10;
}
}
}
}
Stream can also be used for this :
public static int sortDesc(final int num) {
List<Integer> collect = Arrays.stream(valueOf(num).chars()
.map(Character::getNumericValue).toArray()).boxed()
.sorted(Comparator.reverseOrder()).collect(Collectors.toList());
return Integer.valueOf(collect.stream()
.map(i->Integer.toString(i)).collect(Collectors.joining()));
}
class HelloWorld {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int num=sc.nextInt();
System.out.println(" rever number is= "+reversernum(num));
System.out.println("\n sorted number is= "+sortedNumdesc(num));
}
private static int reversernum(int n1)
{
if(n1<10)
return n1;
int n_reverse=0;
int lastDigit=0;
while(n1>=1)
{
lastDigit=n1%10;
n_reverse=n_reverse*10+lastDigit;
// System.out.println(" n_reverse "+n_reverse);
n1=n1/10;
}
return n_reverse;
}
private static int sortedNumdesc(int num)
{
if(num<10)
return num;
List<Integer> numbers = new LinkedList<>();
for (int i=num ;i>0;i/=10)
numbers.add(i%10);
// numbers.stream().sorted().forEach(System.out:: println);
int sorted_Num=0;
List<Integer> sortednum= numbers.stream().sorted()
.collect(Collectors.toList());
// System.out.println("sorted list "+sortednum);
for(Integer x: sortednum)
sorted_Num=sorted_Num*10+x;
return sorted_Num;
}
}
I am moving along in this program just fine, but as I have progressed I have seemingly made some logic errors that are tough to find & need some help. I have methods that sort the array from least to greatest. Whenever I print the smallest number to the screen it always shows that number as 0 even if I haven't typed any zero. I can get the correct highest number, except for when the user enters the max amount of numbers, then it prints the second highest number. Sometimes I get the correct output for the median, but never get the correct output for the average. Any help is greatly appreciated! I feel like I am close to the correct code, but these errors are giving me a tough time.
public static Scanner kbd = new Scanner(System.in);
public static void main(String[] args) {
//change to 100 when done testing
final int MAXSIZE = 10;
int[] nums = new int [MAXSIZE];
int usedSize, indexOfNextSmallest = 0;
double median, average;
System.out.println("Please enter each number starting from least to greatest(a negative number will quit input): ");
usedSize = getNums(nums);
for (int index = 0; index < nums.length -1; index++) {
indexOfNextSmallest = getIndexOfSmallest(index, nums);
interchange(index, indexOfNextSmallest, nums);
}
median = medians(nums);
average = averages(nums);
System.out.println("The smallest number entered is " + nums[0] + ".");
System.out.println("The largest number entered is " + nums[nums.length-1] + ".");
System.out.println("The median is: " + median);
System.out.println("The average is: " + average);
}
public static int getIndexOfSmallest(int startIndex, int[] nums) {
int min = nums[startIndex];
int indexOfMin = startIndex;
for (int index = startIndex +1; index < nums.length; index++) {
if (nums[index] < min) {
min = nums[index];
indexOfMin = index;
}
}
return indexOfMin;
}
private static void interchange(int index, int indexOfNextSmallest, int[] nums) {
int temp = nums[index];
nums[index] = nums [indexOfNextSmallest];
nums[indexOfNextSmallest] = temp;
}
public static int getNums(int nums[]) {
int usedSize = 0, userValue = 0;
while(userValue >= 0 && usedSize < nums.length) {
nums[usedSize] = userValue;
userValue = kbd.nextInt();
usedSize++;
}
if(!(userValue >= 0)) {
--usedSize;
System.out.println(usedSize + " numbers entered.");
}
else if(!(usedSize < nums.length)) {
System.out.println("Maximum amount of inputs (" + nums.length + ") reached.");
}
return usedSize;
}
public static double medians(int nums[]) {
double median;
if (nums.length % 2 == 0)
median = ((double)nums[nums.length / 2] + (double)nums[nums.length / 2 - 1]) / 2;
else
median = (double)nums[nums.length / 2];
return median;
}
public static double averages(int nums[]) {
double average;
int sum = 0;
for (int index = 0; index < nums.length; index++){
sum = sum + nums[index];
}
average = ((double)sum / (double)nums.length);
return average;
}
}
This is the output that I am getting if I enter 1, 2, 3, 4, 5, -7(the negative is to stop user input(could that be a problem?))
Please enter each number starting from least to greatest(a negative number will quit input):
1 2 3 4 5 -7
5 numbers entered.
The smallest number entered is 0.
The largest number entered is 5.
The median is: 0.5
The average is: 1.5
The answers I should be getting with correct code is 1, 5, 3.0, & 3.0
Thank you again for any help.
Your medians() and averages() methods look fine. I would recommend that you get rid of the getIndexOfSmallest() and interchange() methods. You only ostensibly need these methods because you are trying to sort. But I believe the sort is instead altering the array. Use the following method to find the minimum value:
public int getMin(int[] nums) {
int min = nums[0];
for (int i=1; i < nums.length; ++i) {
if (nums[i] < min) {
min = nums[i];
}
}
return min;
}
I will leave it as a homework assignment for you to code a method to find the maximum value.
The whole thing goes worng in two places:
The first one
final int MAXSIZE = 10;
int[] nums = new int [MAXSIZE];
This means that even though the program stopped accepting values after a negative value; all the rest of the array is filled with 0s.
To resolve this, you can choose to use ArrrayList instead on int array.
The second issue
The existing code for getnums is
public static int getNums(int nums[]) {
int usedSize = 0, userValue = 0;
while(userValue >= 0 && usedSize < nums.length) {
nums[usedSize] = userValue;
userValue = kbd.nextInt();
usedSize++;
}
if(!(userValue >= 0)) {
--usedSize;
System.out.println(usedSize + " numbers entered.");
}
else if(!(usedSize < nums.length)) {
System.out.println("Maximum amount of inputs (" + nums.length + ") reached.");
}
return usedSize;
}
Here in the while loop, the statements
nums[usedSize] = userValue;
userValue = kbd.nextInt();
will ensure that the value at num[0] will always be zero(as userValue is initialised to 0) and it won't be fetched from user input.
Instead it should be:
while(userValue >= 0 && usedSize < nums.length) {
userValue = kbd.nextInt();
nums[usedSize] = userValue;
usedSize++;
}
If you take care of these two issues; then the rest of the code should work out fine.
This is what I get when I run the program after updating it for the second issue:
Input
Please enter each number starting from least to greatest(a negative number will quit input):
5
8
4
32
-5
Output
The smallest number entered is -5.
The largest number entered is 32.
The median is: 0.0
The average is: 4.4
Which is correct cause the average and median are calculated for 10 numbers and the rest of the numbers (after entering negative number) are just 0
Update as per comments
If you just wish to reject the negative number the you can update the while loop in getnums method as:
while(userValue >= 0 && usedSize < nums.length) {
userValue = kbd.nextInt();
if(userValue >= 0) {
nums[usedSize] = userValue;
usedSize++;
}
}
Also, the if loop after that shouldn't decrease the value of usedSize
if(!(userValue >= 0)) {
System.out.println(usedSize + " numbers entered.");
}
I am trying a task with arrays: add two elements and check if the sum is less than or equal to 50. If the condition is satisfied, it should break.
Example program:
public class HelloWorld {
public static void main(String []args)
{
int[] nums = new int[2];
for (int i = 0; i < 100; i++)
{
nums[i] = i + 1;
System.out.println(i);
}
System.out.println(nums[1]);
System.out.println(nums[2]);
if (nums[0]+nums[1]<=50)
{
System.out.printf("Sucessfully finished");
}
}
}
Of course, my program is not working. I want i value to store in the two elements
nums[0] = 1 and nums[1] = 2. I also want to add these two elements and check if the sum is less than or equal to 50. I have allocated two elements in the array which means nums want to add and check the current two elements of i and clear and adds next two elements and check if its less than or equal to 50.
nums[0]=1;
nums[1]=2; check <=50 . fails clear the the array elements and store next i value
nums[0]=3;
nums[1]=4; check <=50 . fails clear the the array elements and store next i value
...
nums[0]=25;
nums[1]=26; check <=50 .
There are a lot of ways to do this but here is a nifty trick that solves exactly this kind of problem.
int[] nums = new int[2];
for (int i = 0; i < 100; i++) {
nums[i % nums.length] = i + 1;
if (nums[0] + nums[1] <= 50) {
System.out.println("sum is less than or equal to 50");
break;
}
}
What the mod operator (%) does is calculate the remainder of i based on the array's length. This ensures that i goes from 0 to 99 but the array index always "resets" and stays within the range of the array. For example after i == 0 and i == 1, i will be incremented to out of bounds at i == 2 but 2 % 2 == 0. When i == 3, 3 % 2 == 1 and so on.
But as a side note, the condition you've described ("if the sum is less than or equal to 50...it should break") will be satisfied immediately (sums 1 at nums[0] and 0 at nums[1]) and the loop will not execute past the first iteration (i == 0). I'm not sure that's what you are wanting. Do you mean "not less than or equal to 50"?
int[] nums = new int[2];
for (int i = 0; i < 100; i++) {
nums[i % nums.length] = i + 1;
if (nums[0] + nums[1] > 50) {
System.out.println("sum was NOT less than or equal to 50");
break;
}
}
As an alternate solution finding this result can be very much shortened to the following while loop:
int i = 0;
// note sum of two consecutive integers will never be even (never 50)
while (i + ++i < 50);
System.out.println("min increments with sum > 50 was " + (i - 1) + " and " + i);
The output is min increments with sum > 50 was 25 and 26.
I believe, you need 1 more for loop, to go about checking each num[i] + num[i+1]. You can do it in a single for loop as well, but kept the code as simple as possible for your clarity.(As you are new to java programming ;))
public class HelloWorld{
public static void main(String[] args) {
int[] nums = new int[100];
for (int i = 0; i < 100; i++) {
nums[i] = i + 1;
System.out.println(i);
}
for (int i = 0; i < 99; i++) {
System.out.println(nums[i]);
System.out.println(nums[i+1]);
if (nums[i] + nums[i+1] == 50) {
System.out.printf("Successfully finished");
}
}
}
}
I'm not sure if this is what you meant. Have a try.
public static void main(String[] args) {
int[] nums = new int[100];
nums[0] =1;
for (int i = 1; i < 100; i++) {
nums[i] = i + 1;
if ((nums[i] +nums[i-1]) >= 50) {
System.out.printf("Successfully finished");
}
}
}
I'm not entirely sure on what your end goal is. If you just want to add two numbers (i, and i+1) and see if they are less than 50 then you can use this.
for (int i =0; i < 100; i++) {
int j = i+1;
int total = i+j;
if((i+(i+1)) < 50) {
System.out.println("Numbers '" + i + "' and '" + j + "' equal '" + total + "'.");
}
}
This will print out all the pairs of numbers that add to less than 50 along with what they add to.
I accept that you're probably wanting something more. :)