Ok, so I am working on a java program for my college class and I have now spent many hours trying to figure out what I am doing wrong.
My program is below. What it needs to do is convert an integer into single digits and then add them all up. It has to display the original number, the individual digits and then the sum.
Part of the project is it has to accept negative digits and then display the positive numbers and the sum, however with my array it is displaying a -1 as the first number when a negative number is input and I CANNOT for the life of me figure out how to fix it.
Example: input of -3456 ends up displaying -1, 3, 4, 5, 6 and a sum of 17 which is obviously wrong.
Any help would be immensely appreciated, thanks!
import java.util.*;
import javax.swing.JOptionPane; //import package for using dialog boxes
import java.util.Arrays; //import package for arrays
public class Project4
{
public static void main(String args[])
{
//declares and initialize variables sum & counter
int sum = 0;
int counter = 1;
//asks for integer input and stores as a string in numInput
String numInput = JOptionPane.showInputDialog(null, "Enter an integer: ", "User Input", JOptionPane.QUESTION_MESSAGE);
int input = Integer.parseInt(numInput);//parses the value of numInput as an integer and stores as input
int numLength = String.valueOf(input).length();//sets numLength as the length of input
int [] varArray = new int[numLength];//initilizes an array to match numLength
if(input == (-input))//tests for negative input value
{
input = (input * (-1));//corrects the negative input value
for (int i = 0; i < numLength; i++ ) //starts a for loop
{
String var = numInput.substring(i,counter);//stores the value of the number at the location between i and counter as var
int numVal = Character.getNumericValue(var.charAt(0));//sets numVal to the numeric value of the character at 0
varArray[i] = numVal;//saves the numVal to the array at position i
sum = sum + numVal;//adds the sum of the numbers as the loop goes
counter++;//increments the counter
}
}
else //starts alternate loop if input was not a negative value
{
for (int i = 0; i < numLength; i++ )
{
String var = numInput.substring(i,counter);
int numVal = Character.getNumericValue(var.charAt(0));
varArray[i] = numVal;
sum = sum + numVal;
counter++;
}
}
JOptionPane.showMessageDialog(null, "The Digits of Integer Entered " + input + " are: " + Arrays.toString(varArray).replace("[", "").replace("]", "") + "\nThe sum is: " + sum, "NUMBERS", JOptionPane.INFORMATION_MESSAGE);
System.exit(0); //exits program and is required when using GUI
}
}
if(input == (-input))
doesn't test for negative inputs, it tests if the input is 0.
if(input < 0)
tests for negative input.
Always avoid an if.
input = Math.abs( input );
This takes care of the sign and doesn't need an if.
While I'm at it, this is the preferred way to compute the digit sum (provided you don't need to store the digits in an array, from left to right):
int sum = 0;
while( input > 0 ){
sum += input%10;
input /= 10;
}
Replace Condition
if(input == (-input))
By
if(Math.signum(input) == -1.0)
Or
if(input < 0)
try {
int integerNumber = Integer.parseInt(input);//It may positive or negative
if(integerNumber > 0) {
//Do the stuff positive number
} else if(integerNumber < 0){
integerNumber = (integerNumber * -1);
//Do the stuff for negative number
} else {
System.out.println("Enter Number is zero ::");
}
}catch(NumberFormatException nfe) {
System.out.println("Please Enter a Integer Number :::"+input);
}
//I think this code will help for you.
Related
My program runs but I'm getting an error String index out of range: 3 When I enter 1 2 for example. I tried changing the values of 1 in partStr = str.substring(lastSpace + 1, x); but that didn't work. Any ideas what I'm doing wrong?
public static void main(String[] args) {
String str;
int x;
int length;
int start;
int num;
int lastSpace = -1;
int sum = 0;
String partStr;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a series of integers separated by spaces >> ");
str = keyboard.nextLine();
length = str.length();
for (x = 0; x <= length; x++) {
if (str.charAt(x) == ' ') {
partStr = str.substring(lastSpace + 1, x);
num = Integer.parseInt(partStr);
System.out.println(" " + num);
sum += num;
lastSpace = x;
}
}
partStr = str.substring(lastSpace + 1, length);
num = Integer.parseInt(partStr);
System.out.println(" " + num);
sum += num;
System.out.println(" -------------------" + "\nThe sum of the integers is " + sum);
}
You should traverse upto length - 1.
The indexing in String is similar to what happens in arrays.If the length of String is 5 for example,the characters are stored in 0-4 index positions.
Your current loop is traversing beyond the size of the string.
str.length() will return the amount of characters of the string, let's say N
for(x = 0; x <= length; x++) will loop N+1 times, instead of N, because the index starts at 0 and you also enter the loop when x is equal to the length
replacing <= with < in the for loop will fix your problem
The issue you faced is because you tried to access a character at the index, x (i.e. str.charAt(x)) from str where x is beyond the maximum value of the index in str. The maximum value of the index in str is str.length - 1 whereas the for loop is running up to str.length. In order to fix that problem, you need to change the condition to x < length.
However, even after fixing that issue, your program may fail if any entry is non-integer or if there are multiple spaces in the input. A clean way, including exception handling, to do it would be as follows:
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String str;
int sum = 0;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a series of integers separated by spaces >> ");
str = keyboard.nextLine();
// Split str on space(s) and assign the resulting array to partStr
String[] partStr = str.split("\\s+");
// Iterate through partStr[] and add each number to sum
for (String num : partStr) {
try {
sum += Integer.parseInt(num);
} catch (NumberFormatException e) {
// Integer::parseInt will throw NumberFormatException for a non-integer string.
// Display an error message for such entries.
System.out.println(num + " is an invalid entry");
}
}
// Display the entries and the sum
System.out.println("Your entries are: " + Arrays.toString(partStr));
System.out.println("The sum of the integers is " + sum);
}
}
A sample run:
Enter a series of integers separated by spaces >> 10 a 20 10.5 30 b xy 40
a is an invalid entry
10.5 is an invalid entry
b is an invalid entry
xy is an invalid entry
Your entries are: [10, a, 20, 10.5, 30, b, xy, 40]
The sum of the integers is 100
Problem statement
Need to find the Arithmetic mean of numbers entered by user.
Constraints
We cannot ask user to define/share the number of "NUMBERS" user has planned to enter i.e. we cannot ask user to tell how many numbers he is going to enter.
If -1 is entered by user, the input should stop and Arithmetic mean should be displayed.
We are supposed to ask user only to enter the numbers for which Arithmetic mean is to be calculated. Like : User enters
2
4
7
10
-1
so we need to calculate arithmetic mean for 2,4,7,10 and display the result.
Code
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int sum = 0;
do {
System.out.println("Value is :" + n);
count++;
sum = sum + n;
}while ( n != -1);
}
It goes to infinite loop and I've also tried using if/else but i didn't work. Please assist.
For the input of :
3
9
4
-7
0
2
-1
The arithmetic mean should be calculated for 3,9,4,7,0,2,29 i.e. 1.8
Try this:
Scanner sc = new Scanner(System.in);
int sum = 0;
int count = 0;
int n = 0;
do {
System.out.println("Enter next number(-1 to exit): ");
n = sc.nextInt();
System.out.println("Value is :" + n);
if(n != -1)
{
count++;
sum = sum + n;
}
}while ( n != -1);
sc.close();
System.out.println("Mean is: " + (double) sum/count);
}
You needed to move your sc.nextInt(); into the loop so that you can keep entering in values. I also added an if statement so the -1 does not get used in the mean value.
You're reading "n" as input out of the while, then n has always the first value and the loop is infinite.
You just need to keep passing ints, otherwise n is forever the first value entered.
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int sum = 0;
do {
System.out.println("Value is :" + n);
count++;
sum = sum + n;
n = sc.nextInt();
}while ( n != -1);
The object is to get the average of the entered values.
It is to stop when a negative number is entered.
I am trying to get the smallest and largest values entered.
The problem I am having is that my if statements will not take the smallest/largest new values entered.
It just gives me the Integer.Max_Value and Integer.Min_Value.
import java.util.Scanner;
public class LargeSmallAverage {
public static void main(String[] args) {
// TODO Auto-generated method stub
double count = 0;
double amtOfNums = 0;
int input = 0;
int smallest = Integer.MAX_VALUE, largest = Integer.MIN_VALUE;
int number;
System.out.println("Enter a series of numbers. Enter a negative number to quit.");
Scanner scan = new Scanner(System.in);
while ((input = scan.nextInt()) > 0) {
count += input;
amtOfNums++;
}
while(input>=0){
for(int counter=1; counter<amtOfNums; counter++){
number=scan.nextInt();
if(number<smallest)
smallest=number;
if(number>largest)
largest=number;
}
}
System.out.println("You entered " + amtOfNums + " numbers averaging " + (count/amtOfNums) + ".");
System.out.println("The smallest number is "+ smallest);
System.out.println("The largest number is " + largest);
}
}
Currently you have two loops. One sums the numbers, and the other finds the largest and smallest numbers. Given your output, it sounds like you should be doing it all in one loop - ideally with more useful variable names too. (Your count is actually a sum, not a count... and there's no need for it to be a double. You could make it a long if you really want to avoid overflow. Yes, you need to perform floating point arithmetic for your average, but you can do that when you take the average... your sum is logically an integer.)
int sum = 0;
int smallest = Integer.MAX_VALUE;
int largest = Integer.MIN_VALUE;
int count = 0;
while ((input = scan.nextInt()) >= 0) {
count++;
sum += input;
// Alternative: smallest = Math.min(smallest, input)
if (input < smallest) {
smallest = input;
}
// Alternative: largest = Math.max(smallest, input)
if (input > largest) {
largest = input;
}
}
// Cast for count is just to force floating point division.
System.out.println("You entered " + count +
" numbers averaging " + (sum / (double) count) + ".");
System.out.println("The smallest number is "+ smallest);
System.out.println("The largest number is " + largest);
There is a problem with your while loop condition: while(input>=0){
here input will be always less than zero due to your previous while statement:while ((input = scan.nextInt()) > 0)
Here while loop exits only when you enter a number which is less than zero.. so input will have that value..
I have an assignment where I have to write a code which lets the user decide an amount of int values to be written in, and then decides what these values should be. There has to be atleast 2 inputs from the user. The program will then compare the values from the input and then print out the two highest values. So far I managed to print out the highest value, but I'm not sure whats wrong with the way I've done it since the output just becomes 0 if I choose to print out 2 numbers and the highest one is entered in first. And I'm also not sure how to keep track of the second highest number either. Would appreciate some help.
import java.util.Scanner;
public class ToStoersteTall{
public static void main(String[] args){
System.out.println("How many numbers? (minimum 2)?:");
Scanner reader = new Scanner(System.in);
if (reader.hasNextInt()) {
int numbers = reader.nextInt();
if (numbers >= 2) {
System.out.println("Enter value #1");
if (reader.hasNextInt()) {
int num1 = reader.nextInt();
System.out.println("Enter value #2");
if (reader.hasNextInt()) {
int num2 = reader.nextInt();
int biggest = 0;
for (int i = 3; i <= tall; i++) {
System.out.println("Enter value #" + i);
int num3 = reader.nextInt();
biggest = num1;
if(biggest < num3){
biggest = num3;
}
}
System.out.println(biggest);
} else {
System.out.println("Please enter an integer");
}
} else {
System.out.println("Please enter an integer");
}
} else {
System.out.println("Please enter an integer equal or higher than 2.");
}
} else {
System.out.print("Vennligst oppgi et heltall større eller lik 2.");
}
}
}
I have an assignment where I have to write a code which lets the user decide an amount of int values to be written in, and then decides what these values should be. There has to be atleast 2 inputs from the user. The program will then compare the values from the input and then print out the two highest values. So far I managed to print out the highest value, but I'm not sure whats wrong with the way I've done it since the output just becomes 0 if I choose to print out 2 numbers and the highest one is entered in first. And I'm also not sure how to keep track of the second highest number either. Would appreciate some help.
A couple things:
good practice to close scanner (and IO-related resources in general)
reduced if-statement blocks bloat for easier readability
you specify 2 guaranteed numbers, so attempt to parse those before looping
can remove system.exit calls or replace system.exit and move bulk of code back into the larger if-else blocks as originally state in OP (but I refer back to the sake of readability)
added check for the first and second numbers input to make sure high1 is highest value, and high2 is second highest value.
keep order while looping and checking values (note: does not use array), if the number is a new high, replace high1 and move high1's value down to high2, or if the number is a second (new) high, replace high2. If values are equal, this logic is excluded and you may want to specify based on your own constraints
import java.io.IOException;
import java.util.Scanner;
public class ToStoersteTall {
public static void main(String[] args) throws IOException {
System.out.println("How many numbers? (minimum 2)?:");
Scanner reader = new Scanner(System.in);
int n = 0;
if (reader.hasNextInt()) {
n = reader.nextInt();
} else {
System.out.println("Vennligst oppgi et heltall større eller lik 2.");
System.exit(-1); // quits execution
}
if (n < 2) {
System.out.println("Please enter an integer equal or higher than 2.");
System.exit(-2);
}
// Since guaranteed 2 numbers, parse and assign now
int high1 = 0, high2 = 0;
System.out.println("Enter value # 1");
if (reader.hasNextInt())
high1 = reader.nextInt();
System.out.println("Enter value # 2");
if (reader.hasNextInt())
high2 = reader.nextInt();
// check to see if a switch to keep correct highest order, swap values if so
if (high1 < high2) {
int t = high2;
high2 = high1;
high1 = t;
}
// loop won't execute if only 2 numbers input, but will if 3 or more specified at start
for (int i = 2; i < n; ++i) {
System.out.println("Enter value #" + (i + 1));
if (reader.hasNextInt()) {
int t = reader.nextInt();
if (t > high1) {
high2 = high1; // throw away high2 value and replace with high1
high1 = t; // replace high1 value with new highest value
} else if (t > high2) {
high2 = t;
}
} else {
System.out.println("Please enter an interger");
}
}
reader.close();
System.out.println("The two highest numbers are: " + high1 + ", " + high2);
}
}
You're already keeping track of the biggest, so why not keep track of the second biggest? Another easy way of solving this problem is to keep all the numbers in a list, sort the list by number size, and grab the two highest entries.
I tried your code and used an array to solve the problem.
import java.util.Scanner;
public class Main {
static int secondHighest(int... nums) {
int high1 = Integer.MIN_VALUE;
int high2 = Integer.MIN_VALUE;
for (int num : nums) {
if (num > high1) {
high2 = high1;
high1 = num;
} else if (num > high2) {
high2 = num;
}
}
return high2;
}
public static void main(String[] args) {
System.out.println("How many numbers? (minimum 2)?:");
Scanner reader = new Scanner(System.in);
if (reader.hasNextInt()) {
int numbers = reader.nextInt();
int[] array = new int[numbers];
if (numbers >= 2) {
System.out.println("Enter value #1");
if (reader.hasNextInt()) {
int num1 = reader.nextInt();
array[0] = num1;
System.out.println("Enter value #2");
if (reader.hasNextInt()) {
int num2 = reader.nextInt();
array[1] = num2;
int biggest = 0;
for (int i = 3; i <= numbers; i++) {
System.out.println("Enter value #" + i);
int num3 = reader.nextInt();
array[i-1] = num3;
}
System.out.println("second largest number is" + secondHighest(array));
int largest = 0;
for(int i =0;i<array.length;i++) {
if(array[i] > largest) {
largest = array[i];
}
}
System.out.println("Largest number in array is : " +largest);
} else {
System.out.println("Please enter an integer");
}
} else {
System.out.println("Please enter an integer");
}
} else {
System.out.println("Please enter an integer equal or higher than 2.");
}
} else {
System.out.print("Vennligst oppgi et heltall større eller lik 2.");
}
}
}
Test
How many numbers? (minimum 2)?:
6
Enter value #1
3
Enter value #2
4
Enter value #3
5
Enter value #4
6
Enter value #5
7
Enter value #6
8
second largest number is7
Largest number in array is : 8
There is a logic error in your program. If numbers is 2, then the for loop never gets executed, and the value of biggest remains zero because it is never updated. Change your declaration of biggest to reflect the current maximum value found so far.
int biggest = num1 > num2 ? num1 : num2;
That way if the for loop never executes then biggest will be the maximum value of the first two numbers.
As for keeping track of the second highest value, you could introduce another variable secondBiggest, initialised in a similar manner to biggest, and then write logic to update this value in your for loop. However, in my opinion, it would be much easier to change your strategy to hold the entered values into an array, then when all inputs have been entered, calculate whichever values you desire from the array. This would lead to a much cleaner solution IMO.
(I have assumed that tall in the for loop is actually meant to be numbers...)
import java.util.Scanner;
public class Foo{
public static void main(String[] args){
System.out.println("How many numbers? (minimum 2)?:");
Scanner reader = new Scanner(System.in);
if(reader.hasNextInt()){
int numbers = reader.nextInt();
if(numbers >= 2){
int[] list = new int[numbers];
for(int i = 0; i < numbers; i++){
System.out.println("Enter value #" + (i + 1));
if(reader.hasNextInt())
list[i] = reader.nextInt();
}//for
int biggest = 0;
int secondBiggest = 0;
// find the values you want
for(int i = 0; i < numbers; i++){
if(list[i] > biggest){
secondBiggest = biggest;
biggest = list[i];
}//if
else if(list[i] > secondBiggest)
secondBiggest = list[i];
}//for
// print your results
System.out.println("The biggest integer is: " + biggest);
System.out.println("The second biggest integer is: " + secondBiggest);
}//if
}//if
}//main
}//class
I am writing a program that reads a sequence of positive integers input by the user. User will only enter one integer at a time.Then it will compute the average of those integers. The program will end when user enters 0. (0 is not counted in the average).The program will print out the average once the program ends.
Question: My code stops working when I gets to the while loop hence it doesn't compute the input by user, hence prints out nothing. Why doesn't my while loop compute the average from the user's inputs? Appreciate your guidance :)
import java.util.Scanner;
public class AverageOfIntegers {
public static void main(String[] args) {
int integer;
double sum;
sum = 0;
double average;
Scanner input = new Scanner(System.in);
int count; count = 0;
average = 0;
System.out.println("Please enter an integer: ");
integer = input.nextInt();
while (integer != 0) {
count = count + 1;
sum = sum + integer;
average = sum / count;
}
System.out.println("Average = " + average);
}
}
This is because you are never actually summing over more than one integer. The user only ever enters one number. As a result your loop is essentially acting on just the one number. You need to put the input inside the while loop and save a running sum and count there. Something more like this
while (integer != 0) {
count += 1;
sum += integer;
average = sum / count;
integer = input.nextInt();
}
Explanation
First of all, when you define data types, you can set their default value in the definition. Ex:
double sum = 0;
vs
double sum;
sum = 0;
Secondly, sum = sum + integer; is the same as: sum += integer;
Thirdly, count = count + 1; is the same as: count += 1 OR (and better yet), count++;
As for your actual algorithm, there is one problem and one suggestion:
you are not changing integer's value after each loop. So, you can
either do that in the while condition: while ((integer =
input.nextInt()) != 0) { or, at the end of each loop:
while (integer != 0) {
count ++;
sum += integer;
average = sum / count;
integer = input.nextInt();
}
This is a suggestion for technically better code (in my opinion), but it looks better, is more intuitive and requires less calculations to calculate the average after the while loop is done instead of during. That way, you only calculate it once, where needed, vs. every loop, which is not needed.
________________________________________________________________________________
The Code (complete class)
public class AverageOfIntegers {
public static void main(String[] args) {
int integer;
double sum = 0;
double average = 0;
Scanner input = new Scanner(System.in);
int count = 0;
System.out.println("Please enter an integer: ");
// set integer = to the nextInt() while looping so it calculates properly
while ((integer = input.nextInt()) != 0) {
count ++;
sum += integer;
}
average = sum / count; // calculate the average after the while-loop
System.out.println("Average = " + average);
}
}
________________________________________________________________________________
Example input/output:
Please enter an integer:
5
10
15
0
Average = 10.0
So it did 5 + 10 + 15 = 30 (which is the sum), and then the average is 30 / 3 (30 is the sum, 3 is the count), and that gave you Average = 10.0.
You need to move integer = input.nextInt(); inside the loop, so your program will collect inputs in a loop. See the corrected version:
import java.util.Scanner;
public class AverageOfIntegers {
public static void main(String[] args) {
int integer = 0, count = 0;
double sum = 0.0, average = 0.0;
Scanner input = new Scanner(System.in);
System.out.println("Please enter an integer: ");
integer = input.nextInt();
while (integer != 0) {
count = count + 1;
sum = sum + integer;
System.out.println("Please enter an integer: ");
integer = input.nextInt();
}
average = sum / count;
System.out.println("Average = " + average);
}
}
The problem is that the input.nextInt() should be part of the loop. The way you wrote it, the code gooes into an infinite loop whenever the first input is non-zero. Instead, do:
while ((integer = input.nextInt()) != 0) {
count = count + 1;
sum = sum + integer;
average = sum / count;
}
In the loop:
while (integer != 0) {
count = count + 1;
sum = sum + integer;
average = sum / count;
}
This will only stops when integer is 0, but this variable is not changing in the loop, so it will never be 0 if it wasn't already in the first place.
According to what you said you want to do, you should probably repeat the call to integer = input.nextInt(); inside your loop, lke this:
System.out.println("Please enter an integer: ");
integer = input.nextInt();
while (integer != 0) {
count = count + 1;
sum = sum + integer;
System.out.println("Please enter an integer: ");
integer = input.nextInt();
}
average = sum / count;
Also, as others have said, you only need to compute the average once after the loop, so I moved it too.