I need to fill 2D array using input without spaces, so for this I'm trying to use 'String' firstly.
import java.util.Scanner;
import java.util.Arrays;
public class TikTakToe {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
char[][] TikTakToe = new char[3][3];
System.out.print("Enter cells: ");
String enter = scanner.next();
for (int i = 0; i < TikTakToe.length; i++) {
for (int j = 0, l = 0; j < TikTakToe[i].length && l < enter.length(); j++, l++) {
TikTakToe[i][j] = enter.charAt(l);
}
}
for (char[] chars : TikTakToe) {
System.out.println(Arrays.toString(chars).substring(1).replaceFirst("]",
"").replace(", ", " "));
}
}
}
Input: XOXOXOXOX
Output:
X O X
X O X
X O X
The problem in this solving that variable 'l' resets after outer 'for' loop goes to the next stage. How can I fix it?
You're problem is that you defined the variable l in the nested for loop. Consequently, when that loop returns, l is deleted.
What you would need to do is define l before the first loop, that way its scope is the whole method.
...
char[][] TikTakToe = new char[3][3];
System.out.print("Enter cells: ");
String enter = scanner.next();
int l = 0; // <-- **I moved the declaration here**
for (int i = 0; i < TikTakToe.length; i++) {
for (int j = 0 /*removed the declaration from here*/; j < TikTakToe[i].length && l < enter.length(); j++, l++) {
TikTakToe[i][j] = enter.charAt(l);
}
}
...
You should initialize int l = 0 outside the loop. As it will be re-initialized when inner loop will run.
So your final code would look like :-
import java.util.Scanner;
import java.util.Arrays;
public class TikTakToe {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
char[][] TikTakToe = new char[3][3];
System.out.print("Enter cells: ");
String enter = scanner.next();
int l = 0; // initialize here
for (int i = 0; i < TikTakToe.length; i++) {
for (int j = 0; j < TikTakToe[i].length && l < enter.length(); j++, l++) {
TikTakToe[i][j] = enter.charAt(l);
}
}
for (char[] chars : TikTakToe) {
System.out.println(Arrays.toString(chars).substring(1).replaceFirst("]",
"").replace(", ", " "));
}
}
Related
I just learned how to use nested loops today and the task I am required to do is quite simple but I am not able to execute it properly, although with the same idea.
The task is to input a character, an integer that is the rows**(n), and another integer that is the columns **(m)
It should display the rectangular pattern with n rows and m columns
Sample input:
*
3
2
Here the number of rows is 3 and the number of columns is 2
Sample output:
**
**
**
This has to be done using nested for loops only
My code:
import java.util.Scanner;
class Example {
public static void main (String[] args) {
Scanner keyboard = new Scanner(System.in);
String character = keyboard.next();
int n = keyboard.nextInt();
int m = keyboard.nextInt();
for (int x = m; x <= m; x++) {
for (int y =n ; y <= n; y++) {
System.out.print(character);
}
System.out.println("");
}
}
}
The output I am getting:
*
You should use a loop like this start from 0 to row and j from 0 to col for each row, and close the scanner after reading
public static void main(String[] arg) {
Scanner keyboard = new Scanner(System.in);
String character = keyboard.next();
int col = keyboard.nextInt();
int row = keyboard.nextInt();
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
System.out.print(character);
}
System.out.println("");
}
keyboard.close();
}
, output
***
***
You should start from 0 in both loops until reaching < m and < n as follows:
Scanner keyboard = new Scanner(System.in);
String character = keyboard.next();
int n = keyboard.nextInt();
int m = keyboard.nextInt();
for (int x = 0; x < m; x++){
for (int y = 0; y < n; y++){
System.out.print(character);
}
System.out.println("");
}
A sample input/output would be:
*
3
2
***
***
what is wrong in your code is that you are starting loop from m itself instead you should think it like how many times you want to run the loop.
With that in mind try running the code from 0 to m and inner loop from 0 to n.
This mindset will help you in learning while loop also.
import java.util.Scanner;
class Example {
public static void main (String[] args)
{
Scanner keyboard = new Scanner(System.in);
String character = keyboard.next();
int n = keyboard.nextInt();
int m = keyboard.nextInt();
for (int x = 0;x<m;x++){
for (int y=0;y<n;y++){
System.out.print(character);
}
System.out.println("");
}
}
}
Im trying to practice some java and I am confused. I am trying to enter in multiple numbers into a 3*3 array, however when I run my program I get a compliation error (Exception in thread "main"java.lang.NumberFormatException)? How can parse multiple ints from a Joptionpane into the arrays?
public static int[][] enterMatrix() {
String NumberstoParse = JOptionPane.showInputDialog("Enter list: ");
int UserInput = Integer.parseInt(NumberstoParse);
int[][] matrix = new int[3][3];
for (int i = 0; i < matrix.length; i++)
for (int j = 0; j < matrix[i].length; j++)
matrix[i][j] = UserInput;
return matrix;
}
}
I think the main issue is when parsing the String from the JOptionPane. Integer.parseInt() sees the commas and throws NumberFormatException. Might be worthwhile to do some testing of this method, possibly with JShell!
Here, I have taken the input String "1, 2, 3, 4, 5, 6, 7, 8, 9" and used method split from class String to make an array of String that is split by (",\s+"). This means, split around the matching regular expression, which here is "a comma and one or more white space characters". Each individual String from the array is then processed with Integer.parseInt().
public static int[][] enterMatrix() {
String numberstoParse = JOptionPane.showInputDialog("Enter list: ");
String[] splitNumbers = numberstoParse.split(",\\s+");
int[][] matrix = new int[3][3];
int ctr = 0;
for (int i = 0; i < matrix.length; i++)
for (int j = 0; j < matrix[i].length; j++) {
matrix[i][j] = Integer.parseInt(splitNumbers[ctr]);
ctr++;
}
return matrix;
}
Adding to what Alex already added below is the code which will take care of some border line issues there are some test cases include few test cases. The code is documented, I hope this helps...
public class Dummy
{
public static void main(String[] args)
{
String temp = "";
for(int x = 0; x <10; x++){
temp = temp + x+"";
int[][] matrix = enterData(temp);
System.out.println("Given Input:" + temp);
if(matrix != null){
for (int i = 0; i < matrix.length; i++){
for (int j = 0; j < matrix[i].length; j++)
System.out.print(matrix[i][j] + " ");
System.out.println();
}
}
System.out.println("-------------");
temp +=",";
}
}
//Once you understand the test cases, you can remove the argument and use the JOptionPane for input
public static int[][] enterData(String input)
{
//TODO: Please user JOPtionPane I have added this just to make the test cases work
//String input = JOptionPane.showInputDialog("Enter list: ");
//This will split the Input on the basis of ","
String[] inputArr = input.split(",");
//Variable has a counter which which will represent the number of inputs received
int inputArrCount = 0;
int[][] matrix = new int[3][3];
//If the size is greater than 9, then as u suggested an error is printed
if(inputArr.length > 9 ){
System.err.println("Number length > 9");
return null;
}
for(int i = 0; i <matrix.length; i++){
for (int j = 0; j < matrix[i].length; j++){
//If to just track that inputArrCount never goes beyond the inputArr elements
if(inputArrCount < inputArr.length){
int temp = Integer.parseInt(inputArr[inputArrCount++]);
matrix[i][j] = temp;
}
}
}
return matrix;
}
}
I have to take a user input of integers from a range, convert that to binary, and fill a 3x3 array with the binary. The only problem is, my code is giving me an output of only dependent on the first 3 numbers of that binary (i.e 010001101 = 010 across all rows).
import java.util.Scanner;
public class HW11P02 {
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
System.out.print("Enter a number between 0 and 511: ");
int n = in.nextInt();
String binary = Integer.toBinaryString(n);
binary = binary.format("%09d", Integer.parseInt(binary));
System.out.println(binary);
listArray(binary);
};
public static String[][] listArray(String binary) {
String[][] array = new String[3][3];
char ch = ' ';
String value = "";
for (int i = 0; i < 3; i++) {
for (int n = 0; n < 3; n++) {
ch = binary.charAt(n);
value = Character.toString(ch);
array[i][n] = value;
System.out.print(array[i][n] + " ");
}
System.out.println();
}
return array;
}
};
I think this will provide the the output you may really want.
import java.util.Scanner;
public class HW11P02
{
public static void main(String[] args)
{
Scanner in = new Scanner (System.in);
System.out.print("Enter a number between 0 and 511: ");
int n = in.nextInt();
String binary = Integer.toBinaryString(n);
binary = binary.format("%09d", Integer.parseInt(binary));
System.out.println(binary);
int result[][]=new int[3][3];
int position=0;
for (int i = 0; i < result.length; i++)
{
for (int j = 0; j < result.length; j++)
{
result[i][j]=binary.charAt(position++)-'0';
System.out.print(result[i][j]+" ");
}
System.out.println();
}
}
}
My program will output a graphical representation of some rows and columns. It asks the users to input the number of rows and columns they want to see the figure for. For example if the user chooses 4 rows and 3 columns, it should print a figure (let's say it's made up of character X) which has 4 rows and 3 columns.
The final output will look like this:
X X X
X X X
X X X
X X X
Now the problem is I can't set the logic in my for loop so that it makes the desired shape. I tried, but couldn't figure it out.
This what I have done so far:
package banktransport;
import java.util.*;
public class BankTransport {
static int NumOfRow;
static int numOfColum;
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
showRowCol(NumOfRow, numOfColum);
}
public static void showRowCol(int NumOfRow, int numOfColum) {
System.out.println("Enter row: ");
NumOfRow = input.nextInt();
System.out.println("Enter Col: ");
numOfColum = input.nextInt();
System.out.println("");
System.out.println("Visual Representation: ");
//print column and row
for (int i = 0; i < numOfColum; i++) {
System.out.print(" X ");
//System.out.println("");
//for(int j=1; j<(NumOfRow-1);j++){
// System.out.print(" Y ");
//}
}
System.out.println("");
}
}
Try a loop like this:
for ( int i = 0; i < numOfRow; i++ )
{
for ( int j = 0; j < numOfColum; j++ )
{
System.out.print(" X ");
}
System.out.println();
}
Try:
for (int i = 0; i < numOfRow; i++) {
StringBuilder line = new StringBuilder();
for (int j = 0; j < numOfColumn; j++) {
line.append("X ");
}
System.out.println(line.toString());
}
You can also use Apache Commons Lang StringUtils.repeat method (which would prevent you from having a trailing space at the end of the line):
for (int i = 0; i < numOfRow; i++) {
System.out.println(StringUtils.repeat("X", " ", numOfColumn));
}
Ok, so here are my codes (main method and method I'm trying to call)
I want my method "rotateRR" to basically take the value from board[0] and put it on [1] and keep doing that for that single row. For example:
old array -> [1][2][3][4][5] to become [5][1][2][3][4] <- what new array should look like.
but after I call my method, I put my regular input which should be "1 rr", but it returns the same array. I need to return the updated array from rotateRR method, but it doesn't let me add a return statement.
public class Numbrosia {
static int [][] board = new int[5][5];
public static void main(String [] args){
Scanner scan = null;
try{
scan = new Scanner(new File("input.txt"));
}
catch (FileNotFoundException e){
e.printStackTrace();
return;
}
for(int i = 0; i < board.length; i++){
for(int j = 0; j < board.length; j++){
board[i][j] = scan.nextInt();
}
}
Scanner input = new Scanner (System.in);
while (true){
showBoard();
System.out.println("What's your move?");
int rowOrCol = input.nextInt();
String action = ("");
action = input.nextLine();
if (action.equals(rowOrCol + " rr")){
rotateRR(board);
System.out.println("The new board looks like: ");
//Im guessing I should put something here?
}
}
}
public static void showBoard(){
for(int row = 0; row < board.length; row++){
for(int col = 0; col < board.length; col++){
System.out.print(board[row][col] + " ");
}
System.out.println(" ");
}
}
//METHODS
public static void rotateRR (int [][] board){
int[] temp = board[0];
for (int i = 0; i < board.length + 1; i++){
board[i] = board[i+1];
}
board[board.length + 1] = temp;
}
//Its not letting me add a "return" type, tells me it is a syntax error on and an invalid type
The main problem with the method is that it's not even doing what you described as the functionality:
public static void rotateRR (int [][] board){
int[] temp = board[0];
for (int i = 0; i < board.length + 1; i++){
board[i] = board[i+1];
}
board[board.length + 1] = temp;
}
Should be changed to:
public static void rotateRR (int [][] board){
// Saves the last entry of board, because
// each entry should be shifted to the right
int[] temp = board[board.length - 1];
// Here you should only run till board.length - 2, because
// if you add 1 to i for accessing the next entry
// you can maximal access the entry with number board.length - 1
for (int i = 0; i < board.length - 1; i++){
board[i] = board[i+1];
}
// Set the first entry to temp
board[0] = temp;
}
So after that method your array you inserted as a parameter is changed the way you described above. Notice that you don't need a return type, since the change affects the original array (keyword call-by-reference).
You have made the function void therefore you cannot return anything from it. So what you need to do is change it from void to something like char * and then return the associated char * to solve your problem
Read this: http://docs.oracle.com/javase/tutorial/java/javaOO/returnvalue.html for any further doubts.
Change this:
public static void showBoard()
to this
public static return-type showBoard()