I have a task to ask user for input (user's name) and then to print a rhombus pattern out of it.
For example:
If user's name is Thomas, then the output should be like this:
T
Th
Tho
Thom
Thoma
Thomas
homas
omas
mas
as
s
This is my code so far. I am having trouble with second for loop. I can easily print out lines until "Thomas", but I don't know, how to print whitespace infront so that the end of the word will be on the same place.
import java.util.Scanner;
public class wordRhombus {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = sc.nextLine();
int enteredNamesLength = name.length();
for (int i = 0; i <= enteredNamesLength; i++) {
System.out.println(name.substring(0, (int) i));
for (int j = 1, k = 1; j <= enteredNamesLength; i++, k++) {
System.out.println(k * " " + name.substring(j, enteredNamesLength));
}
}
}
}
I think there must be one for loop to print the name like what you did, then another for space and inside the same print the substring.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = sc.nextLine();
int enteredNamesLength = name.length();
for (int i = 0; i <= enteredNamesLength; i++) {
System.out.println(name.substring(0, (int) i));
}
for(int i = 1;i <= enteredNamesLength; i++ ) {
for(int j = 0;j < i; j++) {
System.out.print(" ");
}
System.out.println(name.substring(i, enteredNamesLength));
}
}
It would be easier to do it in 2 times : substring from start to an index, and then print the spaces followed by the end of the world, ans some changes to do :
no need to cast i as int, it's already an int
first loop : start index i at 1 and not 0, no avoid empty line
second loop : end index for i at enteredNamesLength-1 and not enteredNamesLength to avoid also an empty line
for (int i = 1; i <= enteredNamesLength; i++) { // start at 1
System.out.println(name.substring(0, i)); // don't cast
}
for (int i = 1; i < enteredNamesLength; i++) { // stop at enteredNamesLength-1
for (int space = 0; space <= i; space++) {
System.out.print(" ");
}
System.out.println(name.substring(i, enteredNamesLength));
}
Here is another solution, you can extract a print method which accepts a start and stop. If the index between them, then print character at index, otherwise print whitespace.
import java.util.Scanner;
public class wordRhombus {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = sc.nextLine();
int enteredNamesLength = name.length();
for (int start = 0, stop = 0; start < enteredNamesLength && stop < enteredNamesLength; ) {
print(start, stop, name);
if (stop < enteredNamesLength - 1) {
stop++;
} else {
start++;
}
}
}
private static void print(int start, int stop, String name) {
for (int index = 0; index < name.length(); index++) {
if (index >= start && index <= stop) {
System.out.print(name.charAt(index));
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
You can combine the upper increasing part and the lower decreasing part in one loop.
Try it online!
public static void main(String[] args) {
String str = "RHOMBUS";
int n = str.length();
// two parts: negative and positive
for (int i = 1 - n; i < n; i++) {
// leading whitespaces for the positive part
for (int j = 0; j < i; j++) System.out.print(" ");
// negative part: str.substring(0, n + i);
// positive part: str.substring(i, n);
String sub = str.substring(Math.max(0, i), Math.min(n + i, n));
// output the line
System.out.println(sub);
}
}
Output:
R
RH
RHO
RHOM
RHOMB
RHOMBU
RHOMBUS
HOMBUS
OMBUS
MBUS
BUS
US
S
See also: Writing a word in a rhombus / diamond shape
This code works with both regular UTF8 characters and surrogate pairs.
Try it online!
public static void main(String[] args) {
String str = "π₯π·πΎπΌπ±ππ¦";//"RHOMBUS";
int n = (int) str.codePoints().count();
// two parts: negative and positive, i.e.
// upper increasing and lower decreasing
IntStream.range(1 - n, n)
// leading whitespaces for the positive part
.peek(i -> IntStream.range(0, i)
.forEach(j -> System.out.print(" ")))
// negative part: range(0, n + i);
// positive part: range(i, n);
.mapToObj(i -> str.codePoints()
.skip(Math.max(0, i))
.limit(Math.min(n + i, n))
.mapToObj(Character::toString)
.collect(Collectors.joining()))
// output the line
.forEach(System.out::println);
}
Output:
π₯
π₯π·
π₯π·πΎ
π₯π·πΎπΌ
π₯π·πΎπΌπ±
π₯π·πΎπΌπ±π
π₯π·πΎπΌπ±ππ¦
π·πΎπΌπ±ππ¦
πΎπΌπ±ππ¦
πΌπ±ππ¦
π±ππ¦
ππ¦
π¦
Related
What is the mistake in my code?
Given a string consisting of lowercase letters, arrange all its letters in ascending order.
Input: The first line of the input contains T, denoting number of testcases. Then follows description of each testcase. The first line of the testcase contains positive integer N denoting the length of string. The second line contains the string.
Output: For each testcase, output the sorted string.
Constraints:
1 <= T <= 100
1 <= N <= 100
import java.util.*;
class GFG {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for (int i = 1; i <= t; i++) {
int n = sc.nextInt();
sc.nextLine();
String S = sc.nextLine();
String sor = "";
for (int j = 0; j < n; j++) {
int min = j;
for (int k = j + 1; k < n; k++) {
if (S.charAt(k) > S.charAt(min)) {
min = k;
}
}
sor += S.substring(min, min + 1);
}
System.out.println(sor);
}
}
}
For Input:
1
5
edcab
Output:
edcbb
Expected Output:
abcde
import java.util.*;
class GFG {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for (int i = 1; i <= t; i++) {
int n = sc.nextInt();
sc.nextLine();
String S = sc.nextLine();
System.out.println("S: "+S);
String sor = "";
for (int j = 0; n > 0; j++) {
int min = 0;
for (int k = 0; k < n; k++) {
if (S.charAt(k) < S.charAt(min)) {
min = k;
}
}
sor += S.substring(min, min + 1);
S = S.substring(0, min) + S.substring(min + 1);
n--;
}
System.out.println(sor);
}
}
}
This code does what you want. I changed > to < and I removed every char that added to sorted String from unsorted String. This way we don't need to deal with the same char again and again.
You are not exchanging the place of the min character after finding it. But Strings in java are immutable so you can't swap the places of characters in it. I suggest you convert your String to a char[] so that you can swap the characters:
public static void main (String[] args){
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for(int i=1; i<=t; i++){
int n = sc.nextInt();
sc.nextLine();
String S = sc.nextLine().toCharArray(); // convert it to char array
char[] sor = new char[S.length];
for(int j=0; j<n; j++){
int min = j;
for(int k =j+1; k<n; k++){
if(S[k]<S[min]){
min = k;
}
}
swap(S, min, j);
sor[j] = S[min]
}
System.out.println(new String(sor));// reconvert to string
}
}
public static void swap(char[] c,int x,int y){
char temp= c[x];
c[x] = c[y];
c[y] = temp;
}
You can use String.toCharArray method to iterate over the array of characters char[] of this string, sort their decimal values and return back the string that contains the characters of the sorted array:
public static void main(String[] args) {
String str = "edcab";
String sorted = selectionSort(str.toCharArray());
System.out.println(sorted); // abcde
}
public static String selectionSort(char[] arr) {
// iterate over all subsets of the array
// (0-last, 1-last, 2-last, 3-last, ...)
for (int i = 0; i < arr.length; i++) {
// assume the min is
// the first element
char min = arr[i];
// index of the
// min element
int min_i = i;
// check the elements
// after i to find
// the smallest
for (int j = i + 1; j < arr.length; j++) {
// if this element
// is less, then it
// is the new min
if (arr[j] < min) {
min = arr[j];
min_i = j;
}
}
// if min element is not
// equal to the current
// one, then swap them
if (i != min_i) {
char temp = arr[i];
arr[i] = arr[min_i];
arr[min_i] = temp;
}
}
return String.valueOf(arr);
}
You can use String.codePoints method to iterate over int values of the characters of this string, sort them and collect another sorted string:
String str = "edcab";
String sorted = str.codePoints()
.sorted()
.mapToObj(Character::toString)
.collect(Collectors.joining());
System.out.println(sorted); // abcde
See also:
β’ How do I not take Special Characters in my Password Validation (without Regex)?
β’ Java Selection Sort
I have just started my java course so still cannot understand a lot of things, help me out please.
So here is the base code
import java.util.Arrays;
import java.util.Scanner;
public class Main<i> {
public static void main(String[] args ) {
System.out.println (" Enter count of digits: ");
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int [] sourceNumber = new int [size];
System.out.println("Enter your digits with space");
for (int i = 0; i < size; i++) {
sourceNumber[i] = scanner.nextInt();
[...]
So I have no single idea how to make method to find any count with stepful numbers. Example:
I have counts like: 12405346 534952359 6456934 1234567
so I need system to find 1234567 and print it out
For example I made method to find a count with munimum same numbers like this:
[...]
for (int j = 0; j < 10; j++) {
if (digitsCount[j] > 0)
differentDigitsCount++;
}
mindifferent = differentDigitsCount;
for (int k = 1; k < size; k++) {
int differentDigitsCount1 = 0;
int[] digitsCount1 = new int[10];
while (sourceNumber[k] != 0) {
digitsCount1[(int) (sourceNumber[k] % 10)]++;
sourceNumber[k] /= 10;
}
for (int j = 0; j < 10; j++) {
if (digitsCount1[j] > 0)
differentDigitsCount1++;
}
if (mindifferent <= differentDigitsCount1) {
} else {
mindifferent = differentDigitsCount1;
l = k;
}
}
System.out.println("Digit with minimum same numbers: " + moimassiv[l]);
[...]
This code is huge, but its fine for me now. I just need to make method to find stepful counts
I'm assuming that you want to print those numbers whose digits are sorted from smallest to largest. Is that right?
You can convert the number to String, then you can get each digit by using charAt(int index) method
You can iterate over sourceNumber and call hasSortedNumbers() for each one to know if its digits are sorted.
for (int number : sourceNumber) {
String valueOfNumber = String.valueOf(number);
if (hasSortedNumbers(valueOfNumber)) {
System.out.println(number);
}
}
This is the code for hasSortedNumbers()
public static boolean hasSortedNumbers(String valueOfNumber) {
for (int i = 0; i < valueOfNumber.length() - 1; i++) {
if (valueOfNumber.charAt(i) >= valueOfNumber.charAt(i + 1)) {
return false;
}
}
return true;
}
I'm assuming you're going to use this method from main, so it needs to be static, since main is static.
Basically I'm comparing each digit with the next one, if it turns out that the next one is smaller, it returns false. If not, when it exits the for loop, it returns true.
I am new to Java Programming (or programming infact).
I have an array which contains either 4 or 6 only. Given a number, either 4 or 6, find the highest sequential occurrence of the given number.
I need highest sequential occurrence count
Example: arr[{4,4,6,6,4,4,4,4,4,6}]
If the above array is given, and next input number is 4, the output should be 5. Because the number 4 has occurred sequentially 5 times.
public static void main(String[] args) throws IOException {
String arrayTK = br.readLine(); // Input is 4466444446
int[] inpArray = new int[10];
for (int i = 0; i < 10; i++) {
inpArray[i] = arrayTK.charAt(i) - '0';
}
int maxSequenceTimes = 0;
for (int j = 0; j < 10; j++) {
// Logic
}}
Any help would be greatly appreciated.
Edit
We will separate and count all sequences and then search in each sequence to know which sequence contain the biggest length.
int[] arr = {4,4,6,6,4,4,4,4,4,6};
boolean newSeq = false;
int diffrentSeq = 0;
int currentNumber;
//Get sequence numbers
for (int i = 0; i < arr.length; i++) {
currentNumber = arr[i];
if (i >= 1 && currentNumber != arr[i - 1])
newSeq = true;
else if (i == 0)
newSeq = true;
//It's new sequence!!
if (newSeq) {
diffrentSeq++;
newSeq = false;
}
}
System.out.println(diffrentSeq);
int[] maxSequencSize = new int[diffrentSeq];
int lastIndex = 0;
for (int i = 0; i < maxSequencSize.length; i++) {
int currentNum = arr[lastIndex];
for (int j = lastIndex; j < arr.length; j++) {
if (arr[j] == currentNum) {
maxSequencSize[i]++;
lastIndex = j + 1;
} else break;
}
}
System.out.println(max(maxSequencSize));
You need to get max value which act the max sequence length:
private static int max(int[] array){
int maxVal = 0;
for (int anArray : array) {
if (anArray > maxVal)
maxVal = anArray;
}
return maxVal;
}
String arrayTK = br.readLine(); // Input is 4466444446
Because your first input is a string, you don't need to convert it to an int array and if you are using you can use:
String arrayTK = "4466444446";
int result = Arrays.asList(arrayTK.replaceAll("(\\d)((?!\\1|$))", "$1;$2").split(";"))
.stream().max(Comparator.comparingInt(String::length)).get().length();
System.out.println(result);
Explanation :
arrayTK.replaceAll("(\\d)((?!\\1|$))", "$1;$2") put a separator between each two different numbers the result should be 44;66;44444;6
.split(";") split with this separator (i used ; in this case) the result is ["44", "66", "44444", "6"]
stream().max(Comparator.comparingInt(String::length)).get() get the max input
.length() to return the length of the result
Ideone demo
Edit
How I modify the same, to get count to any specific number. I mean, max sequential occurrence of number 4
In this case you can just add a filter .filter(t -> t.matches(number + "+")) which mean get only the numbers which match 4+ where 4 can be any number :
...
int number = 6;
int result = Arrays.asList(arrayTK.replaceAll("(\\d)((?!\\1|$))", "$1;$2").split(";"))
.stream()
.filter(t -> t.matches(number + "+"))
.max(Comparator.comparingInt(String::length)).get().length();
You need something like this:
import java.util.Scanner;
public class A {
public static void main(String[] args) {
Scanner br =new Scanner(System.in);
String str = br.next();
int arr[]=new int[str.length()];
for(int i=0;i<str.length();i++)
{
arr[i]=str.charAt(i)-'0';
//System.out.println(arr[i]);
}
int j=0;
int count=1,max=0;
for(int i=0;i<str.length();i++)
{
if(i==0){
j=arr[i];
}
else
{
if(arr[i]==j)
{
count++;
//System.out.println(" "+count);
}
else
{
if(max<count){
max=count;
}
count=1;
j=arr[i];
}
}
}
if(max<count){
max=count;
}
System.out.println(max);
}
}
That should do the work. Every time you find the matching value you start counting and when the streak is over you compare the length with the maximum length you have found so far.
public int logic(int[] inpArray, int num) {
int count = 0, max = 0
for(int i = 0; i < 10; ++i){
if(inpArray[i] == num) {
count++
else{
if(count > max)
max = count;
count = 0;
}
}
if (count > max)
max = count;
return max;
}
So, I'm creating this minesweeper game and I am confused with 2 of my methods which one, will initialize the array with a certain character and one method will actually print the game. Here is my code:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int a = 0;
int b = 0;
System.out.println("Welcome to Mine Sweeper!");
a = promptUser(in, "What width of map would you like (3 - 20):", 3, 20);
b = promptUser(in, "What height of map would you like (3 - 20):", 3, 20);
eraseMap(new char[b][a]);
simplePrintMap(new char[b][a]);
}
public static int promptUser(Scanner in, String prompt, int min, int max) {
int userInput;
System.out.println(prompt);
userInput = in.nextInt();
while (userInput < min || userInput > max) {
System.out.println("Expected a number from 3 to 20.");
userInput = in.nextInt();
}
return userInput;
}
public static void eraseMap(char[][] map) {
for (int i = 0; i < map.length; ++i) {
for (int j = 0; j < map[i].length; ++j) {
map[i][j] = (Config.UNSWEPT);
}
}
return;
}
public static void simplePrintMap(char[][] map) {
for (int i = 0; i < map.length; ++i) {
for (int j = 0; j < map[i].length; ++j) {
System.out.print(map[b][a] + " ");
}
System.out.println();
}
return;
}
The methods that are in question is eraseMap and simplePrintMap. eraseMap is supposed to initialize the array with "." and simplePrintMap is supposed to actually print the array. So if i input 3 and 4, it will print periods will a width of 3 and height of 4.
(each period separated by space).
A) You create 2 seperate maps. You perform the erase on the first, then throw it all away, create a new map and print that. Which, of course, is empty.
Try creating one map and work on it:
char[][] map = new char[b][a]
eraseMap(map);
simplePrintMap(map);
B) in the print method, you use the wrong indices:
System.out.print(map[b][a] + " ");
change these to
System.out.print(map[i][j] + " ");
C) not an error, just a hint: you don't need return; at the end of void methods.
Here am finding the middle letter of each element of the array and making it upper case and merge it so that it'll give me a result like e:g- {bOy, inDia, apPle}
Following is the code am trying till now.
public class FindMiddle {
public static void main(String[] args) {
ArrayList<String> al = new ArrayList<String>();
al.add("boy india apple");
String str[] = al.toArray(new String[al.size()]);
String newar[];
String delimiter = " ";
newar = str[0].split(delimiter);
for (int i = 0; i < newar.length; i++) {
char[] c = newar[i].toCharArray();
for (int j = 0; j < c.length; j++) {
if (j == c.length / 2) {
c[j] = Character.toUpperCase(c[c.length / 2]);
System.out.println(c[j]);
}
newar[i] += c[j];
}
}
}
}
It's only giving me O D P.
I want them merged with the original elements like bOy inDia apPle.
that's because you print only the middle char (the println is inside the if statement)
if (j == c.length / 2) {
c[j] = Character.toUpperCase(c[c.length / 2]);
System.out.println(c[j]);
}
I would suggest using StringBuilder.setCharAt
for (int i = 0; i < newar.length; i++) {
StringBuilder updateString = new StringBuilder(newar[i]);
int middleIndex = newar[i].length /2;
updateString.setCharAt(middleIndex, Character.toUpperCase(newar[i].charAt(middleIndex));
System.out.println(updateString);
}
you could use the charAt function of the String object and replace function
using the full String.length is not accurate when you will be accessing the middle index of the String since index are length - 1 (because it starts with 0) so you need to deduct 1 from the length and then divide it by half.
for(int i=0;i<newar.length;i++){
int index = (newar[i].length()-1)/2;
newar[i] = newar[i].replace(newar[i].charAt(index), Character.toUpperCase(newar[i].charAt(index)));
System.out.println(newar[i]);
}
output:
bOy
inDia
aPPle
Try this :
for (int i = 0; i < newar.length; i++) {
char[] c = newar[i].toCharArray();
for (int j = 0; j < c.length; j++) {
if (j == c.length / 2) {
c[j] = Character.toUpperCase(c[c.length / 2]);
//System.out.print(c[j]); <--- you keep getting O D P because you
print them here
}
// newar[i] += c[j]; <-- here you just concat changed elements to newar
System.out.print(c[j]); <--- print the value of array none middle and middle one
}
if (i != newar.length-1) { <-- avoid printing , for last item
System.out.print(",");
}
}
output:
bOy,inDia,apPle
My explanations are as comment inside the code.
Note: when you are in a for loop, you are checking whether you ecnounter the middle character. if you encountered, you will make it uppercase other wise nothing is changed, and each character is printed out on the console.
import java.util.ArrayList;
public class Test
{
public static void main(String[] args) {
ArrayList<String> al = new ArrayList<String>();
al.add("boy india apple");
String str[] = al.toArray(new String[al.size()]);
String newar[];
String delimiter = " ";
newar = str[0].split(delimiter);
for (int i = 0; i < newar.length; i++) {
char[] c = newar[i].toCharArray();
for (int j = 0; j < c.length; j++) {
if (j == c.length / 2) {
c[j] = Character.toUpperCase(c[c.length / 2]);
// System.out.println(c[j]);
// (1)
}
System.out.print(c[j]);
// (2)
newar[i] += c[j];
}
System.out.println();
// (3)
}
}
}
(1) - I got rid of this because it would only print out the uppercase letter. You had set the middle characters in all 3 words to uppercase, but, you need to print out the whole word, not just one letter.
(2) - You do, however, want to print out the whole word, which is what this line is doing. Instead of doing println, it only does print. Reason is because we are taking advantage of that for loop that is going through each character in the specific word to be able to print out each letter after we are done checking if it's the middle letter.
(3) - We have this line here because we want to be able to separate between words. I am not sure how you want these words separated so change this as you feel it's necessary, I just separated them so you could see.
There are a lot of things wrong with your code, so here is a simplified rewrite:
public static void main(String[] args) {
String s = "boy india apple";
String[] split = s.split( " " );
String[] toReturn = new String[split.length];
for (int i = 0; i < split.length;i++)
{
String word = split[i];
char[] chars = word.toCharArray();
chars[chars.length/2] = Character.toUpperCase( chars[chars.length/2] );
toReturn[i] = String.valueOf( chars );
}
System.out.println(Arrays.toString( toReturn ));
}
In order to correct your code you can start by removing the useless ArrayList and moving the System.out outside of the for loop. There are some other issues like you are appending the new result to the original so newar after this runs will look like {boybOy, indiainDia, appleapPle}.
EDIT:
For teaching purposes, here is your code modified so that it will work; however inefficient.
public static void main(String[] args) {
ArrayList<String> al = new ArrayList<String>();
al.add("boy india apple");
String str[] = al.toArray(new String[al.size()]);
String newar[];
String delimiter = " ";
newar = str[0].split(delimiter);
System.out.print("{");
for (int i = 0; i < newar.length; i++) {
char[] c = newar[i].toCharArray();
for (int j = 0; j < c.length; j++) {
if (j == c.length / 2) {
c[j] = Character.toUpperCase(c[c.length / 2]);
}
System.out.print(c[j]);
}
newar[i] = String.valueOf(c);
if (i < newar.length - 1)
System.out.print(",");
}
System.out.println("}");
}
String temp = ""; //define temp string as "" (don't assign null)
for (int j = 0; j < c.length; j++) {
...
//newar[i] += c[j]; //don't append to existing String in array
temp += c[j];
newar[i] = temp;
}
//after replacement is done
//now can print replaced string in array by looping
for (String string : newar) {
System.out.println(string);
}