Im working on an assignment for a beginners Java course, and Im having a problem with printing out an array the way that its asking for. The problem is as follows:
"Write a program that asks the user "How many numbers do you want to enter?" With that value, create an array that is big enough to hold that amount of numbers (integers). Now ask the user to enter each number and store these numbers into the array. When all the numbers have been entered, display the numbers in reverse order from the order in which they were entered."
I have everything except the last part, displaying the numbers in reverse order.
Any help on this would be appreciated.
Heres What I have so far:
import java.util.Scanner;
public class ArraysNickGoldberg
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("How many numbers do you want to enter?");
final int NUMBER_OF_ELEMENTS = input.nextInt();
int[] myList = new int[NUMBER_OF_ELEMENTS];
for( int i = 0; i < NUMBER_OF_ELEMENTS; i++) {
System.out.println("Enter a new number: ");
myList[i] = input.nextInt();
}
for( int i = 0; i < NUMBER_OF_ELEMENTS; i++){
System.out.print(myList[i] + " ");
}
}
}
try
for( int i = NUMBER_OF_ELEMENTS - 1; i >= 0; i--){
System.out.print(myList[i] + " ");
}
You may also want to look at
Java Array Sort
to print it in reverse order, you just need to simply reverse your for loop :)
so instead of
for(int i=0; i< NUMBER_OF_ELEMENTS; i++){
}
use this instead:
for(int i=NUMBER_OF_ELEMENTS - 1; i >= 0; i--){ //remember to minus 1 or else you'll get index of out of bound
}
Related
Im trying to print out an array but only print out the distinct numbers in that array.
For example: if the array has {5,5,3,6,3,5,2,1}
then it would print {5,3,6,2,1}
each time i do it either i only print the non repeating numbers, in this example {6,2,1} or i print them all. then i didnt it the way the assignment suggested
the assignment wants me to check the array before i place a value into it to see if its there first. If not then add it but if so dont.
now i just keep getting out of bounds error or it just prints everything.
any ideas on what i should do
import java.util.Scanner;
public class DistinctNums {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int value;
int count = 0;
int[] distinct = new int[6];
System.out.println("Enter Six Random Numbers: ");
for (int i = 0; i < 6; i++)
{
value = input.nextInt(); //places users input into a variable
for (int j = 0; i < distinct.length; j++) {
if (value != distinct[j]) //check to see if its in the array by making sure its not equal to anything in the array
{
distinct[count] = value; // if its not equal then place it in array
count++; // increase counter for the array
}
}
}
// Displays the number of distinct numbers and the
// distinct numbers separated by exactly one space
System.out.println("The number of distinct numbers is " + count);
System.out.print("The distinct numbers are");
for (int i = 0; i < distinct.length; i++)
{
System.out.println(distinct[i] + " ");
}
System.out.println("\n");
}
}
Always remember - if you want a single copy of elements then you need to use set.
Set is a collection of distinct objects.
In Java, you have something called HashSet. And if you want the order to be maintained then use LinkedHashSet.
int [] intputArray = {5,5,3,6,3,5,2,1};
LinkedHashSet<Integer> set = new LinkedHashSet<Integer>();
//add all the elements into set
for(int number:intputArray) {
set.add(number);
}
for(int element:set) {
System.out.print(element+" ");
}
You can make this using help array with lenght of 10 if the order is not important.
int [] intputArray = {5,5,3,6,3,5,2,1};
int [] helpArray = new int[10];
for(int i = 0; i < intputArray.length ; i++){
helpArray[intputArray[i]]++;
}
for(int i = 0; i < helpArray.length ; i++){
if(helpArray[i] > 0){
System.out.print(i + " ");
}
}
package selectionsortintro;
public class SelectionSortIntro {
public static void main(String[] args) {
int nums[] = { 22, 30, 15, 1, 7, 87, 65, 24, 22, 0 };
// print out unsorted list
for (int count = 0; count < nums.length; count++) {
System.out.print(nums[count] + " ");
}
System.out.println("\n---------------------------------");
selectionSort(nums);
// print out sorted list
System.out.println("After sorting using the Selection Sort," + " the array is:");
for (int count = 0; count < nums.length; count++) {
System.out.print(nums[count] + " ");
}
}
public static void selectionSort(int data[]) {
int smallest;
for (int i = 0; i < data.length - 1; i++) {
smallest = i;
// see if there is a smaller number further in the array
for (int index = i + 1; index < data.length; index++) {
if (data[index] < data[smallest]) {
swap(data, smallest, index);
}
}
}
}
public static void swap(int array2[], int first, int second) {
int hold = array2[first];
array2[first] = array2[second];
array2[second] = hold;
}
}
I want to add a random amount of random integers into the array, so the selection sort algorithm will sort them out. The only problem is, I don't know how to store the array with random numbers and not be a fixed amount. If that's confusing, when you make the array it's like :
int[] randomNumbers = new int[20];
Where 20 is the amount of numbers generated. Well I want to have the user be the judge of how many numbers are randomly generated into the array. So I'm thinking maybe use ArrayList? But then, I get confused as to how I can use it to add the random numbers into itself. If anyone can help me that'd be awesome
EDIT: So I got input using scanner, but I really would prefer JOptionPane as the input dialog looks a lot nicer, but if scanner is the only way that's fine. So now that that's done, I just need to actually FILL the array with random integers, does anyone know how to do that?
Here's what I came up with, I get an error with my code, if anyone could help that'd be awesome.
Scanner input = new Scanner(System.in);
Scanner s = new Scanner(System.in);
System.out.println("enter number of elements");
int n = s.nextInt();
int nums[]=new int[n];
Random randomGenerator = new Random();
//print out unsorted list
for (int count = 0; count < nums.length; count++) {
System.out.print(nums[count] + " ");
nums[n] = randomGenerator.nextInt(1001);
}
Here's an example using a traditional array and a JOptionPane:
import javax.swing.*;
import java.util.Random;
public class Random_int_array {
public static void main(String[] args) {
JFrame frame = new JFrame("Total number of integers");
int iTotalCount = Integer.parseInt(JOptionPane.showInputDialog(frame, "What is the total number of integers?"));
int[] array = new int[iTotalCount];
Random randomGenerator = new Random();
for(int i=0; i < iTotalCount; i++){
array[i] = randomGenerator.nextInt(1001);
}
// Now you can do whatever processing you would like to do
// For the sake of this answer, I will just print the numbers
for(int i=0; i < array.length; i++){
System.out.println(array[i]);
}
// We should explicitly call exit because we used a form/window
System.exit(0);
}
}
And here's an example of using an ArrayList with JOptionPane instead of a regular int[] array;
import javax.swing.*;
import java.util.Random;
import java.util.ArrayList;
public class Random_int_array {
public static void main(String[] args) {
JFrame frame = new JFrame("Total number of integers");
int iTotalCount = Integer.parseInt(JOptionPane.showInputDialog(frame, "What is the total number of integers?"));
// Can also be written as: ArrayList<Integer> array = new ArrayList<>();
// in newer versions of Java.
ArrayList<Integer> array = new ArrayList<Integer>();
Random randomGenerator = new Random();
for(int i=0; i < iTotalCount; i++){
array.add(randomGenerator.nextInt(1001));
}
// Now you can do whatever processing you would like to do
// For the sake of this answer, I will just print the numbers
for(int i=0; i < array.size(); i++){
System.out.println(array.get(i));
}
// We should explicitly call exit because we used a form/window
System.exit(0);
}
}
Note: ArrayLists cannot use primitive data types, so you must specify it as using an Integer rather than an int.
Adding an option to set the size of the array based off of user input is a bit more tricky
The easiest way to code it is to pass in command line arguments and read them in your args variable in your main method
Another way to read input is the Scanner class
Whichever way you choose, you may end up with a String variable you need to convert to an int with
String input = args[0]; //or use Scanner
int size = Integer.parseInt(input);
Three different methods of generating random integers, from easiest to implement to hardest
To generate a random int [0, max)
(int)(Math.random() * max)
or use
Random r = new Random();
r.nextInt(max);
A more complicated way to generate a more random number instead of Java's pseudo-random generators would be to query random.org for data. Do note that this may take a bit longer to set up and code, as well as relying on third party servers (no matter how reliable they may be)
You can use the random int to initialize the input array with a random length, then fill in the values with random numbers with a for loop
How do I solve the following problem?
Please see link here.
My code only works when the data is entered horizontally.
How would I go about changing my code in order to be able to display the sums like my 2nd example above in the link?
Here's my code:
import java.util.Scanner;
public class sums_in_loop {
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
String code = scanner.nextLine();
String list[] = code.split(" ");
for( int counter = 0; counter < list.length; counter++) {
int sum = 0;
System.out.println(sum + " ");
}
}
}
Judging by the URL you provided, the solution is rather straight-forward.
Ask the user how many pairs to enter
Declare an array of integers with a size of the user input from step 1
Run a loop based on the user input from step 1
Declare an array of integers with a size of 2
Run a nested loop of two to get user input for the two integers
Add the two numbers into the array from step 2
Display results
With that in mind (I assume only valid data is being used):
public static void main(String[] args) throws Exception {
Scanner input = new Scanner(System.in);
System.out.print("How many pairs do you want to enter? ");
int numberOfPairs = input.nextInt();
int[] sums = new int[numberOfPairs];
for (int i = 0; i < numberOfPairs; i++) {
int[] numbers = new int[2];
for (int j = 0; j < numbers.length; j++) {
// Be sure to enter two numbers with a space in between
numbers[j] = input.nextInt();
}
sums[i] = numbers[0] + numbers[1];
}
System.out.println("Answers:");
for (int sum : sums) {
System.out.print(sum + " ");
}
}
Results:
How many pairs do you want to enter? 3
100 8
15 245
1945 54
Answers:
108 260 1999
I'm trying to create a code that lets the user determine the size and elements of an array and then print it out. So far I have this.
import java.util.Scanner;
public class test3 {
public static void main (String[] args)
{
Scanner keyboard=new Scanner(System.in);
System.out.println("Input how many numbers you want to find the median for (numerical value) :");
int num = keyboard.nextInt();
System.out.println("Please enter " + num + " numbers.");
int[] values = new int[num];
for (int i = 0; i < num; i++) {
values[i] = keyboard.nextInt();
System.out.println(values[i]);
}
}
}
I don't know if it is right because when a user inputs the size and then the elements, the code is just displaying the element as the user inputs it. For example,
input how many numbers you want to find the median for
5
please enter 5 numbers
3//user input
3//what is displayed.
I want to make it so that the user inputs all of their numbers and THEN it displays the inputed numbers as an array.
We are not allowed to use the array class by the way.
import java.util.Scanner;
public class test3 {
public static void main (String[] args) {
Scanner keyboard=new Scanner(System.in);
System.out.println("Input how many numbers you want to find the median for (numerical value) :");
int num = keyboard.nextInt();
System.out.println("Please enter " + num + " numbers.");
int[] values = new int[num];
for (int i = 0; i < num; i++) {
values[i] = keyboard.nextInt();
}
for (int i = 0; i < num; i++) {
System.out.println(values[i]);
}
}
}
Your for loop will execute for as many number as the user has entered, in your test case 5. Every iteration will take a number from the keyboard input, place it into the array and display it. Since you want to capture all the numbers first and then want to display them you should remove
System.out.println(values[i]);
from the for loop and place that into another for loop to display the numbers like so
for(int x=0 ;i < num ; i++)
{
System.out.println(values[x]);
}
This way the first loop will gather all the numbers and after the numbers are collected the second loop will display the numbers one by one iterating over the array.
Hope this helps!
In line 24, I am getting an error which is commented out. What is causing this and how to I get it fixed?
Any help is much appreciated. Thanks ahead of time. :)
import java.util.Scanner;
public class main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//initialize array
double[] numbers = new double [10];
//Create Scanner object
System.out.print("Enter " + numbers.length + " values: ");
//initialize array
for ( int i = 0; i < numbers.length; i++){
numbers[i] = input.nextDouble() ;
java.util.Arrays.sort(numbers[i]); //getting an error here, thay says [The method sort(int[]) in the type Arrays is not applicable for the arguments (double)]
//Display array numbers
System.out.print(" " + numbers);
}
//Close input
input.close();
}
}
You need to sort the complete array rather than a single element:
Arrays.sort(numbers);
Better to move it outside of the for-loop. You could use Arrays.toString to display the contents of the array itself:
for (int i = 0; i < numbers.length; i++) {
numbers[i] = input.nextDouble();
}
Arrays.sort(numbers);
System.out.print(Arrays.toString(numbers));
Note: Class names start with an uppercase letter, e.g. MyMain.
Put this after the for loop:
java.util.Arrays.sort(numbers);
notice numbers not numbers[i] and the print needs to come out of that loop too.
The mistake you're making is that you are trying to sort a single number. The error message points out that the sort method expects an array.
Your algorithm should first read in all the numbers, before sorting. So change your code to something like this:
...
// first read in numbers
for ( int i = 0; i < numbers.length; i++){
numbers[i] = input.nextDouble() ;
}
// then apply sort
java.util.Arrays.sort(numbers); // numbers is an array, so it's a valid argument.
// finally, after sorting you may now output the sorted array
for(int number : numbers){
System.out.println(number);
}
...