Java: Printing trailing spaces - java

I'm a beginner in Java and working on a code that first requires user to enter total number of integers and next the integers themselves. Example input is:
4
1 4 3 2
The code will need to reverse the second input to the following:
2 3 4 1
My solution is as follow:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int arr[] = new int[n];
for(int arr_i=0; arr_i < n; arr_i++){
arr[arr_i] = in.nextInt();
}
for(int reverse_i=n-1; reverse_i>=0; reverse_i--){
System.out.print(arr[reverse_i]);
if(reverse_i != 0){System.out.print(" ");}
}
}
My question is related to the code to add a blank space " " in between the printed numbers. I wonder what other way I can use to get this done? Any suggestion is appreciated, thank you.

The easy way to reverse a string is using the StringBuilder class:
One option is to remove the spaces at the end of the string eg. remove last char
package stackoverflow.main;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
StringBuilder sb = new StringBuilder();
for(int arr_i = 0; arr_i < n; arr_i++){
sb.append(in.nextInt());
sb.append(" ");
}
sb.deleteCharAt(sb.length() - 1);
String normal = sb.toString();
String reversed = sb.reverse().toString();
System.out.println("normal: " + normal);
System.out.println("reversed: " + reversed);
}
}
Another option is to check whether you are at the last arr_i of your loop.
If so, then don't add a space
package stackoverflow.main;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
StringBuilder sb = new StringBuilder();
for(int arr_i = 0; arr_i < n; arr_i++){
sb.append(in.nextInt());
if (arr_i != 3
sb.append(" ");
}
String normal = sb.toString();
String reversed = sb.reverse().toString();
System.out.println("normal: " + normal);
System.out.println("reversed: " + reversed);
}
}

First reverse the array and then print it with a for loop.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int arr[] = new int[n];
for(int arr_i=0; arr_i < n; arr_i++)
{
arr[arr_i] = in.nextInt();
}
for(int i = 0; i < arr.length / 2; i++)
{
int temp = arr[i];
arr[i] = arr[arr.length - i - 1];
arr[arr.length - i - 1] = temp;
}
for(int i = 0; i < arr.length; i++)
{
System.out.print(arr[i]+" ");
}
}
}

It is all about output formatting. You may use this examples and become familiar with all possible approaches.
Your code can be improved in next two ways :
1) Use \t instead of Empty Space (\t is a tabulation)
2) Create a constant with output format like this private static final String output = "%d " and use it in output line like this : String.format(output, number) where number is your number that should be printed.

Related

Java Program to Enter a sentence and print the longest word [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 12 months ago.
Improve this question
This a program to enter a sentence and print the longest word using substring()
Here, I have used the 1st loop to extract each word from the sentence and find the length of the longest word.
In the 2nd Loop, its purpose is it to extract and print the word that matches the length which was found out in the 1st loop and stored in the "longestLength" variable.
I am getting an error when i compile the following code:
import java.util.*;
public class Program {
public static void main(String[] args) {
String s, st;
int longestLength = 0;
int i1 = 0;
int i2;
Scanner sc = new Scanner(System.in);
System.out.println("Enter Sentence");
s = sc.nextLine();
s = s.trim();
s = s+" ";
for (int i = 0; i < s.length(); i++) {
if (Character.isWhitespace(s.charAt(i))) {
i2 = i;
st = s.substring(i1, i2);
if (st.length() > longestLength)
longestLength = st.length();
i1 = i;
}
}
for (int i = 0; i < s.length(); i++) {
if (Character.isWhitespace(s.charAt(i))) {
i2 = i;
st = s.substring(i1, i2);
if (st.length() == longestLength) {
System.out.println("Longest Word : " + st);
break;
}
i1=i;
}
}
}
}
Here you don't need to use for loops for just finding the longest word.
Just remove the for loops and add the following lines below that.
Scanner sc = new Scanner(System.in);
System.out.println("Enter Sentence");
s = sc.nextLine();
s = s.trim();
s = s+" ";
String longest = Arrays.stream(s.split(" ")).max(Comparator.comparingInt(String::length)).orElse(null);
System.out.println(longest);
YOUR FINAL CODE WILL BE:
import java.util.*;
public class Program {
public static void main(String[] args) {
String s;
int longestLength = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter Sentence");
s = sc.nextLine();
s = s.trim();
String longest = Arrays.stream(s.split(" ")).max(Comparator.comparingInt(String::length)).orElse(null);
System.out.println(longest);
}
}
It will print the longest word. Hope it will be helpful to you.
There is an alternate easy method to split sentence using delimter using String.spilt(delimiter) funciton.
Below code is an working example for your task
public class Test {
public static void main(String[] args) {
String s, st;
int longestLength = 0;
int i1 = 0;
int i2;
Scanner sc = new Scanner(System.in);
System.out.println("Enter Sentence");
s = sc.nextLine();
String maxString = "";
for(String string : s.split(" ")){
maxString = maxString.length() > string.length() ? maxString : string;
}
System.out.println("The max lengthed string is : "+maxString);
}
}
Your issue is due to i1 has not be resetted to 0 hence the old loop value if i1 is there hence the issue
The solution is given below:
public static void main(String[] args) {
String s, st;
int longestLength = 0;
int i1 = 0;
int i2;
Scanner sc = new Scanner(System.in);
System.out.println("Enter Sentence");
s = sc.nextLine();
s = s.trim();
s = s+" ";
for (int i = 0; i < s.length(); i++) {
if (Character.isWhitespace(s.charAt(i))) {
i2 = i;
st = s.substring(i1, i2);
if (st.length() > longestLength)
longestLength = st.length();
i1 = i;
}
}
i1=0;
for (int i = 0; i < s.length(); i++) {
if (Character.isWhitespace(s.charAt(i))) {
i2 = i;
st = s.substring(i1, i2);
if (st.length() == longestLength) {
System.out.println("Longest Word : " + st);
break;
}
i1=i;
}
}
}

Read, store and print user input

I have to get 4 user input from the user one by one on the next line like
Sample input:
65
66
67
68
Then the output has to displayed like
You have entered:
65-A
66-B
67-C
68-D
the program i have return is this:
import java.util.Scanner;
public class ASCII {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the digits:");
int no = sc.nextInt();
char ch= (char) no;
System.out.println(no + "-" + ch);
}
}
the one thing could not get is the 4 input for the user could someone help with that
You should loop it;
int[] numbers = new int[4];
for (int i = 0; i < 4; i++) {
numbers[i] = sc.nextInt();
}
numbers[n-1] will return number in your case 0 < n < 5;
and you can create another loop to print them.
chars[] characters = {'A','B','C','D'};
for (int i = 0; i < 4; i++) {
System.out.println(Integer.toString(numbers[i]) + characters[i]);
}
for loops works like;
for (DoAtStart; Condition; DoAtEndOfARepeat) {
}
This would work for you :
public class ASCII {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the digits:");
int array[]=new int[4];
for(int i=0; i<4;i++) {
int no = sc.nextInt();
array[i]=no;
}
System.out.println("You have entered:");
for(int j=0;j<array.length;j++) {
char ch= (char) array[j];
System.out.println(ch+"-"+array[j]);
}
}
}

I am generating a series of numbers delimited with space but I want to remove the space at end

I am generating the series of numbers using for loop, delimited with space but I want to remove trailing space at last. Unable to use trim() for the output.
import java.util.*;
public class Main {
public static void main(String [] args){
Scanner s = new Scanner(System.in);
int str = s.nextInt();
for(int i=1; i<=str; i++) {
System.out.printf("%d", i);
System.out.print(" ");
}
}
}
1 2 3 4 5(space here)
but I want output without the space after 5.
int i;
for(i = 1; i < str.length(); i++) {
System.out.print(i + " ");
}
System.out.println(i);
Do an if test inside the for-loop like this
if (i == str) {
System.out.printf("%d", i);
} else {
System.out.printf("%d", i);
System.out.print(" ");
}
The logic you want is to print a space behind every number, except for the last number. You should have this conditional logic in your code somewhere. Like,
if (i < str)
System.out.print(" ");
Note: it's very confusing to call a variable str if it contains a number; everyone will assume that it's a String instead of a number. You could change code to something like this:
public static void main(String [] args){
Scanner s = new Scanner(System.in);
int n = s.nextInt();
for(int i = 1; i <= n; i++) {
System.out.print(i);
if (i < n)
System.out.print(" ");
}
}

Writing a word in a rhombus/diamond shape in Java

I have to write a program that asks a word and then prints it in a rhombus/diamond shape, like this:
Word: Hello
H
He
Hel
Hell
Hello
ello
llo
lo
o
I tried something but I really could use some help if someone could, I tried something like this:
import java.util.Scanner;
public class Rhombus {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Word: ");
String word = sc.nextLine();
int wordLength = word.length();
for (int i = 0; i < wordLength; i++) {
System.out.println(word.substring(0, i));
}
}
}
Here you are:
public static void main(String[] args) {
printRhombusText("yolobird");
}
public static void printRhombusText(String s) {
// top part
for (int i = 1; i <= s.length(); ++i) {
System.out.println(s.substring(0, i));
}
// bottom part
for (int i = 1; i <= s.length(); ++i) {
// print out the space
for (int y = i; y > 0; --y) {
System.out.print(" ");
}
System.out.println(s.substring(i));
}
}
output:
y
yo
yol
yolo
yolob
yolobi
yolobir
yolobird
olobird
lobird
obird
bird
ird
rd
d
Want to add user input? Here:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
do {
System.out.print("Input your text: ");
String input = scanner.nextLine();
printRhombusText(input);
scanner.reset();
System.out.print("You want to do one more? (y/n): ");
} while (scanner.nextLine().trim().equals("y"));
}
output:
Input your text: kiet
k
ki
kie
kiet
iet
et
t
You want to do one more? (y/n): y
Input your text: ahihi
a
ah
ahi
ahih
ahihi
hihi
ihi
hi
i
You want to do one more? (y/n): n
You can use this code to output a word in a rhombus shape.
Try it online!
public static void main(String[] args) {
String str = "RhOmBuS";
int h = str.length();
// two parts: negative and positive, i.e.
// upper increasing and lower decreasing
for (int i = 1 - h; i < h; i++) {
// white space padding for the positive part
for (int j = 0; j < i; j++) System.out.print(" ");
// negative part: str.substring(0, h + i);
// positive part: str.substring(i, h);
String sub = str.substring(Math.max(0, i), Math.min(h, h + i));
// output the line
System.out.println(sub);
}
}
Output:
R
Rh
RhO
RhOm
RhOmB
RhOmBu
RhOmBuS
hOmBuS
OmBuS
mBuS
BuS
uS
S
See also: Print a rhombus pattern from user input

java regex loop are not running properly

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StringInteger {
public static void main(String[] args) {
System.out.println("Enter no. of times input numbers will be given : ");
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int index = 0, index1 = 0;
int girl[] = new int[1000];
int boy[] = new int[1000];
for (int i = 1; i <= n; i++) {
String s = sc.next();
Pattern mypattern = Pattern.compile("[0-9]+");
Matcher mymatcher = mypattern.matcher(s);
while (mymatcher.find()) {
if (i % 2 != 0) {
girl[index] = Integer.valueOf(mymatcher.group());
index++;
} else {
boy[index1] = Integer.valueOf(mymatcher.group());
index1++;
}
}
}
for (int j = 0; j < index; j++) {
System.out.print(girl[j] + " ");
}
}
}
Why loop are not running upto its limit?
For loop runs correctly for the no. of times i.e. n.
You should format your code, Java class name should be CamelCase and without underscore and do add System.out.println to help you understand debugging and program makes more logical sense.
It seems like your program is expecting a number for which user can enter numbers.
There are 2 arrays i.e. girl and boy. If the number is odd then then it is added to girl array and if the number is even then it is added to boy array.
Finally girl array is printed.
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StringInteger {
public static void main(String[] args) {
System.out.println("Enter no. of times input numbers will be given : ");
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int index = 0, index1 = 0;
int girl[] = new int[1000];
int boy[] = new int[1000];
for (int i = 1; i <= n; i++) {
String s = sc.next();
Pattern mypattern = Pattern.compile("[0-9]+");
Matcher mymatcher = mypattern.matcher(s);
while (mymatcher.find()) {
if (i % 2 != 0) {
girl[index] = Integer.valueOf(mymatcher.group());
index++;
} else {
boy[index1] = Integer.valueOf(mymatcher.group());
index1++;
}
}
}
for (int j = 0; j < index; j++) {
System.out.print(girl[j] + " ");
}
}
}
Sample Run:
Enter no. of times input numbers will be given :
4
10
11
12
13
10 12

Categories

Resources