Scanner input issue - java

How do I take in input from a user from a scanner, then put that input into a 2D Array. This is what I have but I dont think it is right:
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int [][] a = new int[row][col];
Scanner in = new Scanner(System.in);
System.out.println("Enter a sequence of integers: ");
while (in.hasNextInt())
{
int a[][] = in.nextInt();
a [row][col] = temp;
temp = scan.nextInt();
}
Square.check(temp);
}
What I am trying to do is create a 2D array and create a magic Square. I have the boolean part figured out, I just need help with inputting users sequence of numbers into the array so the boolean methods can test the numbers. All help greatly appreciated

I don't believe your code will work how you want it to. If I'm understanding your question correctly, here's what I would do:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int [][] a = new int[row][col];
for(int i = 0; i < row; i++) {
for(int j = 0; j < col; j++) {
System.out.print("Enter integer for row " + i + " col " + j + ": ");
a[i][j] = in.nextInt();
}
}
// Create your square here with the array
}
In the loops, i is the current row number and j is the current column number. It will ask the user for every row/column combination.

You can use that in order to enter all number at the same time :
int [][] a = new int[3][3];
Scanner in = new Scanner(System.in);
System.out.println("Enter a sequence of integers: ");
int row=0,col=0;
while (in.hasNextInt())
{
a [row][col++] = in.nextInt();
if(col>=3){
col=0;
row++;
}
if(row>=3)break;
}
Then you can enter :
1 2 3 4 5 6 7 8 9
to fill your array.

Related

create a two dimensional (2D) array in java

I am working on a java code that calculates the average of an array and it is working perfectly in serving its purpose but I want to modify it to be a 2D array (Two-dimensional).
import java.util.*;
public class Test3{
public static void main(String [] args){
Scanner adnan = new Scanner(System.in);
System.out.println("Enter the length of the array : ");
int length = adnan.nextInt();
int [] input = new int [length];
System.out.println("Enter Numbers : ");
for ( int i = 0; i < length; i++){
input [i] = adnan.nextInt();
}
float average = average(input);
System.out.println("Average of all numbers in the array : " + average);
adnan.close();
}
public static float average(int [] input){
float sum = 0f;
for ( int number : input){
sum = sum + number;
}
return sum / input.length;
}
}
any help would be really appreciated because I am not too good at 2D arrays.
In Java a 2D Array is declared using double brackets T [][]:
public static void main(String[] args) {
// mock to not to use a stdin redirection or enter data manually
ByteArrayInputStream system_in = new ByteArrayInputStream("3 2 5 8 1 6 7 2".getBytes(UTF_8));
Scanner adnan = new Scanner(system_in);
System.out.println("Enter rows number: ");
final int rows = adnan.nextInt();
System.out.println("Enter rows number: ");
final int cols = adnan.nextInt();
final int [][] input = new int[rows][cols];
System.out.println("Enter Numbers : ");
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
input[row][col] = adnan.nextInt();
}
}
double average = average(input);
System.out.println("Average of all numbers in the array : " + average);
adnan.close();
}
public static double average(int[][] input) {
// use streams or you can use the `Enter Numbers...` way
return Arrays.stream(input)
.flatMap(x -> Arrays.stream(x).boxed())
.mapToInt(x -> x).average()
.getAsDouble();
}
with output
Enter rows number:
Enter rows number:
Enter Numbers :
Average of all numbers in the array : 4.833333333333333

How to find missing number in array by taking user input

This is my code and Iam getting ArrayIndexoutofBoundsException and cant able to find where
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
int sum=0,sumtotal;
Scanner sc = new Scanner(System.in);
System.out.println("Enter x");
int x = sc.nextInt();
sumtotal = (x+1)*(x+2)/2;
System.out.println("Enter the size of array");
int n = sc.nextInt();
int a[] = new int[n];
System.out.println("Enter values of array");
for(int i = 0;i<n;i++){
a[i] = sc.nextInt();
}
for(int i = 0;i<=a.length;i++)
sum = sum+a[i];
int miss = sumtotal-sum;
System.out.println(miss);
}
}
I put size of array 5 values are 1,2,4,5,6
and value of x is 5
You need to change the for loop from
for(int i = 0;i<=a.length;i++)
to
for(int i = 0;i<a.length;i++)
because the range of i is from 0 to 5 and your array a have index from 0 to 4 only.

Create multiple arrays using a for loop

I would like to make a program where the user can input the number of variables and fill every variable with certain values. For example, the User inputs that he/she wants to make 10 arrays, then the User inputs that the first array should have 5 elements and the User fills that array with values, then the User wants the second array to have 4 elements and does the same and so on.
This is the code I was using, but it doesn't work:
public static void main(String[] args){
Scanner s = new Scanner(System.in);
System.out.println("Enter the numbers of variables: ");
int i = s.nextInt();
for(int j = 0;j < i;j++){
int[] var = new int[j];
System.out.println("Enter the number of values: ");
int p = s.nextInt();
for(int q = 0;q < p;p++){
int n = s.nextInt();
var[q] = n;
}
}
}
And how could I compare these arrays that the user inputs?
The problem is that each time you are creating the array.
try this:
Scanner s = new Scanner(System.in);
System.out.println("Enter the numbers of variables: ");
int i = s.nextInt();
int[][] var = new int[i][];
for(int j = 0;j < i;j++){
System.out.println("Enter the number of values: ");
int p = s.nextInt();
var[j] = new int[p];
for(int q = 0;q < p;p++){
int n = s.nextInt();
var[j][q] = n;
}
}
Instead of creating a one dimensional array, you create a jagged array. Essentially, a 2d array is an array of arrays. that way the user inputs the number of arrays (i) and then continues to fill the arrays.
To check whether two collections have no commons values, you can use
Collections.disjoint();
For other operations, you can look here
This should work (with bidimensionnal array)
public static void main(String[] args){
Scanner s = new Scanner(System.in);
System.out.println("Enter the numbers of variables: ");
int i = s.nextInt();
int[][] var = new int[i][];
for(int j = 0;j < i;j++){
System.out.println("Enter the number of values: ");
int p = s.nextInt();
var[j] = new int[p];
for(int q = 0;q < p;q++){
int n = s.nextInt();
var[j][q] = n;
}
}
}
You have to replace the incrementation in the second loop too ("q++" instead of "p++")
This should work and solve their first point
Scanner s = new Scanner(System.in);
System.out.println("Enter the numbers of variables: ");
int i = s.nextInt();
int[][] var = new int[i][];
for(int j = 0;j < i;j++){
System.out.println("Enter the number of values: ");
int p = s.nextInt();
while (p>0)
{
var[j] = new int[p];
for(int q=0;q < p;q++){
System.out.println("Value number : " +(q+1) + " For Array Number "+ (j+1));
int n = s.nextInt();
var[j][q] = n;
}
p-=1;
}
}

About saving and printing distinct numbers in an array

before you help me this is a homework assignment, i have most of all of it done but there is one thing that i cant figure out, 0 doesn't get detected at all. This means if i input 0-9 into the array it will tell me there is only 9 distinct numbers when really there should be 10 and it will print out all the numbers but 0. Can anyone see the problem and please explain it to me becuase i need to understand it.
package javaproject.pkg2;
import java.util.Scanner;
public class JavaProject2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] numArray = new int[10];
int d = 0;
System.out.println("Enter Ten Numbers: ");
for(int i = 0; i < numArray.length; i++){
int num = input.nextInt();
if(inArray(numArray,num,numArray.length)){
numArray[i] = num;
d++;
}
}
System.out.println("The number of distinct numbers is " + d);
System.out.print("The distinct numbers are: ");
for(int i = 0; i < d; i++){
System.out.print(numArray[i] + " ");
}
}
public static boolean inArray(int[] array, int searchval, int numvals){
for (int i =0; i < numvals; i++){
if (searchval == array[i]) return false;
}
return true;
}
}
You can use a set to identify distinct values:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Set<Integer> distinctNumbers = new LinkedHashSet<>();
System.out.println("Enter ten Numbers: ");
for (int i = 0; i < 10; i++) {
int number = input.nextInt();
distinctNumbers.add(number);
}
System.out.println("The number of distinct numbers is " + distinctNumbers.size());
System.out.print("The distinct numbers are: ");
for (Integer number : distinctNumbers){
System.out.print(number + " ");
}
}
If a value already exists in a set, it can't be added again. Arrays are not the best fit for your problem, since they must be initialized with a fixed size and you don't know how many distinct values the user will inform.
Take a look at numArray after int[] numArray = new int[10]; - it is initialized with zeros.

Taking User Input for an Array

A link to the assignment:
http://i.imgur.com/fc86hG9.png
I'm having a bit of trouble discerning how to take a series of numbers and apply them to an array without a loop. Not only that, but I'm having a bit of trouble comparing them. What I have written so far is:
import java.util.Scanner;
public class Lottery {
public static void main(String[] args) {
int userInputs[] = new int[5];
int lotteryNumbers [] = new int[5];
int matchedNumbers =0;
char repeatLottery = '\0';
Scanner in = new Scanner (System.in);
do{
System.out.println("Enter your 5 single-digit lottery numbers.\n (Use the spacebar to separate digits): ");
for(int i = 0; i <5; i++ )
userInputs[i] = in.nextInt();
System.out.println("Your inputs: ");
printArray(userInputs);
System.out.println("\nLottery Numbers: ");
readIn(lotteryNumbers);
for(int i=0; i<5; i++) {
System.out.print(lotteryNumbers[i] + " ");
}
matchedNumbers = compareArr(userInputs, lotteryNumbers);
System.out.println("\n\nYou matched " + matchedNumbers + " numbers");
System.out.println("\nDo you wish to play again?(Enter Y or N): ");
repeatLottery = in.next().charAt(0);
}
while (repeatLottery == 'Y' || repeatLottery == 'y');
}
public static void printArray(int arr[]){
int n = arr.length;
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
}
public static void readIn(int[] List) {
for(int j=0; j<List.length; j++) {
List[j] = (int) (Math.random()*10);
}
}
public static int compareArr (int[] list1, int[] list2) {
int same = 0;
for (int i = 0; i <= list1.length-1; i++) {
for(int j = 0; j <= list2.length-1; j++) {
if (list1[i] == list2[j]) {
same++;
}
}
}
return same;
}
}
As you'll notice, I commented out the input line because I'm not quite sure how to handle it. If I have them in an array, I should be able to compare them fairly easily I think. This is our first assignment handling arrays, and I think it seems a bit in-depth for only having one class-period on it; So, please forgive my ignorance. :P
Edit:
I added a new method at the end to compare the digits, but the problem is it compares them in-general and not from position to position. That seems to be the major issue now.
your question isn't 100% clear but i will try my best.
1- i don't see any problems with reading input from user
int[] userInput = new int[5]; // maybe here you had a mistake
int[] lotterryArray = new int[5]; // and here you were declaring your arrays in a wrong way
Scanner scanner = new Scanner(system.in);
for ( int i = 0 ; i < 5 ; i++)
{
userInput[i] = scanner.nextInt();
} // this will populate your array try to print it to make sure
Edit : important in the link you shared about the assignment the compare need to check the value and location so if there are two 5 one in input one in loterry array they need to be in the same location check the assignment again
// to compare
int result = 0 ; // this will be the number of matched digits
for ( int i = 0 ; i < 5 ; i++)
{
if ( userInput[i] == loterryArray[i] )
result++
}
// in this comparsion if the digits are equale in value and location result will be incremented

Categories