I need to take the user input and get the program to run it through all the methods and stuff to output the largest and smallest number. I got it to print the largest, but it always has the smallest at 0. This is probably simple to fix, but It's the end of the quarter and i'm stressing to get this last one done. Here is my code.
import java.io.*;
import java.util.*;
public class P4_6
{
private int sum;
private int count;
private int largest = Integer.MIN_VALUE;
private int smallest = Integer.MAX_VALUE;
public P4_6()
{
sum = 0;
largest = 0;
smallest = 0;
count = 0;
}
public void addValue(int x)
{
smallest = Math.min(smallest, x);
largest = Math.max(largest, x);
sum = sum + x;
count++;
}
public int getSum()
{
return sum;
}
public int getLargest()
{
return largest;
}
public int getSmallest()
{
return smallest;
}
public static void main(String[] args)
{
Scanner kbreader = new Scanner(System.in);
System.out.println("Enter your first integer: ");
int num1 = kbreader.nextInt();
System.out.println("Enter your second integer: ");
int num2 = kbreader.nextInt();
System.out.println("Enter your third integer: ");
int num3 = kbreader.nextInt();
System.out.println("Enter your fourth integer: ");
int num4 = kbreader.nextInt();
P4_6 data = new P4_6();
data.addValue(num1);
data.addValue(num2);
data.addValue(num3);
data.addValue(num4);
System.out.println("The largest was " + data.getLargest());
System.out.println("The smallest was " + data.getSmallest());
}
}
You do not need to use No-argument Constructor. Java compiler by default add No-argument Constructor . You can remove the below part.
public P4_6()
{
sum = 0;
largest = 0;
smallest = 0;
count = 0;
}
if you want to keep this part in your code then you should initialize your variable like below
public P4_6()
{
sum = 0;
largest = Integer.MIN_VALUE;
smallest = Integer.MAX_VALUE;
count = 0;
}
You don't need to initialise the 'smallest' and 'largest'. Just remove them
public Test()
{
sum = 0;
//largest = 0;
//smallest = 0;
count = 0;
}
Related
First of all let me say I am quite new to programming its been my second week since I started so if you see any bad practice or error in code please accept my apologies.
I want to print sum of first n odd numbers. But so far I can only do the sum of odd number up to the given number. kindly help.
public static void main(String[] args)
{
Scanner userInput = new Scanner(System.in);
System.out.print("Please enter the number : ");
int num1 = userInput.nextInt();
int sum = sumOfOdd(num1);
System.out.println("sum of first " +num1 + " odd numbers is " + sum);
userInput.close();
}
static int sumOfOdd(int num)
{
int sum = 0;
for (int i = 0; i <= num; i++)
{
if(i % 2 != 0)
{
sum += i;
}
}
return sum;
}
}
You don't have to use a loop at all
static int sumOfOdd(int num) {
return num*num;
}
For Any Arithmetic Progression, the sum of numbers is given by,
Sn=1/2×n[2a+(n-1)×d]
Where,
Sn= Sum of n numbers
n = n numbers
a = First term of an A.P
d= Common difference in an A.P
Using above formula we can derive this quick formula to calculate sum of first n odd numbers,
Sn(odd numbers)= n²
Try this it uses a for loop that increments by two to only account for odd numbers.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the value of n: ");
int n = scanner.nextInt();
System.out.println("The sum of the first " + n + " odd numbers is: " + sumOfOddNumbers(n));
}
public static int sumOfOddNumbers(int n) {
int sum = 0;
for(int i = 1; i < n*2; i+=2) {
sum += i;
}
return sum;
}
}
Example usage:
Enter the value of n: 5
The sum of the first 5 odd numbers is: 25
Try this:
static int sumOfOdd(int num) {
int sum = 0;
for (int i = 0; i < num; i++){
sum += i*2+1;
}
return sum;
}
It sums up all odd numbers until the limit is reached.
With i*2+1 you get the next odd number. Then you add it to the sum.
Tested with System.out.println(sumOfOdd(4)); and got the expected result 16 (1+3+5+7)
Change the counter to the number of times you add an odd number to the sum value...
static int sumOfOdd(int num) {
int sum = 0;
int i = 0;
int count = 0;
do {
if(i % 2 != 0) {
sum += i;
count++;
}
i++;
} while (count < num);
return sum;
}
Or even cleaner:
static int sumOfOdd(int num) {
int sum=0;
for (int i=1;i<num*2;i+=2) {
sum=sum+i;
}
return sum;
}
You should count how many numbers have you added and in the condition to check if count of numbers you summed is less or equal than your n. Just add the counter in your for loop and set condition to: count <= num and it should work.
Every time you add a number to the sum increment the count by count++.
The code suppose to look like this:
static int sumOfOdd(int num)
{
int sum = 0;
int count = 0;
for (int i = 0, count= 0; count <= num; i++)
{
if(i % 2 != 0)
{
sum += i;
count++;
}
}
return sum;
}
I haven't checked it, but it should be correct
Since you don't know how many loop cycles are required you have to change the exit condition of the for loop.
Or you can use a while loop exploiting the same exit condition.
static int sumOfOdd(int num){
int sum = 0;
int counter = 0;
int currentNumber = 0;
while (counter<num){
if(currentNumber % 2 != 0){
sum += currentNumber;
counter++;
}
currentNumber++;
}
return sum;
}
Here is the complete code you'd be using:
public class YourClass {
public static void main(String[] args)
{
Scanner userInput = new Scanner(System.in);
System.out.print("Please enter the number : ");
int num1 = userInput.nextInt();
int sum = sumOfOdd(num1);
System.out.println("sum of first " +num1 + " odd numbers is " + sum);
userInput.close();
}
static int sumOfOdd(int num)
{
int counter = 0;
for (int i = 0;; i++)
{
int sum = 0;
if(i % 2 != 0)
{
counter++;
sum += i;
}
if(counter == num) return sum;
}
}
}
Another alternative.
static int sumOfOdd(int num) {
int sum = 0;
int last = 2*num-1;
for (int i = 1; i <= last; i+=2){
sum += i;
}
return sum;
}
Obviously return num*num; is the most efficient but if you're obliged to use a loop then this method avoids a * inside the loop.
This will be a tiny (tiny) bit more efficient than:
for (int i = 0; i < num; ++i){
sum += 2*i+1;
}
import java.util.*;
class karan{
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int i = n;
int sumOddNumber = n * i;
System.out.println(n*i);
}
}
I am trying to return the sum of all the values in the the array while also trying to return the largest value to the main method, however, the program states that I have an error at return total and at return number. The error states, "Type mismatch: cannot convert from int to int[]."
public static void main(String[] args) {
Scanner number = new Scanner(System.in);
int myArray[] = new int[10];
for(int i = 0; i <= myArray.length-1; i++ ) {
System.out.println("Enter Number: ");
int nums = number.nextInt();
myArray[i] = nums;
}
int [] sum = computeTotal(myArray);
System.out.println("The numbers total up to: "+sum);
int [] largest = getLargest(myArray);
System.out.println("The largest number is: "+largest);
}
public static int[] computeTotal(int myArray[]) {
int total = 0;
for (int z : myArray){
total += z;
}
return total;
}
public static int[] getLargest(int myArray[]) {
int number = myArray[0];
for(int i = 0; i < myArray.length; i++) {
if(myArray[i] > number) {
number = myArray[i];
}
}
return number;
}
The methods computeTotal and getLargestshould be changed the return types to int. Please refer this:
public static void main(String[] args) {
Scanner number = new Scanner(System.in);
int myArray[] = new int[10];
for(int i = 0; i <= myArray.length-1; i++ ) {
System.out.println("Enter Number: ");
int nums = number.nextInt();
myArray[i] = nums;
}
int sum = computeTotal(myArray);
System.out.println("The numbers total up to: "+sum);
int largest = getLargest(myArray);
System.out.println("The largest number is: "+largest);
}
public static int computeTotal(int myArray[]) {
int total = 0;
for (int z : myArray){
total += z;
}
return total;
}
public static int getLargest(int myArray[]) {
int number = myArray[0];
for(int i = 0; i < myArray.length; i++) {
if(myArray[i] > number) {
number = myArray[i];
}
}
return number;
}
Hope this help.
Probably in java8 there're easier way to get the max and sum.
int sum = Arrays.stream(new int[] {1,2, 3}).sum(); //6
int max = Arrays.stream(new int[] {1,3, 2}).max().getAsInt(); //3
I need to create a program that will prompt the user to enter salaries and get the highest and lowest salaries.. Ive been working on it for 4 days now.. and I finally created my program using some of the tutorials on the internet but I only have one problem... I just can't convert the INT to Double ## its giving me a headache.. where did I go wrong? can someone help me? I need to pass java class ;;
here's the code:
import java.util.*;
public class HighestLowestSalary
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("How many salary do you want to enter?: ");
int sal = input.nextInt();
//starting here should be double already..
System.out.println("Enter the "+sal +" salaries");
int[]salary = new int[sal];
for (int i=0; i<sal; i++)
{
salary[i]=input.nextInt();
}
System.out.println("The Highest Salary is: " +high(salary));
System.out.println("The Lowest Salary is: " +low(salary));
}
public static int high(int[] numbers)
{
int highsal = numbers[0];
for (int i=1; i<numbers.length;i++){
if (numbers[i] > highsal){
highsal = numbers[i];
}
}
return highsal;
}
public static int low(int[] numbers){
int lowsal = numbers[0];
for (int i=1;i<numbers.length;i++){
if (numbers[i] < lowsal){
lowsal = numbers[i];
}
}
return lowsal;
}
}
anyone who can help me and teach me how to convert it in double? thank you in advance..
Erm ... to convert an int to a double you can just assign it. The assignment will cause a a "primitive widening conversion" to occur; see JLS 5.1.2.
int myInt = 42;
double myDouble = myInt; // converts to a double.
(No typecast is necessary for a primitive widening conversion ... though adding one does not harm.)
To convert an int array to a double array ....
int[] myInts = ....
double[] myDoubles = new double[myInts.length];
for (int i = 0; i < myInts.length; i++) {
myDoubles[i] = myInts[i];
}
You could just assign an int value to double like:
int n = 1;
double j = n;
System.out.println(j);
Output:
1.0
Note: you could ask for salary to be of double type by using nextDouble api instead of nextInt
I was able to solve the problem because of your help! here is what I did.. like everyone said to convert int to Double
//this is where I changed all the int to double
System.out.println("Enter the "+sal +" salaries");
double[]salary = new double[sal];
for (int i = 0; i<sal; i++){
salary[i] = input.nextDouble();
}
System.out.println("The Highest Salary is: " +high(salary));
System.out.println("The Lowest Salary is: " +low(salary));
}
public static double high(double[] numbers)
{
double highsal = numbers[0];
for (int i=1; i<numbers.length;i++){
if (numbers[i] > highsal){
highsal = numbers[i];
}
}
return highsal;
}
public static double low(double[] numbers){
double lowsal = numbers[0];
for (int i=1;i<numbers.length;i++){
if (numbers[i] < lowsal){
lowsal = numbers[i];
}
}
return lowsal;
}
}
public class NestedCountLoop
{
public static void main(String[] args)
{
int sum = 0;
for (int i = 1; sum < 5050; i++) {
sum = sum + i;
System.out.println(sum);
}
}
}
So I have a little homework assignment for my intro programming class to use a nested loop to accept positive integer input and add all of the integers within the interval from 1 to that input. My mind is playing games with me and I'm having trouble getting going. I know I need a scanner and whatnot, and it has to print every result from 1 to n such as "The sum of 1 to 100 is 5050." Any advice is helpful
Information on scanner at from http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
Scanner sc = new Scanner(System.in);
for (int i = o; i < 100; i++){
int upperLimit = sc.nextInt();
for (int w = 0; w < upperLimit; w++){
sum = sum + i;
}
System.out.println("Sum is " + sum);
}
public class NestedCountLoop
{
public static void main(String[] args)
{
int to = Integer.parseInt(args[0]);
int sum = 0;
for (int i = 1; sum < to; i++) {
sum = sum + i;
System.out.println(sum);
}
}
}
How about this one? It takes an input from the command line (arg0), and adds every number to your number (not inclusive).
So you have to compile your java file with javac, then you can run:
javac NestedCountLoop.java
java NestedCountLoop.class 100
On the other hand, the a previous solution mentioned the javadoc for your scanner, if you really need to use it. :)
System.out.println("Enter your maximum number: ");
// get the input
Scanner input = new Scanner(System.in);
int max = input.nextInt();
int sum = 0;
// iterate through an array to sum up the numbers
for (int i = 1; i < max; i++) {
sum = sum + i; // sum += i;
}
// print out the sum after you counted everything
System.out.println(sum);
import java.util.Scanner;
public class sumoftenIntegerInput {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int sum = 0;
for(int i=1; i<=10; i++){
System.out.println("Enter integer input " + i + ":");
int a = input.nextInt();
sum = sum + a ;
}
System.out.println("Total is:" + sum );
}
}
I am trying to create an array with 'total' amount of numbers between min and max. And then, sort them using bubble sort. When i execute, i get all zeros. Could someone find what is going wrong? A prompt reply would be appreciated.
import java.util.*;
import java.util.Random;
public class final_project
{
public static void main(String[] args)
{
int numbers[];
int i, min, max, total;
int num;
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a minimum random value");
min = scan.nextInt();
System.out.println("Please enter a maximum random value");
max = scan.nextInt();
System.out.println("Please enter the amount of random numbers");
total = scan.nextInt();
numbers = new int[total];
i = 0;
total = 0;
while ( i < total )
{
num = min + (int)(Math.random()*max);;
numbers[i] = num;
total += num;
i += 1; /* i = i + 1; */
}
bubbleSort(numbers, numbers.length);
System.out.println("Your Sorted Array Is: ");
for(i=0; i<numbers.length; i++)
{
System.out.print(numbers[i] + " ");
}
}
private static void bubbleSort(int[] numbers, int length)
{
int temp, counter, index;
for(counter=0; counter<length-1; counter++)
{
for(index=0; index<length-1-counter; index++)
{
if(numbers[index] > numbers[index+1])
{
temp = numbers[index];
numbers[index] = numbers[index+1];
numbers[index+1] = temp;
}
}
}
}
}
Change
while ( i < total )
to
while ( i < numbers.length )
Your loop doesn't execute:
i = 0;
total = 0;
while ( i < total )
...
Also you don't want to increment total. Replace your loop with:
for(int i = 0; i < numbers.length; ++i)
{
numbers[i] = num;
}
You should consider using a for loop instead of a while loop. A for loop is perfect for iterating through an array.