Count and print even flowers - java

We have n number of flowers that can be black or white. We have m number of months. At the end of each month, if the number of white flowers is even, we print B for the number of roses that are even, and print F for the rest of the characters.For example:(W=white,B=black)
input:3(n) 2(m)
WBW
BBW
output:FBB
My code just work well just for this example and dont give true answer for other examples.
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter number of flowers: ");
int flower = input.nextInt();
System.out.println("Enter number of months : ");
int month = input.nextInt();
String[] arr = new String[month];
char ch = ' ';
int count = 0;
for (int j = 0; j < month; j++)
arr[j] = input.next();
for (int i = 0; i < month; i++) {
char[] s = arr[i].toCharArray();
for (int j = 0; j < flower; j++) {
if (s[j] == 'W') {
count++;
}
}
if (count % 2 == 0) {
for (int k = 0; k < flower - count; k++) {
System.out.print('F');
}
for (int b = 1; b <= count; b++) {
System.out.print('B');
}
}
}
}
}

In your for loop
for (int j = 0; j < flower; j++) {
if (s[j] == 'W') {
count++;
}
}
We must remember what s is referring to, char[] s = arr[i].toCharArray(); which means that s will not have a length of flower but will have a length of arr[i].length() or s.length.
So if you change the for loop to use that as its control, it should solve the index out of bounds exception that you get.
The fix would look like:
for (int j = 0; j < s.length; j++) {
if (s[j] == 'W') {
count++;
}
}

Related

Find lowest matching values in Java

I created this program that allows the user to input 5 numbers for array 1 and 5 numbers for array 2, the idea of the program is to iterate through those arrays and find the matching values for example: user types on input 1 = 1, 2, 3, 4 and 5 and the same for input 2, the lowest matching value is 1 and my program does that, if there is no matching value displays a message that there is no matching values and my program does that. However, if the user inputs something like this on 1 = 3, 4, 5, 7, 2 and input 2 = 9, 12, 8, 7, 15, what my program does in this case, variable min1 on array1 find lowest value which is 2 and variable min2 on array2 find lowest value which is 7 so in theory does not match, but they are asking me to find the lowest MATCHING values so both of them have 7 so it should display 7, I have some code there that select the 7 on each array and display them, now I have to figure out how to add that temporal variable into the displays so it only displays one or the other, as of now it displays 7 and then no matching value, tried adding it to the if statement but couldn't make it
import java.util.Scanner;
public class SmallestArrayItem {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int array1[] = new int[5];
int array2[] = new int[5];
System.out.println("Please enter 5 values for array 1");
for(int i = 0; i < array1.length; i++) {
int userInput = keyboard.nextInt();
array1[i] = userInput;
}
System.out.println("Please enter 5 values for array 2");
for(int i = 0; i < array2.length; i++) {
int userInput = keyboard.nextInt();
array2[i] = userInput;
}
int min1 = array1[0];
for(int index1 = 1; index1 < array1.length; index1++) {
if(array1[index1] < min1) {
min1 = array1[index1];
}
}
int min2 = array2[0];
for(int index2 = 1; index2 < array2.length; index2++) {
if(array2[index2] < min2) {
min2 = array1[index2];
}
}
int tmpval = Integer.MAX_VALUE;
for(int i = 0; i < array1.length; i++){
for(int j = 0; j < array2.length; j++){
if(array1[i] == array2[j]){
// same value
if(tmpval > array1[i]){
tmpval = array1[i];
}
}
}
}
System.out.println(tmpval);
if(min1 == min2) {
System.out.println("The Smalest match in the array is : " + min1);
} else if(min1 != min2) {
System.out.println("There is no smallest matching integer!");
}
}
}
Your code look great, its just a problem with your logic. In your question, you talked about nesting for loops, so you were on the right track.
int[] arr1 = {3,4,5,7,2};
int[] arr2 = {9,12,8,7,15};
int tmpval = Integer.MAX_VALUE;
for(int i = 0; i < arr1.length; i++){
for(int j = 0; j < arr2.length; j++){
if(arr1[i] == arr2[j]){
// same value
if(tmpval > arr1[i]){
tmpval = arr1[i];
}
}
}
}
System.out.println(tmpval);
It's not clear from your description if the matching values have to be at the same position in the two arrays. If we assume that they do then something like this would work:
int[] arr1 = {3,4,5,7,2};
int[] arr2 = {9,12,8,7,15};
int minIdx = -1;
for(int i = 0; i < arr1.length; i++)
{
if(arr1[i] == arr2[i] && (minIdx < 0 || arr1[i] < arr1[minIdx]))
{
minIdx = i;
}
}
if(minIdx < 0)
System.out.println("No match");
else
System.out.println("Min match: " + arr1[minIdx]);
Note how we use a negative index as an indicator that we haven't found a match. The standard trick of using Integer.MAX_VALUE as our starting value isn't really safe as it could be a matching value in the array.
If the matching values can appear at any position in the arrays then you'll need to compare each value in array1 with every value in array2:
for(int i = 0; i < arr1.length; i++)
{
for(int j = 0; j < arr2.length; j++)
{
if(arr1[i] == arr2[j] && (minIdx < 0 || arr1[i] < arr1[minIdx]))
{
minIdx = i;
}
}
}
Thanks for all your help guys, this is the final code:
public class SmallestArrayItem {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int array1[] = new int[5];
int array2[] = new int[5];
System.out.println("Please enter 5 values for array 1");
for(int i = 0; i < array1.length; i++) {
int userInput = keyboard.nextInt();
array1[i] = userInput;
}
System.out.println("Please enter 5 values for array 2");
for(int i = 0; i < array2.length; i++) {
int userInput = keyboard.nextInt();
array2[i] = userInput;
}
int minIdx = -1;
for(int i = 0; i < array1.length; i++)
{
for(int j = 0; j < array2.length; j++)
{
if(array1[i] == array2[j] && (minIdx < 0 || array1[i] < array1[minIdx]))
{
minIdx = i;
}
}
}
if(minIdx < 0)
System.out.println("There is no smallest matching integer!");
else
System.out.println("The Smallest match in the array is : " + array1[minIdx]);
}
}

I need to find the first maximum element in a 2D matrix using java but the code doesn't seem to work like i wanted it to. Can anyone help me?

I need the maximum elements position if there is more than one maximum element then the first one is to be printed.
My code prints the position of the maximum element but not the first one.
I don't understand why the last iteration is not working as I intend it to.
Please solve it using only Java.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
// put your code here
Scanner sc = new Scanner(System.in);
// define lengths
int n = sc.nextInt();
int m = sc.nextInt();
// add length to matrix
int[][] matrix = new int[n][m];
// insert elements
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
matrix[i][j] = sc.nextInt();
}
}
// define max
int max = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (matrix[i][j] > max) {
max = matrix[i][j];
}
}
// System.out.print(i + " " + j);
}
// System.out.print(max + " ");
// print index of highest element
// int pos1 = 0;
// int pos2 = 0;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
if (matrix[i][j] == max) {
System.out.print(i + " " + j);
break;
}
// pos2 += 1;
break;
}
// pos1 += 1;
// break;
}
}
}
There is no need to go through the matrix twice. When you are searching for the max, store also the coordinates of the matrix where that max was found. A code example:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
// put your code here
Scanner sc = new Scanner(System.in);
// define lengths
int n = sc.nextInt();
int m = sc.nextInt();
// add length to matrix
int[][] matrix = new int[n][m];
// insert elements
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
matrix[i][j] = sc.nextInt();
}
}
// define max
int max = Integer.MIN_VALUE, row=0, col=0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (matrix[i][j] > max) {
max = matrix[i][j];
row=i;
col=j;
}
}
}
System.out.print("max: "+max + " is at: ");
System.out.print(col + " " + row); //indexes starting from zero
}
}
Create a new variable to hold the position of the max value and set it in the current loop
int max = matrix[0][0];
int[] maxPos = new int[2];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (matrix[i][j] > max) {
max = matrix[i][j];
maxPos[0] = i;
maxPos[1] = j;
}
}
}
and then remove the rest of the code and print the result
System.out.printf("Max is %d and is found at [%d, %d]\n", max, maxPos[0], maxPos[1]);

How to hide characters using for loops, respectively?

I want to basically hide characters following three constant dots (...), the pattern goes like this:
Inputs a phrase from the user and outputs the phrase followed by three dots (...), then the phrase minus one character followed by three dots (...), then the phrase minus two characters followed by the dots, and so on until only one dot is left.
Note: This has to be done using nested for loops only
Sample input
1
disappear
Expected output:
disappear...
disappea...
disappe...
disapp...
disap...
disa...
dis...
di...
d...
...
..
.
This is my attempt:
Problem: I am unable to make it so the phrase decreases each time (minus 1 each time)
I tried using the charAt(); method, but it wouldn't work, I am sure that you would need a for loop separate for each of the dots or a whole set of dots, in this case.
import java.util.Scanner;
public class Dissappear{
public static void main(String[]args){
Scanner keyboard = new Scanner(System.in);
int option = keyboard.nextInt();
String phrase = keyboard.next();
if (option == 1){
for (int x = 0; x <= phrase.length(); x++){
System.out.print(phrase + "...");
for (int y = 0; y <= phrase.length(); y++){
char n = phrase.charAt(y);
System.out.print(n+"...");
}
}
}
}
}
This is how I got it to work:
public class Disappear {
public static void main(String... args) {
String word = "disappear";
int originalLength = word.length();
for(int i = 0; i < originalLength; i++) {
System.out.println(word.substring(0, originalLength - i) + "...");
}
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3 - i; j++) {
System.out.print(".");
}
System.out.println();
}
}
}
Without substring:
public class Disappear {
public static void main(String... args) {
String word = "disappear";
int originalLength = word.length();
for(int i = 0; i < originalLength; i++) {
for(int j = 0; j < originalLength - i; j++) {
System.out.print(word.charAt(j));
}
System.out.println("...");
}
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3 - i; j++) {
System.out.print(".");
}
System.out.println();
}
}
}
You can do it with StringBuilder:
StringBuilder stringBuilder = new StringBuilder(str);
System.out.println(str + "...");
for (int i = 0; i < length; i++) {
stringBuilder.deleteCharAt(stringBuilder.length() - 1);
System.out.println(stringBuilder.toString() + "...");
if (i == length - 1) {
for (int j = 0; j < 2; j++) {
for (int k = j; k < 2; k++) {
System.out.print(".");
}
System.out.println();
}
}
Ok! Nested for loops. But the outer one is only included to meet the requirement. Probably not in the spirit of the assignment though. Just keep decrementing k until it is zero and then latch it there until the StringBuilder length is 0 and the inner loop terminates.
StringBuilder sb = new StringBuilder("disappear...");
for (;;) {
for (int k = sb.length() - 4; sb.length() > 0;) {
System.out.println(sb);
sb.delete(k, k + 1);
k = k > 0 ? --k : 0;
}
break;
}

Stuck in an endless loop

I set a loop condition to be a<b. However it still continues when a>b .I get the loop in input==3
I haven't finished the code, so if you want to run it[input==3] you have to initialize the game size and after that the game .
I tried both while and for loops and im getting the same results.
import java.util.Scanner;
import java.util.Random;
public class Assignment2 {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
Random rand = new Random();
int input;
int[][] board = null;
int rows = 0;
int columns = 0;
do {
System.out.println("0. End Program" + "\n" + "1. Initialize Game Size" + "\n" + "2. Initialize Game" + "\n"
+ "3. Print 1 stage Ahead" + "\n" + "4. Print k stage ahead");
input = sc.nextInt();
if (input < 0 || input > 4) {
System.out.println("Wrong menu input");
}
if (input == 0) {
System.out.println("End Program");
break;
}
if (input == 1) { // Setting a game board size
System.out.println("Enter number of rows");
rows = sc.nextInt();
System.out.println("Enter number of columns");
columns = sc.nextInt();
if (rows < 1 || columns < 1) {
System.out.println("Wrong game size");
} else {
board = new int[rows][columns];
System.out.println("set Game size");
}
}
if (input == 2) { // initialize a random game with 1 and 0
if (columns == 0 || rows == 0) {
System.out.println("No game size stored");
} else {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
if (rand.nextBoolean())
board[i][j] = 1;
else
board[i][j] = 0;
}
}
for (int k = 0; k < board.length; k++) {
for (int j = 0; j < board[k].length; j++) { // loop to check every square in the board
System.out.print(board[k][j] + " ");
}
System.out.println();
}
}
}
if (input == 3) { // 1 movement ahead in the game
for (int k = 0; k < board.length; k++) {
for (int j = 0; j < board[k].length; j++) { // loop to check every square in the board
if (board[k][j] == 1) {
int rowMove = 0; // checks for possible movement
int columnMove = 0; // checks for possible movement
int counter = 0;
for (rowMove = 0; rowMove < rows || columnMove < columns; rowMove++) {
for (columnMove = 0; rowMove < rows || columnMove < columns; columnMove++) {
int difrow = rowMove - rows; // row distance
int difcolumn = columnMove - columns; // column distance
if (difrow < 0) { // absolute number
difrow = -difrow;
}
if (difcolumn < 0) { // absolute number
difcolumn = -difcolumn;
}
if (difcolumn + difrow == 3) {
counter++;
}
}
}
if (counter == 1 || counter == 2) {
board[k][j] = 1;
} else {
board[k][j] = 0;
}
}
}
}
for (int k = 0; k < board.length; k++) {
for (int j = 0; j < board[k].length; j++) { // loop to check every square in the board
System.out.print(board[k][j] + " ");
}
System.out.println();
}
}
} while (input != 0);
}
}
in your inner for loop
for (columnMove = 0; rowMove < rows || columnMove < columns; columnMove++)
the condition is to iterate as long as rowMove < rows || columnMove < columns but only columnMove get advanced, so rowMove < rows is always true
have you tried this :
for (rowMove = 0; rowMove < rows; rowMove++) {
for (columnMove = 0; columnMove < columns; columnMove++)

Java: Removing duplicates from a user inputted integer array

Im trying to remove duplicates from a user inputted array using java and am getting an error for a duplicate variable, here is what i have so far:
public class sortedArray {
static int alter(int array[], int n) {
if (n == 0 || n == 1)
return n;
int[] arr = new int[n];
int r = 0;
for (int i = 0; i < n - 1; i++)
if (array[i] != array[i + 1])
arr[r++] = array[i];
arr[r++] = array[n - 1];
for (int i = 0; i < r; i++)
array[i] = arr[i];
return r;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] array = new int[49];
int n = array.length;
System.out.print("enter some integers (enter -9999 to stop): ");
for (int i = 0; i < array.length; i++) {
array[i] = input.nextInt();
if (array[i] == -9999) {
break;
}
n = alter(array, n);
for (int i = 0; i < n; i++) //getting error here on the i
System.out.print(array[i] + " ");
}
}
}
Any help would be appreciated.
Your problem is that you are trying to redeclare i inside the first for loop. You need to use another counter variable in your second loop:
for (int i = 0; i < array.length; i++) {
array[i] = input.nextInt();
if (array[i] == -9999) {
break;
}
n = alter(array, n);
for (int j = 0; j < n; j++) //getting error here on the i
System.out.print(array[j] + " ");
}

Categories