Java array , print what is stored in the array [duplicate] - java

This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 6 years ago.
How do I print what is stored in the array in an easy way. I have been staring at this for the past 3 hours!
import java.util.Scanner;
public class December2012 {
public static void main(String[] args) {
int[] array = new int[100];
int sum = 0;
int i = 0;
Scanner input = new Scanner(System.in);
while (sum <= 100 && i < array.length) {
System.out.print("Write in the " + (i + 1) + "th number: ");
array[i] = input.nextInt();
sum += array[i];
i++;
}
System.out.print("You added: ");
System.out.print(array[i] + " ");
System.out.println("\nsum is " + sum);
}
}

The easiest way is
System.out.println(Arrays.toString(array));

Just for the record you could also use the new for-each loop
for(int no : array ) {
System.out.println(no);
}

you can do like this
for(int j= 0 ; j<array.length;j++) {
System.out.println(array[j]);
}
or
for (int j: array) {
System.out.println(j);
}

for (int i = 0 ; i < array.length; i++){
System.out.println("Value "+i+"="+array[i]);
}
thats all my friend :)

Related

How to find second highest number in array in java [duplicate]

This question already has answers here:
Finding the second highest number in array
(45 answers)
Closed 3 years ago.
I want to find second highest number in array in java.
I tied to solve problem from this code.
class Example{
public static void main(String args[]){
Scanner input=new Scanner(System.in);
//Random r=new Random();
int max=0;
int secondMax = 0;
for(int i=0; i<10; i++){
System.out.print("Input an integer : ");
int num = input.nextInt();
if (num>max)
{
secondMax=max;
max=num;
}
}
System.out.println("Max number is : "+max);
System.out.println("Second Max number is : "+secondMax);
}
}
You're trying to find the max and second values while populating the array. Try removing
if (num>max)
{
secondMax=max;
max=num;
}
from the for loop. Then add a separate (not nested) for loop to search the array:
for (int i = 0; i < 10; i++){
if (input[i] > max){
secondMax = max;
max = input[i];
}
if ((input[i] < max) && (input[i] > secondMax))
secondMax = input[i];
}
import java.util.*;
class Example{
public static void main(String args[]){
Scanner input=new Scanner(System.in);
int []numbers=new int[10];
for (int i = 0; i <10 ; i++)
{
System.out.print("Input an integer: ");
numbers[i]=input.nextInt();
}
int max=0;
int secondHighest=0;
for (int i = 0; i < numbers.length; i++)
{
if (numbers[i]>max)
{
secondHighest=max;
max=numbers[i];
}
if (numbers[i]<max && numbers[i]>=secondHighest )
{
secondHighest=numbers[i];
}
}
System.out.println("Max number is : "+max);
System.out.println("Second highest number is : "+secondHighest);
}
}

Printing array elements with a for loop

This is a challenge question from my online textbook I can only get the numbers to prin forward... :(
Write a for loop to print all elements in courseGrades, following each element with a space (including the last). Print forwards, then backwards. End each loop with a newline.
Ex: If courseGrades = {7, 9, 11, 10}, print:
7 9 11 10
10 11 9 7
Hint: Use two for loops. Second loop starts with i = NUM_VALS - 1.
Note: These activities may test code with different test values. This activity will perform two tests, the first with a 4-element array (int courseGrades[4]), the second with a 2-element array (int courseGrades[2]).
import java.util.Scanner;
public class CourseGradePrinter {
public static void main (String [] args) {
final int NUM_VALS = 4;
int[] courseGrades = new int[NUM_VALS];
int i = 0;
courseGrades[0] = 7;
courseGrades[1] = 9;
courseGrades[2] = 11;
courseGrades[3] = 10;
/* Your solution goes here */
for(i=0; i<NUM_VALS; i++){
System.out.print(courseGrades[i] + " ");
}
for(i=NUM_VALS -1; i>3; i++){
System.out.print(courseGrades[i]+ " ");
}
return;
}
}
This is the code to answer the question from zyBooks, 6.2.3: Printing array elements with a for loop.
for (i = 0; i < NUM_VALS; i++) {
System.out.print(courseGrades[i] + " ");
}
System.out.println("");
for (i = NUM_VALS - 1; i >= 0; i--) {
System.out.print(courseGrades[i] + " ");
}
System.out.println("");
Your two loops almost were correct. Try using this code:
for (int i=0; i < NUM_VALS; i++) {
// this if statement avoids printing a trailing space at the end.
if (i > 0) {
System.out.print(" ");
}
System.out.print(courseGrades[i]);
}
for (int i=NUM_VALS-1; i >= 0; i--) {
if (i > 0) {
System.out.print(" ");
}
System.out.print(courseGrades[i] + " ");
}
To print backwards you want:
for(i = NUM_VALS - 1; i >= 0; i--) {
System.out.print(courseGrades[i] + " ");
}
// To end with a newline
System.out.println("");
I also have been working on the this textbook question. The issue with the above code is that i has already been assigned, so trying using int in the for loop will cause an error. Below is the code I used to successfully achieve the desired outcome.
for ( i = 0 ; i <NUM_VALS; ++i) {
if (i > 0) {
System.out.print("");
}
System.out.print(courseGrades[i] + " ");
}
System.out.println("");
for ( i = NUM_VALS -1; i >=0; --i) {
if (i > 0) {
System.out.print("");
}
System.out.print( courseGrades[i] + " ");
}
System.out.println();

Displaying odd values in an array

I am trying to display the odd numbers in an array, but only once per number (i.e. numbers[3] = 3,3,1; would only display 3 and 1 instead of 3, 3 and 1.)
this is the code that I have as of now, the program completely will create an with the specific length entered by the user and then will calculate the max min, and odd values in the array.
import java.util.Scanner;
public class ArrayLab
{
static Scanner input = new Scanner (System.in);
public static void main(String[] args)
{
System.out.println("Enter the number of numbers: ");
final int NUMBER_OF_ELEMENTS = input.nextInt();
double[] numbers = new double[NUMBER_OF_ELEMENTS];
System.out.println("Enter the numbers: ");
for (int i = 0; i < NUMBER_OF_ELEMENTS; i++)
{
numbers[i] = input.nextDouble();
}
input.close();
double max = numbers[0];
double min = numbers[0];
for (int i = 0; i < NUMBER_OF_ELEMENTS; i++)
{
if (numbers[i] > max)
{
max = numbers[i];
}
}
System.out.println("The max is: " + max);
for (int i = 0; i < NUMBER_OF_ELEMENTS; i++)
{
if (numbers[i] < min)
{
min = numbers[i];
}
}
System.out.println("The min is: " + min);
for (int i = 0; i < NUMBER_OF_ELEMENTS; i++)
{
if (numbers[i] % 2 != 0)
{
System.out.println ("The odd numbers are: " + numbers[i]);
}
}
}
}
thanks for any help.
Set<Integer> set = new HashSet<Integer>();
for (int i = 0; i < NUMBER_OF_ELEMENTS; i++)
{
if (numbers[i] % 2 != 0)
{
set.add(numbers[i]);
}
}
System.out.println ("The odd numbers are: " +set);
This can be done a lot simpler using Java8:
double[] d = Arrays.toStream(numbers).filter(d -> (d % 2) == 1).distinct().toArray();
for(double tmp : d)
System.out.println(tmp);
System.out.println("min: " + Arrays.toStream(numbers).min((a , b) -> new Double(a).compareTo(b)));
System.out.println("max: " + Arrays.toStream(numbers).max((a , b) -> (new Double(a).compareTo(b))));
For you're solution: you never eliminate repeating numbers, thus the duplicates remain in the array until you print all odd numbers and the maximum-number.
This elimination can be done in several ways:
Using Java8 as above
add all values to a Set, since these don't allow duplicate values
eliminate them in your own way (i won't provide any code for this since it's rather complicated to design an efficient solution for this)
Updated solution for what you need. And Please use a better coding standard. Do note the condition check !oddNumbers.contains(numbers[i]) is not very necessary as HashSet never takes any duplicate values.
import java.util.HashSet;
import java.util.Scanner;
public class ArrayLab {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Enter the number of numbers: ");
final int NUMBER_OF_ELEMENTS = input.nextInt();
double[] numbers = new double[NUMBER_OF_ELEMENTS];
System.out.println("Enter the numbers: ");
for (int i = 0; i < NUMBER_OF_ELEMENTS; i++) {
numbers[i] = input.nextDouble();
}
input.close();
HashSet<Double> oddNumbers = new HashSet<Double>(NUMBER_OF_ELEMENTS);
double max = numbers[0];
double min = numbers[0];
for (int i = 0; i < NUMBER_OF_ELEMENTS; i++) {
if (numbers[i] > max) {
max = numbers[i];
}
if (numbers[i] < min) {
min = numbers[i];
}
if (numbers[i] % 2 != 0 && !oddNumbers.contains(numbers[i])) {
oddNumbers.add(numbers[i]);
}
}
System.out.println("The max is: " + max);
System.out.println("The min is: " + min);
System.out.println("The odd numbers are: " + oddNumbers);
}
}
A more meaningful solution to your approach would be as follows:
int[] tempArray; //temporary array to store values from your original "array"
int count=0;
for(int i=0; i<numbers.length; i++) {
if(numbers[i]%2 != 0) {
count++;
}
}
tempArray = new int[count]; //initializing array of size equals to number of odd digits in your array
int j = 0;
for(int i=0; i<numbers.length; i++) {
boolean check = true;
for(int k=0; k<j; k++) {
if(tempArray[k] == numbers[i]) {
check = false; //this will prevent duplication of odd numbers
}
}
if(numbers[i]%2 != 0 && check) {
tempArray[j]=numbers[i];
j++;
}
}
//Now print the tempArray which contains all the odd numbers without repetition
A few people have mentioned sets, but there is a different way as well. Simply sort the array, then scan through it, checking each number against the last one printed. i.e.,
int lastPrinted = 0;
// Sort the array
Arrays.sort(numbers);
System.out.print("The odd numbers are: ");
// Scan through the array
for (int i = 0; i < NUMBER_OF_ELEMENTS; i++)
{
// if it's odd and doesn't match the last one...
if (numbers[i] % 2 != 0 && numbers[i] != lastPrinted)
{
// ...print it and update lastPrinted
System.out.print( "" + numbers[i] );
lastPrinted = numbers[i];
}
}
System.out.println("");
As a side note, you really don't have to scan through the array twice to find your max and min, you can do that in one go.
I think you can use inbuilt hashmap class and its method to achieve the task without affecting the complexity of algorithm to any great extent .
import java.util.HashMap;
public class Hashing {
public static void main(String[] args) {
//declare a new hasmap
HashMap<Integer, Integer> map = new HashMap<>();
//consider Arr as your Array
int Arr[] = {3,3,1,4,5,5,7,8};
//traverse through the array
for(int i=0;i<Arr.length;i++){
//check if the required condition is true
if(Arr[i]%2==1){
/*now we insert the elements in the map but before
that we have to make sure that we don't insert duplicate values*/
if(!map.containsKey(Arr[i])){// this would not affect the complexity of Algorithm since we are using hashMap
map.put(Arr[i], Arr[i]);//We are storing the Element as KEY and as VALUE in the map
}
}
}
//now We can get these element back from map by using the following statement
Integer[] newArray = map.values().toArray(new Integer[0]);
//All the required elements are now present in newArray
for(int ele:newArray){
System.out.println(ele);
}
}
}

Sum of the distincts Extended Description

I have an addition program:
import java.io.*;
public class sum
{
int num;
int sum = 0;
int result;
public void findsum() throws IOException
{
BufferedReader Br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("enter the value for N : ");
num = Integer.parseInt(Br.readLine());
int nums[] = new int[num+1];
for(int i = 1; i <= num; i++)
{
System.out.print("\n Enter " + i + " number: ");
nums[i]= Integer.parseInt(Br.readLine());
sum = sum + nums[i];
}
System.out.print("\n Sum is : " + sum );
}
public static void main(String args[]) throws IOException
{
sum sm = new sum();
sm.findsum();
}
}
Output:
It takes N Integer values as input from the user and returns sum of those N numbers.
But I want if any of the number is equal to the other one it will automatically ignore them in addition.
Just verify if the input number isn't in the array yet.
Change your for loop with this and it will work fine:
for (int i = 1; i <= num; i++) {
System.out.print("\n Enter the " + i + " number : ");
int x = Integer.parseInt(Br.readLine());
int j=0;
while(j<num && nums[j]!=x) {
j++;
}
if(j>=num) {
nums[i] = x;
}
sum = sum + nums[i];
}
From your question
i want if any of the number is equal to the other one it will
automatically ignore them in addition
It will easy if you use Set here
Set<Integer> numbers=new HashSet<>();
for(int i = 1;i<=num;i++){
System.out.print("\n Enter " + i + " number : ");
numbers.add(Integer.parseInt(Br.readLine())); // add to set
}
Now duplicate values not consider. Then simply add elements in the Set.
There are couple of issues:
Your for loop starts with 1 and the index of array that you used is nums[i] which means your array will start with 1. Array start with 0th index so used i-1 when you are referring index in for loop for your array or use loop starting from 0 till n-1.
If you want to stick with your implementation with Array then in every for loop, before doing the sum you need to iterate over each earlier element to check if element already exist in an array something like:
numberFound = false;
for (int j = 1; j < i; j++) {
if (nums[j - 1] == nums[i - 1]) {
numberFound = true;
System.out.println("Duplicate number " + nums[i - 1]
+ " will be ignored");
break;
}
}
if (!numberFound) {
sum = sum + nums[i - 1];
}
Use Set to remove redundancy
Set<Integer> num = new HashSet<Integer>();
num.add(123);
num.add(123);
num.add(1);
num.add(1);
Integer sum=0;
for(Object a: num.toArray()){
sum+=(Integer)a;
}
System.out.println(sum); //124
When using Java 8 you can let the Stream API do the work:
Stream#distinct()
From the JavaDoc:
Returns a stream consisting of the distinct elements (according to Object.equals(Object)) of this stream.
How to use:
final int[] nums = new int[] {1, 2, 2, 3, 4, 4, 4};
final int sum = IntStream.of(nums)
.distinct()
.sum();
System.out.println(sum); // prints 10 (1 + 2 + 3 + 4);

Java - Adjacent comparing and calculating frequency of words [duplicate]

This question already has answers here:
Calculating frequency of each word in a sentence in java
(20 answers)
Closed 9 years ago.
I have a already sorted string array named arr and Supposing I enter the sentence
hello how hello to how me in
Desired Output is
hello 2
how 2
me 1
in 1
to 1
Here's how I am trying to count it
int counter = 1;
for(j1 = 0; j1 < arr.length; j1++){
if(j1 + 1 < arr.length){
if(arr[j1].equals(arr[j1 + 1])){
counter++;
} else {
System.out.println(arr[j1] + " " + counter);
counter = 1;
}
}
}
but this is not working , please help?
The problem is the line:
if(j1 + 1 < arr.length) {...}
You are not iterating over the whole array; the last element is left uncounted.
Without explaining to much, this could be a quick fix:
public static void main(String[] args) {
String[] arr = { "hello", "how", "hello", "to", "how", "me", "in" };
Arrays.sort(arr);
int counter = 1;
for (int j1 = 0; j1 < arr.length; j1++) {
int j2 = j1 + 1;
String next = (j2 < arr.length) ? arr[j2] : null;
if (arr[j1].equals(next)) {
counter++;
} else {
System.out.println(arr[j1] + " " + counter);
counter = 1;
}
}
}

Categories

Resources