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
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 + " ");
}
}
I am trying to generate a program that ask the user a number "n" and displays a 2 x n array. E.g:
1 2 3 4 5 (User input)
5 8 2 1 5 (Random numbers)
I can't see to make my code to work. Here is my code:
import java.util.Scanner;
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter number of exits: ");
int n = input.nextInt();
int [][] A = new int[2][n];
for (int i =0; i <= A[n].length; i++){
A[i][n]= (int)(Math.random()*10);
}
System.out.println(A[2][n]);
System.out.print("Distance between exit i and exit j is: " + distance());
}
public static int distance(){
Scanner input = new Scanner(System.in);
System.out.print("Please enter exit i: ");
int i = input.nextInt();
System.out.print("Please enter exit j: ");
int j = input.nextInt();
return i + j;
}
}
I am getting this error
"Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
5"
How can I fix it?
And I think my Math.random is wrong. Can you guys help me with some advises or where am I doing things wrong?
Thanks.
All your errors lie within and after your for-loop:
for (int i =0; i <= A[n].length; i++){
A[i][n]= (int)(Math.random()*10);
}
If n = 5, A[5].length does not exist, because the first dimensions of your array only exist between 0 and 1. A[2] reserves space for 2 int primitives, the first is at index 0 and the last is at index 1. Even if that is changed, the i variable your for loop declares is incremented beyond 1 and so the JVM will throw a ArrayIndexOutOfBoundsException.
When declaring an array with the dimensions [2][n], (given n is an Integer, which will be provided by the user via the scanner) you cannot access arrayReference[2][x]
Arrays are based on a 0 index structure...
Consider the following:
int [][] A = new int[2][2];
You can only access A[0][0], A[0][1], A[1][0] & A[1][1].
you CANNOT access A[2][0], A[2][1] or A[2][2].
Here's what you need to do:
//A.length will give you the length of the first dimension (2)
for(int i=0; i<A.length; i++){
for(int j=0; j<n; j++){
A[i][j] = (int) (Math.random()*10);
}
}
}
System.out.println(A[1][n-1]);
System.out.print("Distance between exit i and exit j is: " + distance());
I need help printing the array, I need to print 6 items per line and switch to a next line for the seventh and following numbers. Also who do i Enter numbers into an array without defining how many numbers will be entered?
import java.util.Scanner;
public class NumberArray
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("How many grades do you want to enter?");
int num = input.nextInt();
int array[] = new int[num];
System.out.println("Enter the " + num + " grades now.");
for (int grades = 0 ; grades < array.length; grades++ )
{
array[grades] = input.nextInt();
}
System.out.println("These are the grades you have entered.");
printArray(array);
}
public static void printArray(int arr[])
{
int n = arr.length;
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " \t");
}
}
}
I need help printing the array, I need to print 6 items per line and switch to a next line for the seventh and following numbers.
From this question, it seems to indicate that you want the output to look like this:
1 2 3 4 5 6
7 8 9 ... n
This can be achieved quite simply.
Option 1 - The classic If statement
for(int x = 0; x < array.length; x++) {
System.out.print(array[x]);
if(x == 5) {
// 5 because we're counting from 0!
System.out.println();
}
}
Option 2 - Using the Ternary operator to keep it on one line
NOTE: This is more or less the same. It's just nice to be complete in these sorts of answers.
for(int x = 0; x < array.length; x++) {
System.out.print(array[x] + x == 5? "\n":"");
}
Edit
If you meant that you want 6 items on each line, like so:
1 2 3 4 5 6
7 8 9 10 11 12
...
Then you can use the % (The modulus operator) to print out a new line on every output. This is actually quite easy to change, but you'll need to make sure that you're checking the value before you're outputting the content. This can be shown in this IDEOne.
Use modulus operator (%) to break to a new line line:
public static void printArray(int arr[])
{
int n = arr.length;
for (int i = 0; i < n; i++) {
if(i % 6 == 0) // if you don't want the initial newline, check for i > 0
System.out.println()
System.out.print(arr[i] + " \t");
}
}
you can also use printf() method to format the line; which is probably better:
System.out.printf("%5d", arr[i]);
The reason why this is better, is because you can easily format the output to a specific justification, column width, etc., which will make your output look better.
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!
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
}