How to deal with multiple lines input with Scanner - java

Input i have to deal with:
2
2 3
3 3
My code:
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int[][] array = new int[size][2];
Scanner scanner2 = new Scanner(System.in);
for (int i=0; i<size; i++) {
for (int j=0; j<2; j++) {
array[i][j] = scanner2.nextInt();
}
}
2 is number of pairs that input contains. I want to put those pairs in 2D array but I need to get 2 first to declare size of an array. Above code works well in NetBeans where I give input like:
number
enter
pair
enter
...
But all numbers come together in a format I posted above.
Any help?

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in).useDelimiter("\\n");
System.out.println("Enter an integer");
int size = scanner.nextInt();
int[][] array = new int[size][2];
for (int i = 0; i < size; i++) {
String myInt = scanner.next();
String[] myInts = myInt.split(" ");
for (int j = 0; j < 2; j++) {
array[i][j] = Integer.parseInt(myInts[j]);
}
}
// print contents
for (int i = 0; i < size; i++) {
for (int j = 0; j < 2; j++) {
System.out.println("[" + i + "]" + "[" + j + "] = " +array[i][j]);
}
}
}

Related

Having trouble searching array

So I have everything working fine up until the point in which I need to search. I'm really new to this so my code is probably awful I'm sorry in advance. Anyway, its a user input array, and the user should be able to search for a number in an array. Im getting the error for a duplicate variable on line 50 (int i, get 1).
import java.util.Scanner;
class SearchingSorting {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
System.out.println ("How many numbers would you like to input?");
int num = input.nextInt();
double[] array = new double[num];
for (int i = 0; i < num; i++) {
System.out.println ("Input number " + (1 + i) + ":");
array[i] = input.nextDouble();
}
for (double temp1 : array){
System.out.print (temp1 + "\t");
}
input.close();
int pass;
int i;
int hold;
for(pass = 1; pass < array.length; pass++)
{
for(i = 0; i < array.length - 1; i++)
{
if(array[i] > array[i+1])
{
hold = (int) array[i];
array[i] = array[i+1];
array[i+1] = hold;
}
}
System.out.println("\nSorted number is: ");
for(i = 0; i < array.length; i++)
System.out.print(" " + array[i]);
}
int i, get1;
Scanner keyboard = new Scanner(System.in);
int[] numbers = new int[10];
for(i = 0; i < numbers.length; i++)
{
numbers[i] = i * 10;
}
System.out.print("Enter search number: ");
get1 = keyboard.nextInt();
SearchMethod(numbers, get1);
}
public static void SearchMethod(int[] num, int get2)
{
int i ;
boolean j = false;
for(i = 0; i < num.length; i++)
{
if(num[i] == get2)
{
j = true;
break;
}
}
if(j == true)
System.out.println(get2 + " is found at num[" + i + "]");
else
System.out.println(get2 + " is not found in an array");
}
}
You are trying to declare a new variable with the same name ("i") in the same scope.
Rename your variable i on line 50.

Randomly place 1D string array into 2D char array

I'm trying to randomly place 1D string array into 2D char array but I'm having issues with my for-loop.
userWords is 1D array of String while puzzleBoard is a 2D array of char.
I've tried
for(int i=0; i<userWords.length;i++) {
puzzleBoard[r++] = userWords[i].toCharArray();
}
but it's not placing it randomly like I want it to
So I tried
for(int i=0; i<userWords.length;i++) {
int r = rand.nextInt(ROW) + 1;
int c = rand.nextInt(COLUMN) + 1;
puzzleBoard[r][c] = userWords[i].charAt(i);
}
but it's printing only 3 char instead of the 3 strings of char into the char array.
I've also tried
puzzleBoard[r][c] = userWords[i].toCharArray();
instead of
puzzleBoard[r][c] = userWords[i].charAt(i);
But it display error "cannot convert from char[] to char"
Thank you
Full Code
public static void main(String[] args) {
String[] userWords = new String[3];
Methods.userInput(userWords); //ask user for input
Methods.fillPuzzle(puzzleBoard); //fill the puzzle with random char
for(int i=0; i<userWords.length;i++) {
int r = rand.nextInt(ROW) + 1;
int c = rand.nextInt(COLUMN) + 1;
puzzleBoard[r][c] = userWords[i].charAt(i);
}
Methods.printPuzzle(puzzleBoard); //print out the puzzle
}//end main
public static void printPuzzle(char a[][]) {
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
System.out.print(a[i][j] + " ");
}
System.out.print((i+1));
System.out.println();
}
}//end printPuzzle
public static void fillPuzzle(char a[][]) {
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
a[i][j] = '*';
}
}
}//end fillPuzzle
public static void userInput(String a[]) {
Scanner input = new Scanner(System.in);
for(int i = 0; i < a.length;i++) {
System.out.println((i+1) + ". enter word:");
a[i] = input.next().toUpperCase();
}
}//end userInput
You can try this one:
for (int i = 0; i < userWords.length; i++) {
int r = rand.nextInt(puzzleBoard.length);
int c = rand.nextInt(puzzleBoard[r].length - userWords[i].length());
for (int j = 0; j < userWords[i].length(); j++) {
puzzleBoard[r][c + j] = userWords[i].charAt(j);
}
}
And you should add something that detects whether there is already a word at this position, otherwise you would overwrite it if the random numbers point to a location where is already written a word.
I think you should use 2 for-loops because you want to select first the string and next the characters in the string.
for(int i=0; i<userWords.length;i++) {
int r = rand.nextInt(ROW) + 1;
int c = rand.nextInt(COLUMN) + 1;
for (int j = 0; j < userWords[i].length(); j++) {
puzzleBoard[r][c + j] = userWords[i].charAt(j);
}
}

How to calculate the average of each row and column in array

So yesterday I asked for help, and a lot of people helped me out with my question, I really appreciated that guys. However, I run into a second problem of my homework, and I have been trying to solve it from this morning, and now it's like almost 2AM in the morning, and I'm not gonna sleep until I solve this problem. I'm not going to lie, so this is my homework to test the basic knowledge of mine. I know I make major mistakes somewhere, so please help me to point them out, so I can fix them. Thank you
The output should be:
1, 2, 3, ave=2
4, 5, 6, ave=5
aver=2.5, 3.5, 4.5
This is my current code:
import java.util.Scanner;
public class Ex {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a number for rows: ");
int rows = input.nextInt();
System.out.print("Enter a number for columns: ");
int columns = input.nextInt();
int[][] array = new int[rows][columns];
System.out.println("Enter the numbers in array: ");
for(int i=0 ; i<rows ; i++)
{
for(int j=0 ; j<columns ; j++)
{
array[i][j] = input.nextInt();
}
}
for(int i=0 ; i<rows ; i++)
{
for(int j=0 ; j<columns ; j++)
{
System.out.print(array[i][j] + " , ");
}
System.out.println("\n");
}
}
double averageRow(int[][] array) {
int rowTotal = 0;
double average = 0;
for (int rows = 0; rows < array.length; rows++) {
for (int columns = 0; columns < array[rows].length; columns++) {
rowTotal += array[rows][columns];
}
average = rowTotal / array[rows].length;
System.out.println(average);
rowTotal = 0;
}
return rowTotal;
}
double averageColumn(int[][] array) {
int columnTotal = 0;
double average = 0;
for (int columns = 0; columns < array.length; columns++) {
for (int rows = 0; rows < array[columns].length; rows++) {
columnTotal += array[rows][columns];
}
average = columnTotal / array[columns].length;
System.out.println(average);
columnTotal = 0;
}
return columnTotal;
}
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of rows");
int r = sc.nextInt();
System.out.println("Enter number of columns");
int c = sc.nextInt();
System.out.println("Enter values");
int[][] matrix = new int[r][c];
for (int i = 0; i < r; i++)
{
float rowSum = 0f;
for (int j = 0; j < c; j++)
{
matrix[i][j] = sc.nextInt();
rowSum += matrix[i][j];
}
System.out.println("Average of row " + i + " " + rowSum / c);
}
for (int i = 0; i < c; i++)
{
float columnSum = 0f;
for (int j = 0; j < r; j++)
{
columnSum += matrix[j][i];
}
System.out.println("Average of column " + i + " " + columnSum / r);
}
sc.close();
}
You can find the each row sum while reading the data. For column average run loop again. Hope you will sleep :)
You can print without calling other function.
import java.util.Scanner;
public class test8 {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a number for rows: ");
int rows = input.nextInt();
System.out.print("Enter a number for columns: ");
int columns = input.nextInt();
int[][] array = new int[rows][columns];
System.out.println("Enter the numbers in array: ");
for(int i=0 ; i<rows ; i++)
{
for(int j=0 ; j<columns ; j++)
{
array[i][j] = input.nextInt();
}
}
int rowSum = 0;
int colSumArr[] = new int[columns];
for(int i=0 ; i<rows ; i++)
{
for(int j=0 ; j<columns ; j++)
{
rowSum = rowSum + array[i][j];
colSumArr[j] = colSumArr[j] + array[i][j];
System.out.print(array[i][j] + " , ");
}
System.out.println( " ave=" + (double)rowSum/columns);
rowSum = 0;
}
System.out.printf("aver=");
for(int i=0;i<columns;i++){
if(i!=columns -1)
System.out.print((double)colSumArr[i]/rows + ", ");
else
System.out.print((double)colSumArr[i]/rows);
}
}
}

How do i output random numbers for 2 different arrays?

This is what i have so far but the output for both arrays is the same randomly generated numbers instead of different ones for each array.
import java.util.Scanner;
public class Prog2_b {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
System.out.println("Program #2b, Breanna Bergado, mascID 1885");
System.out.println("Please enter number of elements for a 1D array:");
int userVal = scnr.nextInt();
//System.out.println(((Object)userVal).getClass().getName();
double[] array = new double[userVal];
double [] array2 = new double[userVal];
double dotProd = 0;
for(int i = 0; i < userVal; i++) {
array[i] = Math.random();
array2[i] = Math.random();
}
for (int j = 0; j < 2; j++){
System.out.println("a"+(j+1)+"[]");
System.out.println("----------------");
for (int i = 0; i < userVal; i++) {
System.out.println(array[i] + " ");
}
System.out.println();
}
for(int i = 0; i < userVal; i++) {
dotProd = dotProd + array[i]* array2[i];
}
System.out.println("Dot Product is " + dotProd);
}
}
You should update your printing logic to:
for (int i = 0; i < userVal; i++) {
System.out.println(array[i] + " ");
}
System.out.println();
for (int j = 0; j < userVal; j++) {
System.out.println(array2[j] + " ");
}
Your current logic just prints the first array twice. You could also use nested arrays as one of the comments suggested, but the above code will work with what you have so far.

How to store input values in an array by using Scanner in Java

Hi I am new to Java and I was experimenting with the Scanner class.
I am trying to figure out a small problem in which I want to enter two inputs such as:
4 5 6 and 8 9 0.
I want to store 4,5,6 in one array and 8,9,0 in another array and then print these arrays.
But I am unable to do so.
I wrote the following code :
public class scanner {
public static void main(String[] args) {
int[] array = new int[3];
int[] array2 = new int[3];
Scanner scan = new Scanner(System.in);
int i = 0;
while(scan.hasNextInt()){
array[i] = scan.nextInt();
i++;
if(i == 3){
break;
}
}
i = 0;
while(scan.hasNextInt()){
array2[i] = scan.nextInt();
i++;
if(i == 3){
break;
}
}
for(int j = 0; j < array.length; j++){
System.out.println(array[j]);
}
for(int j = 0; j < array2.length; j++){
System.out.println(array2[j]);
}
}
}
But this doesn't takes the input 4 5 6 in one single line.
I want to enter 4 5 6 in one line so that all the three digits are stored in the array.
Can someone please help me. I assume I should use delimiter to remove the white space but I am not sure how to go about it.
You can try something like this, instead of the 2 while loops you've to populate your arrays.
Here the scanner reads line by line and each line is split on space (as you mentioned in your question) and then each splitted element is converted to an integer and the array is populated.
String line1 = scan.nextLine(); // Read 1st line
String[] numbers1 = line1.split(" "); // Split based on space
for(int i=0;i<numbers1.length;i++){
array[i] = Integer.parseInt(numbers1[i]);
}
String line2 = scan.nextLine(); // Read 2nd line
String[] numbers2 = line2.split(" "); // Split based on space
for(int i=0;i<numbers2.length;i++){
array2[i] = Integer.parseInt(numbers2[i]);
}
Sample I/O:-
Input:
1 2 3
4 5 6
Output:
1
2
3
4
5
6
To do this you have to get the String as a hole 4 5 6 and use split(" ") to get an array:
String val="4 5 6";
String [] arr = val.split(" ");
Then go on and loop your arry as you do now
int[] array = new int[3];
int[] array2 = new int[3];
Scanner scan = new Scanner(System.in);
for(int i = 0 ; i < array.length ; i++){
array[i] = scan.nextInt();
}
for(int i = 0 ; i < array2.length ; i++){
array2[i] = scan.nextInt();
}
for(int j = 0; j < array.length; j++){
System.out.println(array[j]);
}
for(int j = 0; j < array2.length; j++){
System.out.println(array2[j]);
Is this what you are looking for?
public class InputScanner {
public static void main(String[] args) {
int[] array = new int[3];
int[] array2 = new int[3];
Scanner scan = new Scanner(System.in);
int i = 0;
while (scan.hasNextInt()) {
array[i] = scan.nextInt();
i++;
if (i == 3) {
break;
}
}
i = 0;
while (scan.hasNextInt()) {
array2[i] = scan.nextInt();
i++;
if (i == 3) {
break;
}
}
for (int j = 0; j < array.length; j++) {
System.out.print("" + array[j] + (j<(array.length-1)?" ":"\n"));
}
for (int j = 0; j < array2.length; j++) {
System.out.print("" + array2[j] + (j<(array2.length-1)?" ":"\n"));
}
}
}
Your code is ok. The default delimiter for Scanner is whitespace according to javadoc.
The input is broken into tokens by the delimiter pattern, which is whitespace by default
What probably confuse you is that the print put each integer in a new line. To fix that you can simply write this:
for(int j = 0; j < array.length; j++){
System.out.print(array[j] + " ");
}
System.out.println();
for(int j = 0; j < array2.length; j++){
System.out.print(array2[j] + " ");
}
import java.util.*;
class Ab
{
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
String str=s.nextLine();
String [] arr=str.split(" ");
Integer [] a=new Integer[arr.length];
for(int i=0;i<arr.length;i++)
{
a[i]=Integer.parseInt(arr[i]);
}
for(int i=0;i<a.length;i++)
{
System.out.println(a[i]);
}
}
}
You may try this out and can make changes accordingly.

Categories

Resources