Java string manipulation x number of lines with y element - java

Easiest way to explain my problem is to give you an example. Lets say I have 2 values X and Y. I wan't to ask the user to enter X lines with Y elements and they should be only 0s and 1s and then enter that values in array.
Example
x=3 y=3
User input:
101
100
000
And then how to separate string to enter each value in different cell.
EDIT 1:
import java.util.Scanner;
public class RedVsGreen {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
int x,y;
String line;
String[] lineVector = new String[3];
while ( lineVector.length !=2 || (Integer.parseInt(lineVector[0]) >= 1000 || Integer.parseInt(lineVector[0]) <= 1)
|| (Integer.parseInt(lineVector[1]) <= 1 || Integer.parseInt(lineVector[1]) >= 1000)){
System.out.print("Please enter x and y, comma separated (more than 1 and less than 1000):");
//read x,y
line = scanner.nextLine();
//separate all values by comma
lineVector = line.split("\\s*,\\s*");
}
//parsing the values to Integer
x = Integer.parseInt(lineVector[0]);
y = Integer.parseInt(lineVector[1]);
for (i = 0 ; i < x; i++){
}
//
// int[][] field = new int[x][y];
// for (int row = 0; row < field.length; row++) {
// System.out.println("");
// for (int col = 0; col < field[row].length; col++) {
// field[row][col] = 9; //dummy value
// System.out.print(field[row][col] + " ");
// }
// }
//
}
}

Receiving x and y
while ( lineVector.length !=2 ...)
Your while condition is too complicated, a do while format matches this problem much better since you are going to get the values at least once, and the code is more readable.
Also you could have used x instead of Integer.parseInt(lineVector[0]) (same for y) instead of repeating the process, this would have shortened the condition.
String line;
String[] lineVector;
int x = -1, y = -1;
do {
System.out.print("Please enter x and y, comma separated (more than 1 and less than 1000):");
line = scanner.nextLine();
lineVector = line.split("\\s*,\\s*");
if(lineVector.length != 2)
continue;
x = Integer.parseInt(lineVector[0]);
y = Integer.parseInt(lineVector[1]);
} while (!((x > 1 && x < 1000 && y > 1 && y < 1000)));
First of all I removed the initial value of lineVector as it is unnecessary to initialize it in this case (you needed to do it because of it being present in your while condition).
I initialized x and y to -1 (Any number not in our range would work) in order to make sure the do-while condition is fulfilled until proper values are offered for both of the numbers.
Function to check binary values
Create a function to check if string values are binary.
public static boolean isBinary(String s) {
for(int i = 0; i < s.length(); ++i) {
char c = s.charAt(i);
if(c != '0' && c != '1')
return false;
}
return true;
}
Receive binaries
String[] binaries = new String[x];
System.out.println("Enter binaries with length " + y + " :");
//Get binaries
for(int i = 0; i < x; ++i) {
binaries[i] = scanner.nextLine();
while(!isBinary(binaries[i]) || binaries[i].length() != y) {
System.out.println("Invalid binary value. Re-enter new value:");
binaries[i] = scanner.nextLine();
}
}
Receive binary values and continue asking if invalid.
Filling the 2D array
int[][] field = new int[x][y];
for(int i = 0; i < x; ++i) {
System.out.println();
for(int j = 0; j < y; ++j) {
char c = binaries[i].charAt(j);
if(c == '0')
field[i][j] = 0;
else
field[i][j] = 1;
System.out.print(field[i][j] + " ");
}
}
Integer.parseInt is not necessary here as there are only two possible values (0 and 1)

Related

Limit number of input lines in Java?

I have a problem where I want to take input from the user, the user can insert 1 and up to 8 lines, and each line represents a case.
What I want is to stop the scanner when the user inserts 8 lines, Or if the user wants less than 8 he can press enter or a specific key to end the loop.
What I have done so far:
public static void doSomthing(){
Scanner input = new Scanner(System.in);
while (input.hasNextLine()) { // here I want to check so that it don't exeed 8 lines
int e;
int m;
i = input.nextInt();
j = input.nextInt();
int num = 0;
while (i != 0 || j != 0) {
num += 1;
e = (e + 1) % 100;
m = (m + 1) % 400;
}
System.out.println(num);
}
}
The input should be two numbers in each line, one for i and one for j.
Input:
0 0
100 300
99 399
0 200
Output should be:
C1: 0
C2: 100
C3: 1
C4: 200
Hope this explains my problem.
Thanks in advance!
As #Abhishek suggested, you can use a counter variable:
public static void doSomthing(){
Scanner input = new Scanner(System.in);
int linesParsed = 0;
while (linesParsed < 8 && input.hasNextLine()) {
// What are you using these variables for? You compute their
// values, but then you do not use them
int e;
int m;
// Where are these variables declared? It seems weird to have
// instance variables be named i and j
i = input.nextInt();
j = input.nextInt();
int num = 0;
// Unless i and j are being modified concurrently somewhere
// else in the code, this will result in an infinite loop
while (i != 0 || j != 0) {
num += 1;
e = (e + 1) % 100;
m = (m + 1) % 400;
}
System.out.println(num);
linesParsed++;
}
}

how to calculate total number of combinations for 4*3 matrix where 2 elements in matrix are not present

below is the format of the matrix. and no diagonal combinations of letters is allowed ,only vertical and horizontal combinations are allowed.
Can anyone suggest how to calculate the number of combinations required for a particular level.
example: if i say level is 1 then , only 1 letter combination is allowed i.e. A,B,C,D,E,F,G,H,I i.e. 10 combinations
if i say level is 2 then possible combinations are AA,BB,AB,AD,BC,BE,... and so on so total 36 combinations for level 2.
Like that if input is any level number given, then how do i calculate the possible number of combinations ?
A B C
D E F
G H I
J
I tried using this formula :
(n!/(r!(n-r)!)
but it doesnt calculate properly from level 2 onwards.
note : on both sides of J no letter is present.
Please suggest.
#Thientvse
This is the code that i coded... it gives correct output...can you please tell me whether my code is correct and whether it will satisfy all test cases for this scenario
import java.util.ArrayList;
import java.util.Scanner;
public class Game {
public static int combinationCounts(int input1){
ArrayList<String> mainalternatestring = new ArrayList<String>();
ArrayList<String> mainverticalstring = new ArrayList<String>();
String sb = "ABC#DEF#GHI# J ";
String a=null,b=null,c=null,nw=null;
int mainindex = 0,counter,totalcount=10,index=0,mainindex_duplicate=0,count=1;
if(input1 > 1 && input1 <= 4){
while(mainindex != 11){
int level = 0;
counter = 0;
count=1;
char[] strtoworkon = new char[sb.length()];
index=0;
if(mainindex != 0)
mainindex = mainindex+1;
for(int j = mainindex; count!= (sb.length()-mainindex) ; j++){
if(level == input1)
break;
if(sb.charAt(j) == '#'){
level++;
if (counter == 0){
mainindex_duplicate = j;
counter = 1;
}
}
if(level <= input1){
strtoworkon[index] = sb.charAt(j);
index++;
}
count++;
}
mainindex = mainindex_duplicate;
// for sideways combinations
for(int m = 0; m <= strtoworkon.length; m++){
c = null;
if(strtoworkon[m] == ' ')
break;
if(!String.valueOf(strtoworkon).substring(m, m+(input1)).contains("#")){
c = String.valueOf(strtoworkon).substring(m, m+(input1));
if(!c.matches(".*[A-Z].*"))
break;
if(!mainalternatestring.contains(c))
mainalternatestring.add(c);
}
}
//for vertical combinations
nw = "#" + (String.valueOf(strtoworkon));
int counter1=0;
while(counter1 != 3){
c="";
for(int n = 0; n<= strtoworkon.length; n++){
if(nw.charAt(n) == '#'){
Character test = nw.charAt(n+counter1);
a = Character.toString(strtoworkon[n+counter1]).trim();
if(a.contains("#"))
break;
c = a+c;
c.trim();
}
}
if(!mainverticalstring.contains(c) && c.length() == input1)
mainverticalstring.add(c);
counter1++;
}
if(mainindex == 11)
break;
}
totalcount = totalcount + (2*mainalternatestring.size()) + (2*mainverticalstring.size());
}
return totalcount;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int output = 0;
int ip1 = Integer.parseInt(in.nextLine().trim());
output = combinationCounts(ip1);
System.out.println(String.valueOf(output));
}
}

Java : nested loops

I'm very new in Java Programming Language.
I asked to make something like this with nested loops method:
.
"Masukan Angka" is "Input Number" in Indonesian Language. So if we input 9, it will print out 9 lines of * and the amount of * decreased for each line.
I tried it with nested loops, this is what i made :
The code is :
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Input your number: ");
int x = in.nextInt();
for (int y = x; y > 0; y--) {
for (int z = 0; z < y; z++)
System.out.print("*");
System.out.println();
}
}
How can i make it doesn't filled up with * in the line 2-7, but instead filled with blank space like the example in the first picture?
Thanks in advance.
Expanding a bit on #Ringuerel solution:
for (int y = x; y > 0; y--) {
for (int z = 0; z < y; z++) {
// If it's first or last or first row print "*"
if( z == 0 || z == y-1 || y == x) {
System.out.print("*");
}
else {
// Otherwise print " "
System.out.print(" ");
}
}
System.out.println();
}
Add this after the second for, before the print statement, if( z == 0 || z == y-1 ), sorry I'm using my phone
public static void main(String[] args) {
int amount = 10;
String c = "*";
String message = "";
for (int i = 0; i < amount; i++) {
message += "*";
for (int j = 1; j < amount - i; j++) {
message += c;
}
message += "*";
c = " ";
System.out.println(message);
message = "";
}
System.out.println("*");
}
You can try this if you want. Haven't tested it but I'm fairly certain it will work.

Java: While Loop still running even when the condition is false

I'm fairly new at coding and in java in general but I'm hoping that I could get this figured out. I have a do while loop and inside that, I have a while statement if the incorrect value is input in the Scanner. However, when I run the code it always runs the while command once regardless of whether it is incorrect or correct and then runs the code correctly.
import java.util.Scanner;
public class Practice {
public static void main (String [] args) {
int x = 0;
int i = 0;
int n = 0;
String S1 = "";
Scanner user = new Scanner(System.in);
do
{
System.out.println("Enter an integer between 1 and 15: ");
x = user.nextInt();
while ( x < 1 || x > 15);
{
System.out.println("Incorrect integer. Must be between 1 and 15. Try again: ");
x = user.nextInt();
}
n = 1;
}
while (n != 1);
for (i = 1; i <= x; i++)
{
S1 = S1 + "X";
}
for (n = 1; n <= x; n++)
{
System.out.println(S1);
}
}
}
Thank you so much in advance.
Remove the extra ; from your while loop
Like this:
while ( x < 1 || x > 15){
System.out.println("Incorrect integer. Must be between 1 and 15. Try again: ");
x = user.nextInt();
}
while ( x < 1 || x > 15);
The Semi-Colon will terminate the logic and the control will pass to the next line always. Be careful while you code :D
Remove the extra semicolon in the while.
Also close the scanner object(user).
Check the updated code.
public class Practice {
public static void main(String[] args) {
int x = 0;
int i = 0;
int n = 0;
String S1 = "";
Scanner user = new Scanner(System.in);
do {
System.out.println("Enter an integer between 1 and 15: ");
x = user.nextInt();
while (x < 1 || x > 15)
{
System.out.println("Incorrect integer. Must be between 1 and 15. Try again: ");
x = user.nextInt();
}
n = 1;
} while (n != 1);
for (i = 1; i <= x; i++) {
S1 = S1 + "X";
}
for (n = 1; n <= x; n++) {
System.out.println(S1);
}
user.close();
}
}

In a Java Memory game, how do I trigger that 2 unknown has been discovered, and make them stay revealed for the rest of the game?

I'm currently doing a java memory game that makes the user guess duplicate letters by input the coordinate of either a 2x2, 4x4 or 6x6 square, which have 2 sets of repeating letters
ex. for 4x4 it would be
A B C D
E F G H
A B C D
E F G H
but randomized
If they guess correctly the letters would stay revealed, until all are found.
I have successfully randomized the square, and cover it with ( * ), and make them reveal based on the input coordinates
But I don't know how to make that once the 2 revealed letters are the same, the program will keep them revealed through out the game, until all duplicate letters are revealed.
The code right now (You can copy and paste whole thing below, all comments are commented out):
import java.util.Scanner;
import java.io.IOException;
public class a4{
// main method. DO NOT MODIFY
public static void main(String args[]) {
Scanner keyboard = new Scanner( System.in );
System.out.println("Welcome to Memory Game");
int board_side;
//this loop obtains the board size, or more specifically
// the length of the side of the board
do{
System.out.println("\n For 2x2 board game press 2"+
"\n For 4x4 board game press 4"+
"\n For 6x6 board game press 6");
board_side=keyboard.nextInt();
}while(board_side!=2 && board_side!=4 && board_side!=6);
char[][] board = createBoard(board_side);
// a call the the shuffle method
shuffleBoard(board);
// a call to the game playing method
playGame(board);
}
// The following method should shuffle the input 2D array caled board
public static void shuffleBoard(char[][] board)
{
// This creates a 1D array whose size is equal to the size of the board
int N = board.length*board.length;
char[] board1D = new char[N];
// Testing to see the printed square
for ( int i = 0; i < board.length; i++) {
for ( int j = 0; j < board[i].length; j++) {
System.out.print( board[i][j] + " " );
}
System.out.println();
}
System.out.println();
for (int i =0; i < board1D.length; i++) {
System.out.print(board1D[i] + " ");
}
System.out.println();
// Copy the elements of 2D array into that 1D array here
for (int m = 0; m < N; m++){
for (int i = 0; i < board.length; i++){
for (int j = 0; j < board.length; j++, m++){
board1D [m] = board[i][j];
}
}
}
// Shuffle 1D array
// Shuffle the array
for (int i = 0; i < N; i++) {
// Generate an index randomly
int index = (int)(Math.random() * N);
char temp = board1D[i];
board1D[i] = board1D[index];
board1D[index] = temp;
}
//Testing to see the 1D array
System.out.println();
for (int i =0; i < board1D.length; i++) {
System.out.print(board1D[i] + " ");
}
System.out.println();
//Copy shuffled 1D array back into 2D array, i.e., back to the board
for (int m = 0; m < N; m++){
for (int i = 0; i < board.length; i++){
for (int j = 0; j < board.length; j++, m++){
board[i][j] = board1D [m];
}
}
}
//Testing to print the shuffled square
for ( int i = 0; i < board.length; i++) {
for ( int j = 0; j < board[i].length; j++) {
System.out.print( board[i][j] + " " );
}
System.out.println();
}
System.out.println();
System.out.println();
}
// game playing method
public static void playGame(char[][] board)
{
Scanner keyboard = new Scanner( System.in );
// this createst a 2D array indicating what locations are paired, i.e., discovered
// at the begining none are, so default initializaiton to false is ok
boolean[][]discovered=new boolean[board.length][board[0].length];;
for ( int i = 0; i < board.length; i++) {
System.out.print(1 + i + " ");
for ( int j = 0; j < board[i].length; j++) {
System.out.print( "* " );
}
System.out.println();
}
System.out.print(" ");
for ( int x = 0; x < board.length; x++) {
System.out.print(1 + x + " ");
}
System.out.println();
System.out.println();
System.out.println("Enter a pair of undiscovered distinct locations on the board that you want revealed. i.e., a pair of integers in the range [1, 2]");
System.out.println();
int FirstLocationX;
int FirstLocationY;
int SecondLocationX;
int SecondLocationY;
do {
System.out.println("Enter the first location: ");
FirstLocationX=keyboard.nextInt();
FirstLocationY=keyboard.nextInt();
if (FirstLocationX > board.length && FirstLocationY > board.length){
System.out.println("The location is invalid. It is outside of the board. ");
}
} while(FirstLocationX > board.length && FirstLocationY > board.length);
System.out.println();
do {
System.out.println("Enter the second location: ");
SecondLocationX=keyboard.nextInt();
SecondLocationY=keyboard.nextInt();
if (SecondLocationX > board.length && SecondLocationY > board.length){
System.out.println("The location is invalid. It is outside of the board. ");
}
else if (SecondLocationX == FirstLocationX && SecondLocationY == FirstLocationY){
System.out.println("The location is invalid. The second location equal to the first. ");
}
} while(SecondLocationX > board.length && SecondLocationY > board.length && SecondLocationX == FirstLocationX && SecondLocationY == FirstLocationY);
//reveals the letters based on the coordinate user inputed
for ( int i = 0; i < board.length; i++) {
System.out.print(1 + i + " ");
for (int j = 0; j < board[i].length; j++) {
if (FirstLocationX == i+1 && FirstLocationY == j+1){
System.out.print( board[i][j] + " " );
}
else if (SecondLocationX == i+1 && SecondLocationY == j+1){
System.out.print( board[i][j] + " " );
}
/*This part is wrong, reveals the whole square instead of the found duplicates
else if (discovered[0][0] = true){
System.out.print( board[i][j] + " " );
}
else if (discovered[0][2] = true){
System.out.print( board[i][j] + " " );
}
*/
else {
System.out.print( "* " );
}
}
System.out.println();
}
System.out.print(" ");
for ( int x = 0; x < board.length; x++) {
System.out.print(1 + x + " ");
}
System.out.println();
System.out.println();
char[][] FirstInput = new char[FirstLocationX][FirstLocationY];
char[][] SecondInput = new char[SecondLocationX][SecondLocationY];
/*GETTING AN ERROR HERE when I try to trigger a duplicate letter found, since the array is shuffled I don't know how exactly, just testing with the first match right now (A and A), which suppose to be coordinate 0,0 and 0,2 in the non-sorted square matrix
*/
if (board[0][0] == FirstInput[FirstLocationX][FirstLocationY] && board[0][2] == SecondInput[SecondLocationX][SecondLocationY]){
discovered[0][0] = true;
discovered[0][2] = true;
}
waitForPlayer();
do {
playGame(board);
}while(discovered[0][0] == false && discovered[0][2] == false);
}
// createBoard method. DO NOT MODIFY!
/* this method, createBoard, creates the board filled with letters of alphabet,
where each letter appears exactly 2 times
e.g., for 4 x 4, the returned board would look like:
A B C D
E F G H
A B C D
E F G H */
public static char[][] createBoard(int side)
{
char[][] tmp = new char[side][side];
int letter_count=0;
for (int row = 0; row < tmp.length/2; row++){
for(int col = 0; col < tmp[row].length; col++)
{
tmp[row][col]=(char)('A'+letter_count);
tmp[row+tmp.length/2 ][col]=tmp[row][col];
letter_count++;
}
}
return tmp;
}
// waitForPlayer method. Do not modify!
public static void waitForPlayer()
{
System.out.print("Press enter to continue");
try {
System.in.read();
}
catch (IOException e){
System.out.println("Error reading from user");
}
}
}
The current part that is wrong is:
char[][] FirstInput = new char[FirstLocationX][FirstLocationY];
char[][] SecondInput = new char[SecondLocationX][SecondLocationY];
/*when I try to trigger a duplicate letter found, since the array is shuffled I don't know how exactly, just testing with the first match right now (A and A), which suppose to be coordinate 0,0 and 0,2 in the non-sorted square matrix
*/
if (board[0][0] == FirstInput[FirstLocationX][FirstLocationY] && board[0][2] == SecondInput[SecondLocationX][SecondLocationY]){
discovered[0][0] = true;
discovered[0][2] = true;
}
waitForPlayer();
do {
playGame(board);
}while(discovered[0][0] == false && discovered[0][2] == false);
}
and
else if (discovered[0][0] = true){
System.out.print( board[i][j] + " " );
}
else if (discovered[0][2] = true){
System.out.print( board[i][j] + " " );
}
I would suggest making each square as an object instead of having a mere char. That way you can control if they are revealed or not when you display then
Edit
Without objects, you can just create another array of bool that will track what is displayed. Whenever a pay is revealed, set the values inside that alternative board to true, then in your display function check if it is true before showing it
I would do the following:
Create an char[][] array in which the amount of * equals the input characters.
e.g.:
ABCD
DACB
'*****'
'****'
Get the coordinates which the user enters and compare them logically, if both characters are the same, then replace the corresponding * with the character.
e.g:
if the user input would be 0,0 for the first char and 1,1 for the second (both A)
then update the array to:
ABCD
DACB
A***
*A**
all the lines will be in one array but in the game you would print only the second two rows. The offset between the first two rows and the second two rows is the same, so it should be no problem to do that.

Categories