package practiceit;
import java.util.Scanner;
public class numbers {
public static void main (String[]args) {
int max=0;
int min = 0;
}
public static int smallestLargest() {
Scanner console= new Scanner(System.in);
System.out.print("how many numbers do you want to enter?");
int num= console.nextInt();
for (int i=1; i<=num; i++) {
int nums =console.nextInt();
System.out.println("Number "+i+": "+nums);
}
return nums;
}
}
How can I return nums so that it is stored as both a max and min variable, so I can print the highest and lowest value typed by the user?
So something like this?
import java.util.Scanner;
public class numbers
{
public static void main(String[] args)
{
int min = 0, max = 0, current, nums;
Scanner scan = new Scanner(System.in);
System.out.println("How many numbers do you want to enter: ");
nums = scan.nextInt();
for(int i = 0; i < nums; i++)
{
current = scan.nextInt();
if(i == 0)
{
min = current;
max = current;
}
if(current < min)
min = current;
if(max < current)
max = current;
}
//after the loop you should have the max and min value the user entered.
System.out.println("The max number is: "+max);
System.out.println("The min number is: "+min);
scan.close();
}
}
You will have all the value in array
package practiceit;
import java.util.Scanner;
public class numbers {
int[] array = null;
public static void main (String[]args) {
int max=0;
int min = 0;
}
public static int smallestLargest() {
Scanner console= new Scanner(System.in);
System.out.print("how many numbers do you want to enter?");
int num= console.nextInt();
array[] = new int[num];
for (int i=1; i<=num; i++) {
int nums =console.nextInt();
System.out.println("Number "+i+": "+nums);
array [i]= nums;
}
return nums;
}
}
If you use Array.sort(array); you will have sorted array and it will be easy to read minimum and maximum value
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I tried by creating two functions for greatest and smallest values and then subtracting them .but the code doesn't seem to work
here's the code.See if u could help me out .im new to java and still learning.
import java.io.*;
import java.util.*;
public class Main{
public static void smler(int arr[],int j){
for (int i=0;i<=j;j++){
if(arr[i]<arr[i+1]){
int temp =arr[i];
arr[i]=arr[i+1];
arr[i+1]=temp;
}
}
}
public static void grter(int arr[],int j){
for (int i=0;i<=j;j++){
if(arr[i]>arr[i+1]){
int temp =arr[i];
arr[i]=arr[i+1];
arr[i+1]=temp;
}
}
}
public static void main(String[] args) throws Exception {
Scanner sc= new Scanner (System.in);
int n=sc.nextInt();
int[] arr= new int[n];
for(int i=0;i<=n;i++){
arr[i]=sc.nextInt();
}
grter(arr,n);
int y= arr[n];
smler(arr,n);
int z = arr[n];
System.out.println(y-z);
}
}
There are a lot of errors in your logic.
The for loop does not need to be <= it needs to be < otherwise you will get out of bounds exception.
The way you are calculating the min and max are wrong.
Here is an example for you to study that does what you are trying to accomplish:
import java.util.Scanner;
public class ArraySpan {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter array size:");
int n = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
System.out.println("Enter value:");
arr[i] = sc.nextInt();
}
int min = findMin(arr);
int max = findMax(arr);
System.out.println("The span of the array = " + (max - min));
sc.close();
}
static int findMax(int[] a) {
int max = Integer.MIN_VALUE;
for (int i = 0; i < a.length; i++) {
if (a[i] > max)
max = a[i];
}
return max;
}
static int findMin(int[] a) {
int min = Integer.MAX_VALUE;
for (int i = 0; i < a.length; i++) {
if (a[i] < min)
min = a[i];
}
return min;
}
}
and output:
Enter array size:
3
Enter value:
1
Enter value:
2
Enter value:
3
The span of the array = 2
It would better if you could look for complexity improvement.
Idea is to get the max and the min in best possible way and this can be achieved using any sorting techniques, let us assume your sort method runs in O(n log n) time, and then you just need to get the difference of 1st element(0 th index) and last element(n-1 th index).
public static void main(String[] args) throws Exception {
Scanner sc= new Scanner (System.in);
int n=sc.nextInt();
int[] arr= new int[n];
// insert values into your array
if(arr.length >= 2){
sort(arr); // Implement your any sorting method
// Make sure that your arr has exactly n elements, ,
// Otherwise rest of the indices will all be zero(0)
System.out.println(arr[0]-arr[arr.length-1]); // last index is 'arr.length-1'
return; // Return from here
}
// arr has not sufficient elements to determine span
throw new UnsupportedOperationException("Invalid entry");
}
}
Index starts from 0 and it goes till n-1.
So, the condition in for-loop should be i<n instead of i<=n,for(int i=0;i<n;i++).
You have created 2 functions but it doesn't return any value nor changes anything. As you are passing the array by value, not by references.
You don't need the 2 functions, just one for finding max and min in linear, or sort the array in ascending order and array[0] will be the min and array[n-1] will be max.
There is an approach very similar to what you want to do.
import java.io.*;
import java.util.*;
public class Main{
public static int smler(int arr[],int N){
int smaller = arr[0];
for (int i=1;i<N;i++){
if(arr[i] < smaller){
smaller = arr[i];
}
}
return smaller;
}
public static int grter(int arr[],int N){
int greater = arr[0];
for (int i=0;i<N;i++){
if(arr[i] > greater){
greater = arr[i];
}
}
return greater;
}
public static void main(String[] args) throws Exception {
Scanner sc= new Scanner (System.in);
int n=sc.nextInt();
int[] arr= new int[n];
for(int i=0;i<=n;i++){
arr[i]=sc.nextInt();
}
System.out.println(grter(arr, n) - smler(arr, n));
}
}
import java.util.Scanner;
public class sumAverageUsingArray {
public static void main(String[] args) {
/**
* LargestValue
*/
final int LENGTH = 5;
int[] values = new int[LENGTH];
int currentSize = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter values and Q to Quit");
while (sc.hasNextInt() && currentSize < values.length) {
values[currentSize] = sc.nextInt();
currentSize++;
}
sc.close();
int largest = values[0];
for (int i = 1; i < currentSize; i++) {
if (values[i] > largest) {
largest = values[i];
}
}
System.out.printf("Largest is : %d", largest);
}
Expected:
5,4,3,2,1
Largest is : 5
Actual:
6,5,4,3,2,1
Largest is : 6
Scanner class takes an extra input which has no effect on the behavior of the program, how to fix it?
Replace
while (sc.hasNextInt() && currentSize < values.length) {
by
while (currentSize < values.length && sc.hasNextInt()) {
hasNextInt() is forced to block until you enter something to know if... there is a next int or not. If you enter an int, it can return true. If you enter something else, it can return false. If you don't enter enything, it needs to wait until you enter something to know what to return.
This is a tool that you could use to generate an order for positions in any circumstance.
However, I am encountering infinite loops. How can I fix this?
import java.util.Random;
import java.util.Scanner;
public class WhoGoesFirst {
public static void main(String args[]) {
Random random = new Random();
Scanner input = new Scanner(System.in);
int MIN = 1;
int students = 0;
System.out.print("How many students do you have?");
students = input.nextInt();
int comp = random.nextInt(students - MIN + 1) + MIN;
for (int number = 0; number <= students; comp++) {
System.out.println(random);
}
}
}
Increment your number variable in the loop and it should fix the issue:
for (int number = 0; number <= students; number++, comp++) {
System.out.println(comp); //random is an object
}
You need to increment number:
import java.util.Random;
import java.util.Scanner;
public class WhoGoesFirst {
public static void main(String args[]) {
Random random = new Random();
Scanner input = new Scanner(System.in);
int MIN = 1;
int students = 0;
System.out.print("How many students do you have?");
students = input.nextInt();
int comp = random.nextInt(students - MIN + 1) + MIN;
for (int number = 0; number <= students; number++) {
System.out.println(random);
comp++;
}
}
}
Look at this line:
System.out.println(random);
This implementation is trying to print the random number generator, not the numbers themselves. There is a much easier solution, using the built-in Collections.shuffle:
List<Integer> positions = new ArrayList<Integer>(students);
for (int number = 0; number < students; number++)
positions.add(number);
Collections.shuffle(positions);
for (Integer number : positions)
System.out.println(number);
Question :
Write a program that allows the entry of an integer value n, followed by two sets of n integer values into arrays A and B. The program should use a function to calculate the sum of the square of corresponding values of A and B. These values should then be displayed.
My piece of code :
import java.util.Scanner;
public class Question9_SumOfSquareInArrays {
public static void main(String[] args) {
int sumA = 0;
int sumB = 0;
int n;
int i=0;
Scanner src=new Scanner(System.in);
System.out.print("Please enter value :");
n=src.nextInt();
int [] A=new int[n];
int [] B=new int[n];
System.out.println("Enter value for array A :");
for(i=0;i<n;i++)
{
A[i]=src.nextInt();
}
System.out.println("Enter value for array B :");
for(i=0;i<n;i++)
{
B[i]=src.nextInt();
}
src.close();
System.out.println("Total sum for array A is " + SumOfA(sumA));
System.out.println("Total sum for array B is " + sumOfB(sumB));
}
public static int SumOfA(int sumA)
{
int square=1;
int sum=0;
int n=6;
int [] A= new int[n];
for(int i=0;i<n;i++)
{
square=A[i]*A[i];
sum+=square;
}
return sum;
}
public static int sumOfB(int sumB)
{
int square=1;
int n=6;
int sum=0;
int [] B=new int [n];
for(int i=0;i<n;i++)
{
square=B[i]*B[i];
sum+=square;
}
return sum;
}
}
I am not able to find out my mistakes. Can someone please help me?
public static int SumOfA(int sumA)
{
int square=1;
int sum=0;
int n=6;
int [] A= new int[n]; // you are calculating the sum of this array
for(int i=0;i<n;i++)
{
square=A[i]*A[i];
sum+=square;
}
return sum;
}
is problematic because it calculates the sum of an array of 0s.
Instead, you need to pass your array to the method, i.e.
in main you need
System.out.println("Total sum for array A is " + SumOfA(A));
and modify your SumOfA as follows. Notice it's better to use n = A.length since the length of A is not necessarily always 6.
public static int SumOfA(int[] A)
{
int square=1;
int sum=0;
int n=A.length; // use length to handle array A of any length
for(int i=0;i<n;i++)
{
square=A[i]*A[i];
sum+=square;
}
return sum;
}
The other method has the same problem
I'm new to Java programming and I want to know how to swap the position of the highest number and the lowest number.
import java.util.*;
public class HighestandLowestNum
{
static Scanner data = new Scanner (System.in);
public static void main(String[]args)
{
int num [] = new int [10];
int i;
System.out.println("Enter 10 numbers: ");
for (i = 0; i < num.length; i++)
{
num [i] = data.nextInt();
Highest(num);
Lowest(num);
}
System.out.println("The highest number is: " + Highest(num));
System.out.println("The lowest number is: " + Lowest(num));
}
public static int Highest(int[] num)
{
int highest = num[0];
int i;
for (i = 1; i < num.length; i++)
{
if (num[i] > highest)
{
highest = num[i];
}
}
return highest;
}
public static int Lowest(int[] num)
{
int lowest = num[0];
int i;
for (i = 1; i < num.length; i++)
{
if (num[i] < lowest)
{
lowest = num[i];
}
}
return lowest;
}
}
This is my program. Please help me to fix my problem.
Your two functions Highest and Lowest return the value of the highest and lowest numbers. In order to swap them, you need to know the positions those values have within the array.
If you alter those functions or create new ones to return the index of the highest and lowest values, then you can swap them with what you've probably already seen before:
pseudocode:
temp = first
first = last
last = temp
To Swap the two numbers in the array, you need to know the numbers and their position as mentioned in the earlier answers. You can modify the two functions in such a way that they provide Numbers as well as their Position. One way to do this is to return an array instead of integer from the function. And in that array, information about the number and its position can be encapsulated. Ill show you what I mean in the code I am providing:
static Scanner data = new Scanner (System.in);
public static void main(String[]args)
{
int num []= new int [10];
int i;
System.out.println("Enter 10 numbers: ");
for (i = 0; i <num.length; i++)
{
num [i] = data.nextInt();
Highest(num);
Lowest(num);
}
System.out.print("The original array is");
for (i = 0; i <num.length; i++)
{
System.out.print(" "+num[i]);
}
System.out.println("");
int highest = Highest(num)[0];
int lowest = Lowest(num)[0];
int highestPosition = Highest(num)[1];
int lowestPosition = Lowest(num)[1];
System.out.println("The highest number is: " +highest+" at position "+highestPosition);
System.out.println("The lowest number is: " +lowest+" at position "+lowestPosition);
//Swap//
num[highestPosition] = lowest;
num[lowestPosition] = highest;
System.out.print("The new array is");
for (i = 0; i <num.length; i++)
{
System.out.print(" "+num[i]);
}
}
public static int[] Highest(int[] num)
{
int highest = num[0];
int i;
int index = 0;
int[] result = {highest,index};
for (i = 1; i <num.length;i++)
{
if (num[i] > highest)
{
highest = num[i];
index = i;
result[0] = highest;
result[1] = index;
}
}
return result;
}
public static int[] Lowest(int[] num)
{
int lowest = num[0];
int i;
int index = 0;
int[] result = {lowest,index};
for (i = 1; i <num.length;i++)
{
if (num[i] < lowest)
{
lowest = num[i];
index = i;
result[0] = lowest;
result[1] = index;
}
}
return result;
}
Try reading the modification in the Highest and Lowest functions and than go through the main code. Hope this helps.