How can i alternate this input? - java

I'm having some trouble with this Java input:
public class Testinput {
public static void main(String[] args) {
int N = StdIn.readInt();
String[] name = new String[N];
int[] year = new int[N];
for (int i = 0; i < name.length; i++) {
name[i] = StdIn.readString();
for (int j = 0; j < name.length; j++) {
year[j] = StdIn.readInt();
}
}
for (int i = 0; i < name.length; i++ ) {
System.out.println(name[i]+" " +year[i]);
}
}
}
For example: it needs to read name and age in an alternating order:
2
bob
1963
kelly
1981
and print:
bob 1963
kelly 1961
But instead it asks for an input of length 6 (instead of 2*N = 4) and prints out:
input1 input5
input4 input6
Can you guys help me with this?

Are you coming from C background where you are used to Char-array? In Java, it is much straight forward. You can input by String.
Scanner scn = new Scanner(System.in); //Create a scanner object
int n = scn.nextInt(); //Enter number of people you want to prompt and record
String[] name = new String[n]; //Create array of size based on n
int[] year = new int[n]; //Create array of size based on n
for(int x=0; x<n; x++){
name[x] = scn.nextLine(); //for string inputs
year[x] = scn.nextInt(); //for whole number
}
This will provide you an alternative for inputs.
Most universities and schools I encounter teaches their students to use Scanner for receiving user inputs. So you may want to use it too if you are allowed to.

Related

How to take 2 key board inputs to a 2 dimensional array in java?

I want to create a 2D String array which stores name and address which are given as keyboard inputs.
eg: name 1 address 1;
name 2 address 2;
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[][] array = new String[3][2];
for (int i = 0; i < 3; i++)
{
for(int j = 0; j < 2; j++)
{
array[i][j] = sc.nextLine();
}
System.out.println(array[0][0]);
}
}
in here I want to print a statement asking to enter the name
eg. System.out.println("Enter name:");
after that I want to write another statement asking to enter the address
eg.System.out.println("Enter the address");
but i cant figure out how do that in a 2d array
How about something like this?
public static void main(String[] args) {
int rows = 3;
int cols = 2;
Scanner sc = new Scanner(System.in);
String[][] array = new String[rows][cols];
for (int row = 0; row < rows; row++) {
System.out.println("Enter name:");
array[row][0] = sc.nextLine();
System.out.println("Enter the address:");
array[row][1] = sc.nextLine();
}
// Print out array
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
System.out.print(array[row][col] + ", ");
}
System.out.print(";");
}
}
Output:
Person 1, Address 1, ; Person 2, Address 2, ; Person 3, Address 3, ;
Check it live here: https://onlinegdb.com/Byu4wc1vI
I hope this helps!

How to get the sum of each row in java using multidimensional array?

So i'm new at java and I'm currently trying to learn how to use array. So what i'm trying to do is to create a program the will as the user the numbers of rows and column and print the sum of the 2d array.
So the output should be like this:
Enter the number of row:2
Enter the number column:2
Enter a number:1
Enter a number:2
Enter a number:3
Enter a number:4
Output:
1 2 3
3 4 7
Here is my output:
Enter the number of row:2
Enter the number column:2
Enter a number:1
Enter a number:2
Enter a number:3
Enter a number:4
Output:
1 2
3 4
Somehow i cant find a way to sum each row.
Here is my code:
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
int sum = 0;
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of row: ");
int row = input.nextInt();
System.out.print("Enter the number of column: ");
int column = input.nextInt();
int [][] array = new int[row][column];
for(int i = 0; i<row; i++){
for(int j = 0; j<column; j++){
System.out.print("Enter a number: ");
array[i][j] = input.nextInt();
}
}
for(int i = 0; i<row; i++){
for(int j = 0; j<column; j++){
System.out.print(array[i][j]+" ");
}
System.out.println();
}
}
}
I've been trying to do this for the past 3 hours and i cant seem to find a way to sum each row . I'm pretty new at this so any help would be greatly appreciated!
So basically, have a variable initialized for each row to calculate sumof all elements of the given row. Display it after the elements are displayed
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of row: ");
int row = input.nextInt();
System.out.print("Enter the number of column: ");
int column = input.nextInt();
int [][] array = new int[row][column];
for(int i = 0; i<row; i++){
for(int j = 0; j<column; j++){
System.out.print("Enter a number: ");
array[i][j] = input.nextInt();
}
}
for(int i = 0; i<row; i++){
int s = 0; // this variable calculates the sum
for(int j = 0; j<column; j++){
s+=a[i][j]; // summing elements of that row
System.out.print(array[i][j]+" ");
}
System.out.println(s);
}
}
}
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);/*initializing the variable input with
new Scanner object*/
System.out.println("Enter the number of rows");/*getting the number of rows
and columns of the 2D array as an user input*/
int noOfRows=input.nextInt();
System.out.println("Enter the number of columns");
int noOfColumns=input.nextInt();
int newArr[][] = new int[noOfRows][noOfColumns];//creation of the 2D array
for(int i = 0 ; i < noOfRows ; i++) {/*Goal of this for loop is to assign the
userInpts to the array indexes*/
for(int j = 0 ; j < noOfColumns ; j++) {
System.out.println("Enter a number");/*Getting the user inputs to
store in the array*/
newArr[i][j] = input.nextInt();
}
}
for(int i = 0 ; i < noOfRows ; i++) {/*Goal of this for loop is printing the
array and sum of the row at the end of the each row*/
int sumofTheRow = 0;/*This is the variable which holds the sum of the
current row so initial value is 0 */
for(int j = 0 ; j < noOfColumns ; j++) {
sumofTheRow += newArr[i][j];/*so inside the inner for loop sumOfTheRow
will be calculated by adding the elements in the row one by one*/
System.out.print(newArr[i][j] + " ");
}
System.out.println(sumofTheRow);//Calculated sum of the row will be displayed
/*So now if i is less than noOfRows then again it will increment the value of i by one and move to the next row */
}
input.close();/*closing the scanner variable to avoid memory leaks --> [ now garbage collector will free the memory area of scanner object by collecting the scanner object]*/
}
}

Trying to get a For Loop to work

I'm trying to write a program where on the first line, you enter the number of times you want a for loop to iterate, on the second line, you enter the value of the array, and on the third line, you enter the numbers that you want in the array. My program either does not do what I want it to do, or it crashes on me. This is the code that I have for the program so far:
import java.util.*;
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
int n = input.nextInt();
for (int i=0; i<n; i++)
{
int value = input.nextInt();
int[] arr = new int[value];
arr[i] = input.nextInt();
}
}
What can I do? Please help. I've tried everything! Also, it would help if someone could help me with sorting the numbers in ascending order, followed by displaying the middle number in each line, but first thing's first. Thank you.
I believe this is more of what you are after. I output the entries individually but you could combine that easily enough.
public static void main(String[] args)
{
Scanner input = new Scanner (System.in);
try
{
System.out.println("Number of times to loop:");
int numEntries = input.nextInt();
int[][] valueArrays = new int[numEntries][];
for (int i=0; i<numEntries; i++)
{
System.out.println("Size of array #"+i+": ");
int arrayLen = input.nextInt();
int[] inputArray = new int[arrayLen];
for (int j = 0; j < arrayLen; j++)
{
System.out.println("Enter value at index "+j+": ");
inputArray[j] = input.nextInt();
}
Arrays.sort(inputArray);
valueArrays[i] = inputArray;
}
for (int l=0; l < valueArrays.length; l++)
{
int[] values = valueArrays[l];
for (int m=0; m < values.length; m++)
{
System.out.println("Value of array #"+l+" saved at index "+m +": " + values[m]);
}
if ((values.length % 2) == 0)
{
int start = values.length/2;
int end = start + 1;
System.out.println("Middle values in array #"+l+" saved at indices " + start + " and " + end);
}
else
{
int start = values.length/2;
System.out.println("Middle value in array #"+l+" saved at index " + start);
}
}
}
finally
{
input.close();
}
}
You're creating a new array on each iteration inside the loop.
You should get int[] arr = new int[value]; out of the loop:
int arraySize = input.nextInt();
int[] arr = new int[arraySize];
for (int i=0; i<arraySize; i++)
{
int value = input.nextInt();
arr[i] = value;
}
If you don't want to limit the user for a size, use an ArrayList instead.
Problem 1:My program either does not do what I want it to do.
Dont initialize array inside for loop as loop wiil create a new array every time you iterate it.
Scanner input = new Scanner (System.in);
System.out.println("Enter no. of elements in array");
int n = input.nextInt();
int[] arr = new int[n];
System.out.println("Array length set to "+n);
for (int i=0; i<n; i++)
{
System.out.println("Enter value for index "+i);
arr[i] = input.nextInt();
System.out.println(arr[i]+" Value saved at index "+i);
}
DEMO1
Problem 2(described in comments below):Sorting arrays and displaying the middle number
class Ideone
{
static int[] countingSort(int[] numbers) {
int max = numbers[0];
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] > max)
max = numbers[i];
}
int[] sortedNumbers = new int[max+1];
for (int i = 0; i < numbers.length; i++) {
sortedNumbers[numbers[i]]++;
}
int insertPosition = 0;
for (int i = 0; i <= max; i++) {
for (int j = 0; j < sortedNumbers[i]; j++) {
numbers[insertPosition] = i;
insertPosition++;
}
}
return numbers;
}
public static void main (String[] args) throws java.lang.Exception
{
Scanner input = new Scanner (System.in);
System.out.println("Number of times to loop:");
int n = input.nextInt();
// int[] arr = new int[n];
// System.out.println("Array length set to "+n);
for (int i=1; i<=3; i++)
{
System.out.println("Size of array #"+i+": ");
int alen = input.nextInt();
int[] arr = new int[alen];
System.out.println("Value in array #"+i+": ");
for (int j=0; j<alen; j++){
System.out.println("Enter value at index "+j+": ");
arr[j] = input.nextInt();
}
arr=Ideone.countingSort(arr);
for (int l=0; l<alen; l++)
System.out.println(arr[l]+" Value of array #"+i+" saved at index "+l);
System.out.println("Middle value in array #"+i+" saved at index "+arr[alen/2]);
}
}
}
DEMO2

How to check to see if an array index has already been called in java

I am making a sample program that randomly assigns a certain amount of students from a certain amount of students to take a survey using arrays. Since a student can't be chosen two times, I need to figure out a way (the most efficient way, of course), to check and make sure that doesn't happen without using ArrayLists. Here is my current code (also if you have any suggestions on how to condense this code, I would love to hear them):
import java.util.*;
public class StudentsForSurvey {
public static void main(String[] argv) {
Scanner kb = new Scanner(System.in);
Random rndm = new Random();
int N = 0;
int slctd = 0;
while (N < 20) {
System.out.print("How many students are in the class?");
N = kb.nextInt();
System.out.println("Sorry, but School records say that there are at least 20 students `enter code here`in each classroom. Don't you know your own attendance!?");
}
while (slctd > 10 && slctd < 1) {
System.out.print("\nHow many students to randomly select?");
slctd = kb.nextInt();
System.out.println("Sorry, but at least 1 student and at most, 10 students, can `enter code here`participate in this survey. Didn't someone tell you this at orientation!?");
}
int[] stdntnums = new int[slctd - 1];
for (int i = 0; i < slctd - 1; i++) {
stdntnums[i] = i + 1;
}
int[] help = stdntnums;
System.out.print("Students selected are: ");
for (int x = 0; x <= slctd; x++) {
int rnd = rndm.nextInt(N) - 1;
for (int z = 0; z <= N; z++) {
System.out.print(stdntnums[rnd]);
}
}
}
}
Try this code. I had to do similar task then i had used it.
java.util.Random r = new java.util.Random();
java.util.Scanner s = new java.util.Scanner(System.in);
int arraylength = s.nextInt();
int students[] = new int[arraylength];
for(int i =0;i< arraylength;i++)
{
students[i]=i;
System.out.println(students[i]);
}
System.out.println("generated");
int no_of_selected_students = r.nextInt(arraylength);
int selected_students[] = new int[no_of_selected_students];
int last =no_of_selected_students;
for(int i=0;i<no_of_selected_students;i++)
{
int current = r.nextInt(last);
selected_students[i] = students[current];
students[current]= students[last];
last--;
System.out.println(selected_students[i]);
}
System.out.println("randomized");

Reading Multiple Lines, ArrayList

The problem I wanted to solve is:
Sereja has an array a, consisting of n integers a1, a2, ..., an. The boy cannot sit and do nothing, he decided to study an array. Sereja took a piece of paper and wrote out m integers l1, l2, ..., lm (1 ≤ li ≤ n). For each number li he wants to know how many distinct numbers are staying on the positions li, li + 1, ..., n. Formally, he want to find the number of distinct numbers among ali, ali + 1, ..., an.?
Sereja wrote out the necessary array elements but the array was so large and the boy was so pressed for time. Help him, find the answer for the described question for each li.
I need to be able to read an input like such:
10 10
1 2 3 4 1 2 3 4 100000 99999
1
2
3
4
5
6
7
8
9
10
I tried using buffered reader, but I always get a runtime error
import java.util.ArrayList;
import java.util.Scanner;
import java.io.*;
public class Main
{
public static void main(String[] args)
{
Scanner scan = new Scanner(new BufferedInputStream(System.in));
int n = scan.nextInt();
int m = Integer.parseInt(scan.nextLine());
int[] a = new int[n];
int[] l = new int[m];
for(int i=0; i<n-1; i++)
{
a[i] = scan.nextInt();
}
a[n] = Integer.parseInt(scan.nextLine());
for(int j=0; j<m; j++)
{
l[j] = Integer.parseInt(scan.nextLine());
}
int counter = 0;
ArrayList<Integer> list = new ArrayList<Integer>();
for(int k=0; k<m; k++)
{
for(int x=l[k]; x<= n; x++)
{
if(!(list.contains(x)))
{
list.add(x);
counter++;
}
}
System.out.println(counter);
}
}
}
Whenever I run this program, I get a runtime error. The output that I need to get with the aforementioned input is
6
6
6
6
6
5
4
3
2
1
Why isn't it working?
OK, I tried this:
import java.io.*;
import java.util.ArrayList;
public class Main
{
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] tokens = br.readLine().split(" ");
int n = Integer.parseInt(tokens[0]);
int m = Integer.parseInt(tokens[1]);
String[] tokenstwo = br.readLine().split(" ");
int[] a = new int[n];
int[] l = new int[m];
for(int i=0; i<n; i++)
{
a[i] = Integer.parseInt(tokenstwo[i]);
}
for(int j=0; j<m; j++)
{
l[j] = Integer.parseInt(br.readLine());
}
int counter = 0;
ArrayList<Integer> list = new ArrayList<Integer>();
for(int k=0; k<m; k++)
{
for(int x=l[k]; x<= n; x++)
{
if(!(list.contains(x)))
{
list.add(x);
counter++;
}
}
System.out.println(counter);
}
}
}
It said something about IOException. Therefore, i added the throws ioexception at the top. It still give a runtime error though.
Try using the below code for taking the input. Fit it for your need.
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] tokens = br.readLine().split(" ");
int n1 = Long.parseLong(tokens[0]);

Categories

Resources