I'm new to Java and I'm trying to make a program that allows the user to input 100 numbers and if the user writes '0', then the program is suppose to print the smallest, largest, sum and all the numbers. I got all that to work but not to exit and print it all. My teacher said something about using a while loop, but how is that possible when you have a for loop?
Regards
public static void main(String[] args) {
int[] list = new int[100];
int min = 0;
int max = 0;
int sum = 0;
boolean first = true;
Scanner scan = new Scanner(System.in);
while(list[i] != 0) {
for (int i = 0; i < list.length; i++) {
System.out.print("Enter number (0 to exit) " + (1 + i) + ":");
list[i] = scan.nextInt();
}
for (int i = 0; i < list.length; i++) {
if (first == true) {
min = list[i];
first = false;
}
if (list[i] < min) {
min = list[i];
}
else if (list[i] > max) {
max = list[i];
}
sum = list[i] + sum;
}
if (list[i] == 0) {
System.out.print("Numbers are: " + list[0] + ", ");
for (int i = 1; i < list.length; i++)
System.out.print(list[i] + ", ");
System.out.println();
System.out.println("Smallest number is: " + min);
System.out.println("Largest numeber is: " + min);
System.out.println("Sum is: " + sum);
}
}
}
}
You only need one while loop to do this and additionally a for loop just to print the array if you want:
Scanner scan = new Scanner(System.in);
int i = 0;
int sum = 0;
int maxValue = Integer.MIN_VALUE;
int[] history = new int[100];
System.out.println("INPUT:");
int option = scan.nextInt();
while (option != 0 && i <= 100)
{
if (option > maxValue)
maxValue=option;
sum += option;
history[i] = option;
option = scan.nextInt();
i++;
}
System.out.println("OUTPUT: \n" + "SUM: " + sum + "\n MAX VALUE: " + maxValue);
for (int x : history)
System.out.print(x + "");
Here's the body of the method which will do what you've been asked. I have not used a while loop (but in fact, a for-loop is a kind of a while-loop internally).
int size = 100; // Set the number of numbers to input.
int[] list = new int[size]; // Create an array with 'size' elements.
int min = Integer.MAX_VALUE; // Set the highest possible integer as start value.
int max = 0; // Set the minimum to zero, assuming that the user won't input negative numbers.
int sum = 0; // Initialize the sum of the numbers in the list.
Scanner scan = new Scanner(System.in);
for (int i = 0; i < size; i++) { // Run 'size' times the process of inputting a number.
System.out.print("Enter number (0 to exit) " + (i + 1) + ": ");
int number = scan.nextInt();
if (number == 0) { // Quit program if input equals '0'
System.out.println("Exiting...");
break;
}
list[i] = number; // Add the current number to the list
sum += number; // Add the number to the total
if (number < min) { // If the number is smaller than the previous one, set this number as the smallest
min = number;
}
if (number > max) { // If the number is greater than the previous smallest number, set this number as the greatest
max = number;
}
}
// Output all numbers in the list
for (int i = 0; i < list.length; i++) {
if (list[i] != 0) {
System.out.print((i == 0 ? "" : ", ") + list[i]);
}
}
// You see the snippet (i == 0 ? "" : ", ")
// That is a shorthand if-else statement:
// If i equals 0, then "" (empty string), else ", " (comma and space).
// The statement
// System.out.print((i == 0 ? "" : ", ") + list[i])
// is the same as
// if (i == 0) {
// System.out.println("") + list[i];
// }
// else {
// System.out.println(", ") + list[i];
// }
System.out.println("Smallest number is: " + min);
System.out.println("Largest numeber is: " + max);
System.out.println("Sum is: " + sum);
You have muddled code. Better to use a pattern like this:
while (true) {
// read next
if (input == 0)
break;
}
Related
I am relatively new to Java and to coding as well and am currently trying to solve a subset problem.
The goal is to have the user input the amount of numbers and then input every number up to the amount specified, with the computer asking for every n-th number accordingly.
Afterwards the computer should calculate the sum of all subsets, and return the one closest to pi, as well as the subset in this form [x,y,z] within the same line.
I managed the first part just fine, although it might have been improved with a switch-case for convenience. It adds the input numbers into the array
But I struggle with the second part of this problem, and I have no idea how to progress/arrange the code so that it outputs the desired result. The suggestion I got was that, a for-loop for a set with n elements :
for a from 0 to 2^n
for i from 0 to n
when the binary representation of x on has a 1 at the i-th position
add data[i] to solution.
This should supposedly find all subsets of an array. After that I should add each element, check if the distance from pi decreases and add the element to the solution set. Or at least that is the goal, but my code is not functional as I don't know where to start arranging it. I also don't know what to initialize bestsum with, or how the binary representation algorithm works, or how to add elements to the solution array in order.
Edit : I have made progress, the code below outputs all the subarrays, and it properly calculates the closest sum, but I have no idea how to 'save' the best subarray (subarray with the closest sum) so that I can output it at the end with the sum. I am quite new so I haven't learned about lists or even methods, but this problem in this book at this chapter and I would like to solve it with the suggested method and possibly only simple loops.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("How many numbers should be read? ");
int count = input.nextInt();
double[] data = new double[count];
double [] solution = new double[count];
double bestsum = 0.0;
for (int i = 0; i < count; i++) {
if ((i + 1) % 10 == 1) {
System.out.println("Enter " + (i + 1) + "st number: ");
data[i] = input.nextDouble();
} else if ((i + 1) % 10 == 2) {
System.out.println("Enter " + (i + 1) + "nd number: ");
data[i] = input.nextDouble();
} else if ((i + 1) % 10 == 3) {
System.out.println("Enter " + (i + 1) + "rd number: ");
data[i] = input.nextDouble();
} else {
System.out.println("Enter " + (i + 1) + "th number: ");
data[i] = input.nextDouble();
}
}
for (int j = 0; j <(1 << count); j++) {
System.out.print("{ ");
double sum = 0.0;
for (int x = 0; x < count; x++) {
if ((j & (1 << x)) > 0) {
System.out.print(data[x] + " ");
sum = sum + data[x];
}
solution[x] = data[x];
}
System.out.println("}");
if (Math.abs(sum - Math.PI) < Math.abs(bestsum - Math.PI)) {
bestsum = sum;
}
}
System.out.println(bestsum);
System.out.println(Arrays.toString(solution));
}
}
Here's my solution to this problem.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("How many numbers should be read? ");
int count = input.nextInt();
Double data[] = new Double[count];
Double bestsum = 0.0;
List<Double> bestArray= Collections.emptyList();
Set<List<Double>> possibleArrays = new LinkedHashSet<>();
for (int i = 0; i < count; i++) {
if (i == 0) {
System.out.println("Enter " + (i+1) + "st number: ");
data[i] = input.nextDouble();
} else if (i == 1) {
System.out.println("Enter " + (i+1) + "nd number: ");
data[i] = input.nextDouble();
} else if (i == 2) {
System.out.println("Enter " + (i+1) + "rd number: ");
data[i] = input.nextDouble();
} else {
System.out.println("Enter " + (i+1) + "th number: ");
data[i] = input.nextDouble();
}
}
input.close();
for (int i = 0; i < (1<<count); i++)
{
int m = 1; // m is used to check set bit in binary representation.
List<Double> currentArray = new ArrayList<>();
for (int j = 0; j < count; j++)
{
if ((i & m) > 0)
{
currentArray.add(data[j]);
}
m = m << 1;
}
possibleArrays.add(currentArray);
}
Iterator<List<Double>> iterator = possibleArrays.iterator();
iterator.next();
for (int i = 1; i < possibleArrays.size(); i++) {
Double sum=0.0;
List<Double> currentArray = iterator.next();
sum = currentArray.stream().collect(Collectors.summingDouble(Double::doubleValue));
if(Math.abs(sum-Math.PI)<Math.abs(bestsum-Math.PI)) {
bestArray = currentArray;
bestsum = sum;
}
}
System.out.println("possibleArrays: " + possibleArrays);
System.out.println("solution: " + bestArray);
System.out.println("bestsum: " + bestsum);
}
I have tried programming recently and there is an exercise online that involves adding the odd integer values of any inputted integer.
My code is able to output the sum of the odd integer values but the exercise asks to output an addition sequence like 1 + 3 + 5... = sum.
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int number, oddSumPositive = 0, oddSumNegative = 0;
System.out.print("Enter an integer : ");
number = input.nextInt();
oddSumPositive = sumOfOdd_Postive(number);
oddSumNegative = sumOfOdd_Negative(number);
//different scenarios
if(number > 0) {
System.out.println("\nThe Sum of Odd Numbers upto " + number + " = " + oddSumPositive);
}
else if(number < 0) {
System.out.println("\nThe Sum of Odd Numbers upto " + number + " = " + oddSumNegative);
}
else if(number == 0) {
System.out.println("\nThe Sum of Odd Numbers upto 0 = 0");
}
else {
System.out.println("\nError");
}
}
//Method for positive integers
public static int sumOfOdd_Postive(int num)
{
int i, sum = 0;
for(i = 1; i <= num; i++)
{
if (i%2 != 0)
{
sum += i;
System.out.print(i + " ");
}
}
return sum;
}
//Method for negative integers
public static int sumOfOdd_Negative(int num)
{
int i, sum = 0;
for(i = -1; i >= num; i--)
{
if (i%2 != 0)
{
sum += i;
System.out.println((i) + " ");
}
}
return sum;
}
public static int sumOfOddPostive(int num) {
int sum = 0;
for (int i = 1; i <= num; i++) {
if (i%2 != 0) {
sum += i;
if (i != 1) {
System.out.print("+ ");
}
System.out.print(i + " ");
}
}
System.out.println("= " + sum);
// int n = (num + 1)/2; sum = n*n;
return sum;
}
To have a "+" between the terms (one less than the number of terms),
one way is to skip the first (or last term).
It is questionable whether both calculation and output should be so mixed.
Of course the sum can be calculated without all those additions.
I guess you are not printing + as a character anywhere in your code snippet, try below snippet
public static int sumOfOdd_Postive(int num) {
int i, sum = 0;
for(i = 1; i <= num; i++) {
if (i%2 != 0) {
sum += i;
System.out.print(i + "");
if(i != num - 1){ //to avoid + at end of expression
System.out.print("+");
}
}
}
System.out.print("="+sum);
return sum;
}
You want a String so your method should return a String, not an int
Also, you can use StringBuilder in order to create a concatenated String.
Here is a naive implementation :
static String sumOdds(int limit) {
StringBuilder sb = new StringBuilder();
long sum = 0;
for (int i = 1; i <= limit; i++) {
if ( i%2 == 1 ) {
sum += i;
sb.append(i);
if (i + 2 <= limit) {
sb.append(" + ");
} else {
sb.append(" = ").append(sum);
}
}
}
return sb.toString();
}
That being said, as you only want odd or even numbers, there is no point to increment the step one by one and check modulos, you could directly start at 1 and increment steps by 2 :
static String sumOdds(int limit) {
StringBuilder sb = new StringBuilder();
long sum = 0;
for (int i = 1; i <= limit; i+=2) {
sum += i;
sb.append(i);
if (i + 2 <= limit) {
sb.append(" + ");
} else {
sb.append(" = ").append(sum);
}
}
return sb.toString();
}
Also, later, you will discover... Streams !
You can create a Stream of Integer and use some Collectors in order to do fancy things with them.
For example :
static IntStream oddStream(int limit) {
/*
* Here, you can also generate directly odd numbers without filtering
* but it is a bit out of scope.
* See : https://howtodoinjava.com/java8/generate-finite-infinite-stream/
*/
return IntStream.range(1, limit + 1).filter(i -> i % 2 == 1);
}
Then, you can use it to get all the values, map them to a String and collect them in a String, where the values are separated with " + "
String str = Main.oddStream(limit)
.mapToObj(Integer::toString)
.collect(Collectors.joining(" + "));
Also, you can use the same Stream in order to sum all the values :
long sum = Main.oddStream(limit).sum();
Which allows you to create the desired result like this :
static String sumEven(int limit) {
String str = Main.oddStream(limit)
.mapToObj(Integer::toString)
.collect(Collectors.joining(" + "));
long sum = Main.oddStream(limit).sum();
return str + " = " + sum;
}
Okay so im trying to find the amount of numbers that are less then
the mean of the first array. Everything but the last part is working and i
cant figure it out. The code at the bottom is what im having problems with.
for example. if i enter 1 2 3 4 5. the mean is 3 and, 1 and 2 are less then 3. so the answer would be 2 numbers.
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
System.out.println("How many integers should we analyze?" );
int num;
num=in.nextInt();
while ( num <= 2)
{
System.out.println( "Please reenter, integer must be greater than 1" );
num=in.nextInt();
}
int[] arr = new int[num];
System.out.println( "Please enter the "+ num +" integers:" );
for (int i = 0; i < arr.length; i++)
{
arr[i] = in.nextInt();
}
System.out.print("Number of integers input: " + num);
System.out.println();
double total = 0;
for( int element : arr) {
total += element;
}
System.out.print("Total: " + (int) total);
System.out.println();
double mean = 0;
if ( arr.length > 0) {
mean = total / arr.length;
}
System.out.print("Mean: " + mean );
int big = arr[0];
for (int i = 0 ; i < arr.length; i++) {
if (arr[i] > big) {
big = arr[i];
}
}
System.out.println();
System.out.print("Largest: " + big);
System.out.println();
///////////////////////////////////////////////////////////////////////////////////////////////
int less;
for(int i=0;i<mean;i++) {
int num2 = i;
int[] arr2 = new int[num2];
int count = 0;
while ( num2 != 0 )
{
num2/=10;
++count;
System.out.print("Numbers less than the mean: " + count);
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
}
}
you could use this code below
int count = 0;
for(int i =0;i< arr.length;i++) {
if(arr[i] < mean)
count++;
}
System.out.println("numbers less than mean " + count);
what this does is it loops through all of the original integers and if one is less than the mean, the count variable goes up by 1.
You should iterate over the array and check each element if they are under the mean. If yes, then increment an integer.
int less = 0;
for(int i = 0; i < arr.length; i++) {
if(arr[i] < mean) {
less++;
}
}
System.out.print("Numbers less than the mean: " + less);
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter the max number:");
int max = input.nextInt();
int[]arr1 = new int[max+1];
int[]arr2 = new int[max+1];
int[]arr3 = new int[max+1];
int i = 1;
// For-loop to calculate
for (i = 1;i <= max;i++)
arr1[i] = arr1[i-1] + i;
i = 1;
// While-loop to calculate
while (i <= max) {
arr2[i] = arr2[i-1] + i;
i++;
}
i = 1;
// Do-While-loop to calculate
do
arr3[i] = arr3[i-1] + i;
while (++i <= max);
for (i = 0; i <= max; i++)
System.out.println("Arr1 " + arr1[i] + " Arr2 " + arr2[i] + " Arr3 " + arr3[i]);
System.out.println("Sum of All is " + arr1[max]);
}
I have this for doing sums but I am stuck when it comes to getting it to square
You seem to have 3 identical array objects?
Anyway, it's pretty straightforward to print the square of all numbers from 1 to max:
for (int i = 1; i <= max; i++) {
System.out.println(i + ": " + i * i);
}
There are also some fun ways to sum up the numbers from 1 to max, such as:
System.out.println(IntStream.range(1, max + 1).sum());
Doing a rather large assignment for my java class. I've written the entire program, but I've run into one last problem, there needs to be a check on the user input into the array to make sure it is an integer that the user is inputting, and not junk(a, Z, 2.0, #%&##%*#%^, etc.) and if that error happens, it has to loop back, reallowing the input with an error message until they comply.
I've heard of using try/catch to try as a solution, and I've also thought of maybe a while loop, but still not sure on how to go about it. Any tips?
import java.util.Scanner;
import java.util.Arrays;
public class Assignment6 {
public static int getMaxValue(int[] array) {
int maxValue = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] > maxValue) {
maxValue = array[i];
}
}
return maxValue;
}
public static int getMinValue(int[] array) {
int minValue = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] < minValue) {
minValue = array[i];
}
}
return minValue;
}
public static double average(int[] array) {
double sum = 0, average = 0;
for (int i = 0; i < array.length; i++) {
sum = sum + array[i];
average = sum / array.length;
}
return average;
}
public static double Median(int[] array) {
int Median = array.length / 2;
if (array.length % 2 == 1) {
return array[Median];
} else {
return (array[Median - 1] + array[Median]) / 2.0;
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter size of array: ");
int[] array = new int[input.nextInt()];
for (int i = 0; i < array.length; i++) {
System.out.print("Enter value #" + (i + 1) + ": ");
array[i] = input.nextInt();
}
System.out.println("\nYour data is:");
for (int i : array)
System.out.print(i + "\n");
System.out.println();
System.out.println("Average is : " + average(array));
System.out.println("Smallest value is: " + getMinValue(array));
System.out.println("Largest value is: " + getMaxValue(array));
System.out.println("\nYour sorted data is: ");
Arrays.sort(array);
for (int i = 0; i < array.length; i++)
System.out.println(array[i]);
double Median = Assignment6.Median(array);
System.out.println("\nThe median is: " + Median);
int Range = Assignment6.getMaxValue(array) - Assignment6.getMinValue(array);
System.out.println("\nThe range is: " + Range);
double midRange = (Assignment6.getMaxValue(array) + Assignment6.getMinValue(array)) / 2.0;
System.out.println("\nThe Midrange is: " + midRange);
}
}
Since you used Scanner.nextInt(), it is not possible that non-integer input was added to the array. Additionally, it is not possible that a non-integer value got into your int[]. The program would likely not compile, and even if it did, would throw a run-time exception.
However, if the user inputs a non-integer, your program will crash. It doesn't really have anything to do with an array, but I'm guessing this is what you meant by your question. The correct way to safely read only integer input from the user with a Scanner would be:
for (int i = 0; i < array.length; i++) {
System.out.print("Enter value #" + (i + 1) + ": ");
while (!input.hasNextInt()) { // <-- 'peeks' at next token
System.out.println("Please enter an integer!");
input.next(); // <-- skips over invalid token
}
array[i] = input.nextInt();
}
You can also use Integer.parseInt(yourString) and it will throw a NumberFormatException if the String is not a valid