Currently trying to output the Min and Max of 25 numbers inputed from keyboard, although I am having trouble in the Scanner class to be able to input said numbers. I keep getting an error for cannot make Int[] to an Int.
Here is the question:
(MinMax.java) Read in 25 ints from the keyboard, and store them in an
array. Find the maximum and minimum values in the array, and display
them on the screen.
Here is my current Code:
import java.util.Scanner;
import java.util.Arrays;
public class MinMax{
public static void main (String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Please enter 25 numbers.");
int[] numbers = sc.nextInt();
System.out.println("Minimum Value = " + getMinValue(numbers));
System.out.println("Maximum Value = " + getMaxValue(numbers));
}
public static int getMaxValue(int[] numbers) {
int maxValue = numbers[0];
for(int i=1;i<numbers.length;i++){
if(numbers[i] > maxValue){
maxValue = numbers[i];
}
}
return maxValue;
}
//Find minimum (lowest) value in array using loop
public static int getMinValue(int[] numbers){
int minValue = numbers[0];
for(int i=1;i<numbers.length;i++){
if(numbers[i] < minValue){
minValue = numbers[i];
}
}
return minValue;
}
}
You can't do this:
int[] numbers = sc.nextInt();
That's because sc.nextInt() returns an int not an array of ints.
Instead, you need to create a loop that reads the 25 integers:
int[] numbers = new int[25];
for(int i = 0; i < 25; i++) {
numbers[i] = sc.nextInt();
}
The problem is your main funtion.
Just do this:
public static void main (String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter 25 numbers.");
int[] numbers = new int[25];
for (int i = 0; i < 25; i++) {
System.out.print("Number " + (i+1) + ": ");
numbers[i] = sc.nextInt();
}
System.out.println("Minimum Value = " + getMinValue(numbers));
System.out.println("Maximum Value = " + getMaxValue(numbers));
}
Related
I am working on a java code that calculates the average of an array and it is working perfectly in serving its purpose but I want to modify it to be a 2D array (Two-dimensional).
import java.util.*;
public class Test3{
public static void main(String [] args){
Scanner adnan = new Scanner(System.in);
System.out.println("Enter the length of the array : ");
int length = adnan.nextInt();
int [] input = new int [length];
System.out.println("Enter Numbers : ");
for ( int i = 0; i < length; i++){
input [i] = adnan.nextInt();
}
float average = average(input);
System.out.println("Average of all numbers in the array : " + average);
adnan.close();
}
public static float average(int [] input){
float sum = 0f;
for ( int number : input){
sum = sum + number;
}
return sum / input.length;
}
}
any help would be really appreciated because I am not too good at 2D arrays.
In Java a 2D Array is declared using double brackets T [][]:
public static void main(String[] args) {
// mock to not to use a stdin redirection or enter data manually
ByteArrayInputStream system_in = new ByteArrayInputStream("3 2 5 8 1 6 7 2".getBytes(UTF_8));
Scanner adnan = new Scanner(system_in);
System.out.println("Enter rows number: ");
final int rows = adnan.nextInt();
System.out.println("Enter rows number: ");
final int cols = adnan.nextInt();
final int [][] input = new int[rows][cols];
System.out.println("Enter Numbers : ");
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
input[row][col] = adnan.nextInt();
}
}
double average = average(input);
System.out.println("Average of all numbers in the array : " + average);
adnan.close();
}
public static double average(int[][] input) {
// use streams or you can use the `Enter Numbers...` way
return Arrays.stream(input)
.flatMap(x -> Arrays.stream(x).boxed())
.mapToInt(x -> x).average()
.getAsDouble();
}
with output
Enter rows number:
Enter rows number:
Enter Numbers :
Average of all numbers in the array : 4.833333333333333
I'm making a program using Java that calculates the sum of the numbers entered; I figured this part out. However, I want to move the for loop into a different method called "Sum", but I keep getting errors and I don't know what to do.
Here is the code thats only in the Main method (it works perfectly fine):
import java.util.Scanner;
public class testing {
public static void main(String args[]){
System.out.println("Enter the size of the array: ");
Scanner in = new Scanner(System.in);
int size = in.nextInt();
int myArray[] = new int [size];
int sum = 0;
System.out.println("Enter the elements of the array one by one: ");
for(int i=0; i<size; i++){
myArray[i] = in.nextInt();
sum = sum + myArray[i];
}
System.out.println("Sum of the elements of the array: "+ sum);
}
}
However, when I move the for loop into the method known as print, I get a bunch of errors:
import java.util.Scanner;
public class MPA4 {
public static void main(String[] args) {
System.out.println("Enter the size of the array: ");
Scanner in = new Scanner(System.in);
int size = in.nextInt();
int myArray[] = new int [size];
int sum = 0;
System.out.println("Enter the elements of the array one by one: ");
}
print(sum);
}
public static void print (double []sum){
Scanner in = new Scanner(System.in);
int myArray[] = new int [size];
for(int i=0; i<size; i++){
myArray[i] = in.nextInt();
sum = sum + myArray[i];
}
System.out.println("Sum of the elements of the array: "+ sum);
}
}
Here are all the errors underlined in red:
I'm not sure what I'm doing wrong, any help would be much appreciated!
I changed it as below and it is working.
import java.util.Scanner;
public class MP4 {
public static void main(String[] args) {
System.out.println("Enter the size of the array: ");
Scanner in = new Scanner(System.in);
int size = in.nextInt();
int myArray[] = new int[size];
System.out.println("Enter the elements of the array one by one: ");
for (int i = 0; i < size; i++) {
myArray[i] = in.nextInt();
}
print(myArray, size);
}
public static void print(int[] myArray, int size) {
int sum = 0;
Scanner in = new Scanner(System.in);
for (int i = 0; i < size; i++) {
sum = sum + myArray[i];
}
System.out.println("Sum of the elements of the array: " + sum);
}
}
before you help me this is a homework assignment, i have most of all of it done but there is one thing that i cant figure out, 0 doesn't get detected at all. This means if i input 0-9 into the array it will tell me there is only 9 distinct numbers when really there should be 10 and it will print out all the numbers but 0. Can anyone see the problem and please explain it to me becuase i need to understand it.
package javaproject.pkg2;
import java.util.Scanner;
public class JavaProject2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] numArray = new int[10];
int d = 0;
System.out.println("Enter Ten Numbers: ");
for(int i = 0; i < numArray.length; i++){
int num = input.nextInt();
if(inArray(numArray,num,numArray.length)){
numArray[i] = num;
d++;
}
}
System.out.println("The number of distinct numbers is " + d);
System.out.print("The distinct numbers are: ");
for(int i = 0; i < d; i++){
System.out.print(numArray[i] + " ");
}
}
public static boolean inArray(int[] array, int searchval, int numvals){
for (int i =0; i < numvals; i++){
if (searchval == array[i]) return false;
}
return true;
}
}
You can use a set to identify distinct values:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Set<Integer> distinctNumbers = new LinkedHashSet<>();
System.out.println("Enter ten Numbers: ");
for (int i = 0; i < 10; i++) {
int number = input.nextInt();
distinctNumbers.add(number);
}
System.out.println("The number of distinct numbers is " + distinctNumbers.size());
System.out.print("The distinct numbers are: ");
for (Integer number : distinctNumbers){
System.out.print(number + " ");
}
}
If a value already exists in a set, it can't be added again. Arrays are not the best fit for your problem, since they must be initialized with a fixed size and you don't know how many distinct values the user will inform.
Take a look at numArray after int[] numArray = new int[10]; - it is initialized with zeros.
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.