I have gotten 10 values from the user, and I am suppose to put that into an array and call it into a method, and then call another method which contains an array that reverses the integers of the first array without using global variables. For example, the user gives me values 1,2,3, etc.. and I store that in the first array, then in the second array I output 3,2,1.
I have part of the code that gets the integers from the user, but I don't know how to reverse the array without using global variables. The code doesn't run when it gets to the second method at values[i];
Here is what I have so far:
public static void main(String[] args) {
getInput();
reverseInput();
System.exit(0);
}
public static void getInput() {
Scanner keyboard = new Scanner(System.in);
int[] values;
values = new int[10];
//Ask the user to enter 10 integers
System.out.println("Please enter ten numbers.");
for (int i = 0; i<values.length; i++) {//for loop to display the values entered
values[i] = keyboard.nextInt();
System.out.println("Value" + (i +1) + " is " + values[i]);
}
}
public static void reverseInput() {
System.out.println("Now we are going to reverse the numbers.");
Scanner keyboard = new Scanner(System.in);
int [] values;
values = new int[10];
for (int i = (values.length -1); i>= 0; i--) {//for loop to display integers in reversed order
values[i];
System.out.println(values[i]);
}
}
First, if you are not going to be using global variables, then you will need to pass the array from the get input method to the reverseInput method. Something like this:
int[] values = getInput();
reverseInput(values);
Then to output the array in your reverseInput method, it would have to look like this:
public static void reverseInput(int[] values) {
for(int i = (values.length - 1); i >= 0; i--){
System.out.println(values[i]);
}
}
You can use the ArrayUtils.reverse from Commons Lang:
ArrayUtils.reverse(values);
Ok, you understand how to display the elements in reference order. As you wrote:
for (int i = (values.length - 1); i >= 0; i--) {
System.out.println(values[i]);
}
So given that, how would you put the elements of values (say it has 5 elements) in another array (call it reversedValues) such that values[4] was put into reversedValues[0] and so on up to values[0] being put into reversedValues[4]?
use the "getInput" as basis to get the 10 numbers, then after the "for" loop, just do another for loop in reverse
public static void reverseInput()
{
Scanner keyboard = new Scanner(System.in);
int[] values;
values = new int[10];
//Ask the user to enter 10 integers
System.out.println("Please enter ten numbers, we are going to reverse the numbers");
for (int i = 0; i<values.length; i++) //for loop to display the values entered
{
values[i] = keyboard.nextInt();
};
int[] revValues;
revValues = new int[10];
for (int i = (values.length -1); i>= 0; i--) //for loop to display integers in reversed order
{
revValues[ revValues.length -1 -i ] = values[ i ];
System.out.println( revValues[ i ] );
}
}
Related
I am supposed to write a program that accepts 6 user inputs and display numbers less than 3. I don't know what the problem is and I can't find help anywhere.
public class Apples {
public static void main(String [] args{
double [] numList = new double [6];
Scanner scan = new Scanner(System. in);
for (int i = 0; i<6; i++){
numList[i]=scan.nextDouble(); //user input
}
Arrays.sort(numList[i]); //sort user input
for (numList < 3)
System.out.println(numList);
}
}
}
I would to something like this:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
for(int i=0; i<6; i++) {
double number = scan.nextDouble();
if(number < 3.0) {
System.out.println(number);
}
}
}
So:
If it's just about printing, you don't need to store in an array the numbers, that you get from input.
You don't need sorting, you can just check if the number that you have currently scanned is smaller than 3 (or double 3.0).
The for(numList < 3) is not a correct Java syntax. You probably meant if(number < 3)
This may be due to copy/paste but there where quite some problems, let me show you one solution:
public static void main(String [] args){
double [] numList = new double [6];
Scanner scan = new Scanner(System. in);
// until here everything is fine
for (int i = 0; i<numList.length; i++){ // just a hint: use the array's length. Maybe you want to change the array one day and add 20 numbers to it..
numList[i]=scan.nextDouble(); // you forgot the . and it is called nextDouble() (capital D)
}
Arrays.sort(numList); // sorting is fine, just make sure you sort the whole array (not just one element)
for (int i = 0; i<numList.length; i++){ // here I assume you want to print every element smaller than 3, so you still need to iterate over the whole array (maybe the user inputs only twos
if(numList[i]<3){ // test if the number is smaller than 3
System.out.println(numList[i]); // and print it
}
}
}
if however you want to print only the 3 smallest elements of the array, then your approach was correct (though you still need to write out the whole for conditions:
for(int i=0; i<3;i++){
System.out.println(numList[i]);
}
The last for doesn't work like that. With a for you can iterate trough numbers like you did in the first one or through lists/arrays.
I didn't understood if you wanted the smallest 3 or the ones smaller than 3.
If you want the smallest 3 you can do this:
double smallList[] = new double[3]
for (int i=0;i<3;i++) {
smallList[i] = numList[i];
}
or if you want to print it one by one:
for (int i=0;i<3;i++) {
System.out.println(numList[i]);
}
if you want the ones that are smaller than 3 you'll have to do:
for (int i=0;i<numList.length;i++) {
if (numList[i]<3) {
System.out.println(numList[i]);
}
}
Two ways of printing them out.
double[] numList = new double[6];
Scanner scan = new Scanner(System.in);
for (int i = 0; i < 6; i++) {
numList[i] = scan.nextDouble(); // user input
}
// then do
Arrays.stream(numList).filter(a -> a < 3).forEach(System.out::println);
// or
for (double n : numList) {
if (n < 3) {
System.out.println(n);
}
}
So, I have a very messy code. The purpose of the code is to find the minimum and maximum values of a set of numbers that the user entered using arrays. The problem is I don't know how to put the Array elements (Elements) into my array (numbersArray). Here's what I have so far :
package com.company;
import java.util.*;
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Main {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner elements = new Scanner(System.in);
System.out.println("Enter in number of numbers:");
String num = elements.nextLine();
int numArrayElements = Integer.parseInt(num);
System.out.println("Enter in numbers please: ");
Scanner console = new Scanner(System.in);
String userInput = console.nextLine();
int Elements = Integer.parseInt(userInput);
int [] numbersArray = new int[numArrayElements];
int sum = 0;
for (int i = 0 ; i < numbersArray.length ; i++) {
int temp = numArrayElements.nextInt();
numbersArray[i] = temp;
sum += temp;
}
Arrays.sort(numbersArray);
System.out.println((sum - numbersArray[numbersArray.length-1])
+ " " + (sum - numbersArray[0]));
}
}
How can I make it so that I can put Elements into numbersArray?
Your major problem is the part where you try to read values entered by the user:
for (int i = 0 ; i < numbersArray.length ; i++) {
int temp = numArrayElements.nextInt();
...
}
The variable numArrayElements is of type int, you can't call a method nextInt on it, it does not exist.
The method, however, exists for objects of type Scanner, like your elements variable.
After that your code probably compiles and does something useful. At least you set the array items correctly by using
numbersArray[i] = temp;
I'm not that sure about the min/max part though. I don't get why you need the sum if you sort the array. After sorting you can just take the first (min) and last element (max) given by numbersArray[0] and numbersArray[numbersArray.length - 1].
And I'm not sure why you do the parsing stuff in between, does not seem necessary. Same holds for the second scanner, not needed since you already have one.
Let me show you a cleaner approach.
Scanner scanner = new Scanner(System.in);
// Amount of values
System.out.println("Enter amount of values:");
int amount = scanner.nextInt();
// Read values
System.out.println("Enter " + amount + " values:");
int[] values = new int[amount];
for (int i = 0; i < values.length; i++) {
values[i] = scanner.nextInt();
}
// Compute max and min
...
For the last part you have several options. The most efficient would probably be to remember it already at the moment where you read the values. Your sorting approach works too, but is much more work than needed since you don't need the order of all elements, you only need the min and max element.
Let's first do a manual approach
// Compute max and min
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
for (int value : values) {
if (value > max) {
max = value;
}
if (value < min) {
min = value;
}
}
The second approach uses a built-in method which essentially does the same. However, it is less efficient since we will first need to built a Collection on top of the array and then do two iterations instead of only one (one for max, one for min). Also, due to the conversion we need wrapper objects Integer instead of primitive values int.
// Compute max and min
Collection<Integer> valuesAsColl = Arrays.asList(values);
int max = Collections.max(valuesAsColl);
int min = Collections.min(valuesAsColl);
The third approach uses the Java Stream API (since Java 8), looks elegant and does not need to convert stuff to Integer or Collection. But the two iterations instead of one remain.
// Compute max and min
int max = Arrays.stream(values).max();
int min = Arrays.stream(values).min();
I not understand your ask .. however this code for set array size from user and numbers of array by user..
public class JavaApplication2 {
public static int[] numbers() {
Scanner element = new Scanner(System.in);
System.out.print("please insert array long : ");
int count = element.nextInt();
System.out.print("enter numers : ");
element.nextLine(); // throw away the newline.
int [] numbers = new int[count];
Scanner numScanner = new Scanner(element.nextLine());
for (int i = 0; i < count; i++) {
if (numScanner.hasNextInt()) {
numbers[i] = numScanner.nextInt();
} else {
System.out.println("You didn't provide enough numbers");
break;
}
}
return numbers;
}
public static void main(String[] args) {
int[] numbersa = numbers();
System.out.println(Arrays.toString(numbersa));
}
}
This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 6 years ago.
I'm using this code:
import java.util.Scanner;
import java.util.Arrays;
import java.util.Random;
public class Matrix
{
public static void main(String[] args)
{
Scanner enter = new Scanner(System.in);
int[][] firstMatrix = new int[4][4];
int[][] secondMatrix = new int[4][4];
Random spin = new Random();
System.out.println("Please enter 16 numbers to populate the array: ");
for (int count = 0; count<firstMatrix.length;count++) // nested for for user input to populate 4x4 array
{
for (int count2 = 0; count2 < firstMatrix[count].length; count2++)
{
firstMatrix[count][count2] = enter.nextInt(); // populate array with user input
}
} // end array population
System.out.printf("The sum is: %d%n", sumMatrix(firstMatrix)); // call sumMatrix
System.out.println(firstMatrix[0][0]); // debug
for (int count3 = 0; count3<secondMatrix.length; count3++) // nested for to populate array with random numbers 1-100, row
{
for (int count4 = 0; count4<secondMatrix[count3].length; count4++) // column
{
secondMatrix[count3][count4] = 1 + spin.nextInt(100); // 100 inclusive, generate and populate array
}
}
System.out.println(secondMatrix[0][0]); // debug to show that it is properly printing the correct element
for (int i = 0; i<secondMatrix.length; i++)
{
for (int j = 0; j<secondMatrix[i].length; j++)
System.out.print(" " + secondMatrix[i][j]); // print the total array ( this process can be used to print the returned array )
}
System.out.println(); // debug
int arrayTotal = firstMatrix[0][0] + secondMatrix[0][0]; // debug
System.out.println("The element total is " + arrayTotal); // debug
System.out.println();
addMatrix(firstMatrix,secondMatrix); // call addMatrix
System.out.println("Programmed by Stephen Mills");
} // end main
public static int sumMatrix(int[][] array) // method to sum the elements of the array
{
int total = 0;
for (int number = 0; number<array.length; number++) // row
{
for (int number2 = 0; number2<array[number].length; number2++) // column
total += array[number][number2]; // sum of all elements
}
return total; // returns the sum
} // end sumMatrix
public static int[][] addMatrix(int[][] array1, int[][] array2) // improper method
{
int[][] thirdMatrix = new int[4][4];
for (int count4 = 0; count4<thirdMatrix.length; count4++)
{
for (int count5 = 0; count5<thirdMatrix[count4].length; count5++)
thirdMatrix[count4][count5] = array1[count4][count5]+array2[count4][count5];
}
System.out.println(Arrays.toString(thirdMatrix));
return thirdMatrix;
} // end addMatrix7
}
Most of the program works as intended but I'm getting this "[[I#3d4eac69, [I#42a57993, [I#75b84c92, [I#6bc7c054" output when trying to print my array. I've tried several methods, including simple println, toString, setting a variable equal to the method call, and I've tried putting the print statement in main first and then in the method second. Any ideas why this is happening?
If you want to print int elements of the 2d array thirdMatrix you can try this:
for(int[] simpleArray: thirdMatrix)
System.out.println(Arrays.toString(simpleArray));
The reason of your output: when you call
Arrays.toString(thirdMatrix)
you will call
String.valueOf(element)
foreach element of thirdMatrix. As elements of thirdMatrix are Array not primitive types, method
String.valueOf(Object obj)
will be called which return the hashcode of thirdMatrix elements(one-dimensional arrays).
I keep trying to add (many times) +1 to a number (the number is zero) already in an array which is zero but it is not working.
int i=0;//var for arrays
int [] countArray = new int[10];
/////////////////////
//__________ ask for values --------------
System.out.println("Hello please enter the number you would" +
" like to be sorted separated by commas. \n" +
"Example: \" 2,3,5,83,2 \".\t only use" +
" commas. to separate numbers\n");
//----------- save values -----
Scanner scan = new Scanner(System.in);
String allInput = scan.nextLine();//single string object with all input
String [] arr = allInput.split(",");//string array that holds all values
//as String
int [] numbersArray =new int[arr.length] ;//numbers
for ( String w: arr){//change Strings to Int
numbersArray[i]= Integer.valueOf(arr[i]);
i++;
}
//__ set all number in count to zero because necessary
i=0;
for ( int x: countArray){//set all numbers to zero
countArray[i]=0;
i++;
} //everything zeroed
i=0;
This works now, thank you guys:
for (int x = 0; x < numbersArray.length; x++){
if (numbersArray[x] >=10 && numbersArray[x] <=100) {
countArray[(numbersArray[x]-1)/10]++;}
else{
if (numbersArray[x] >=0 && numbersArray[x] <=10)
{
countArray[1 -1]++;}
}
}
Instead of using a for-each loop to edit all the values, try to iterate through them using a standard for loop. Here is a shorthand version of what you wrote. Try this:
for (int x = 0; x < numbersArray.length; x++){
countArray[(numbersArray[x]-1)/10]++;
}
I am trying to solve a problem in Java as part of my assignment. The problem is as below:
The user enters ten numbers one by one upon prompting by the screen. The screen then assigns all the distinct value to an array and a similar array to hold the frequency of how many times those numbers have appeared.
I have done the below work, but seems I am stuck somewhere in assigning the frequencies and distinct values to the arrays:
import java.util.*;
public class JavaApplication10
{
public static void main(String[] args)
{
int [] numbers = new int [10];
int [] count = new int[10];
int [] distinct = new int[10];
for (int k=0;k<10;k++)
{
count[k]=0;
distinct[k]=0;
}
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter number 0: ");
numbers[0]=input.nextInt();
count[0]=1;
distinct[0]=numbers[0];
int j=0;
for (int i = 1;i<10;i++)
{
System.out.print("Enter number "+i+": ");
numbers[i]=input.nextInt();
while(j<i)
{
if (distinct[j]==numbers[i])
count[j]=count[j]+1;
else
distinct[j+1]=numbers[i];
j++;
}
}
for (int k=0;k<10;k++)
{
System.out.println(distinct[k]+ " "+count[k]);
}
}
}
I know that it is not fair to ask someone to help me solve the problem. But any kind of hint will be helpful.
Thank you
are the numbers limited to 0-9? If so, I would simple do the assignment.
(please note you will assign the input to a variable called "input"):
numbers[0]=input;
count[input]++;
Also you can start your for loop in "0" to avoid the assignment prior to the for loop.
Just a hint.
Hope this helps!
the ideal data structure would be a HashMap
Steps:
1) initialize an array to store the numbers and for each input
2) check if a hashmap entry with key as the entered number already exists
3) if exists simply increase its count
4) else create new entry with key as the number and count as 1
so at the end your frequencies would be calculated
if you are forced to use 2 arrays
1) initialize two arrays
2) for each input loop the number array and check whether that number is already in the array
3) if so take the array index and increment the value of the frequency array with the same index
4) if not freq[index] = 1
A proper way of doing that would be:
public Map<Integer, Integer> getFrequencies(Iterable<Integer> numbers) {
Map<Integer, Integer> frequencies = new HashMap<Integer, Integer>();
for(Integer number : numbers) {
if (frequencies.get(number) == null) {
frequencies.put(number, 0);
}
frequencies.put(number, frequencies.get(number) + 1);
}
return frequencies;
}
It returns a map number -> frequency.
Arrays are not a way to go in Java, they should be avoided whenever possible. See Effective Java, Item 25: Prefer lists to arrays.
I removed the Scanner object to write the code faster, just replace it with your code above and it should work.
int[] numbers = { 1, 2, 2, 2, 3, 3, 3, 1, 1, 2 };
int[] count = new int[10];
int[] distinct = new int[10];
count[0] = 1;
distinct[0] = numbers[0];
int disPos = 1; //Current possition in the distinct array
boolean valueInarray = false;
for (int i = 1; i < 10; i++) {
valueInarray = false;
for (int d = 0; d < i; d++) {
if (numbers[i] == distinct[d]) {
count[d] = count[d] + 1;
valueInarray = true;
break;
}
}
if (!valueInarray) {
distinct[disPos] = numbers[i];
count[disPos] = 1;
disPos++;
}
}
If you ABSOLUTELY HAVE TO use arrays.. here is a way to do it…
import java.util.Scanner;
import java.util.Arrays;
public class JavaApplication10
{
public static void main(String[] args)
{
int [] numbers = new int [10];
int [] count = new int[10];
int [] distinct = new int[10];
int [] distinct1 = new int[1];
int distinctCount = 0;
boolean found = false;
Scanner input = new Scanner(System.in);
for (int i=0; i<10; i++) {
found = false;
System.out.print("Enter number " + i);
numbers[i]=input.nextInt(); //Add input to numbers array
for (int j=0; j<=distinctCount; j++)
{
if (distinct1[j] == numbers[i]){ // check to see if the number is already in the distinct array
count[j] = count[j] + 1; // Increase count by 1
found = true;
break;
}
}
if (!found) {
distinct[distinctCount] = numbers[i];
count[distinctCount] = 1;
distinctCount++;
distinct1 = Arrays.copyOf(distinct, distinctCount+1);
}
}
for (int j=0; j<distinctCount; j++)
System.out.println("The number " + distinct1[j] + " occurs " + count[j] + " times" );
}
}
I think this is what you need, correct me if I'm wrong...
import java.util.HashMap;
import java.util.Scanner;
public class JavaApplication10 {
public static void main(String[] args) {
// Initializing variables
int[] numbers = new int[10];
HashMap<Integer, Integer> table = new HashMap<Integer, Integer>();
Scanner input = new Scanner(System.in);
// Getting the 10 inputs
for(int x=0; x<10; x++) {
// Asking for input
System.out.println("Enter number "+x+":");
numbers[x]=input.nextInt();
// If the table contains the number, add 1
// Otherwise: set value to 1
if(table.containsKey(numbers[x]))
table.put(numbers[x], table.get(numbers[x])+1);
else
table.put(numbers[x],1);
}
// Closing the reader
input.close();
// Get the highest and smallest number
int highest=0;
int smallest=0;
for(int i:table.keySet()) {
if(i>highest)
highest=i;
if(i<smallest)
smallest=i;
}
// For every value between the smallest and the highest
for (int x=smallest; x<=highest; x++) {
// Check if the frequency > 0, else continue
if(table.get(x)==null)
continue;
// Output
System.out.println(x+" is "+table.get(x)+" times in \'frequence\'");
}
}
}
This also handles with negative numbers, unlike the other's codes. If you don't want to use HashMaps let me know so I can create something with arrays.
Let me know if it (doesn't) works!
Happy coding (and good luck with your assignment) ;) -Charlie