Convert single integer into string of that length in Java - java

Are there any resources available in the java documentation, or elsewhere that can lead me in the right direction on this? Even just giving the method(s) would help greatly.
Let's say I prompt a user to enter an integer i greater than 0. Then, in the output, they get a string that is the length of the integer. The characters can range from "!" to "~" on the ASCII table (33-126).
For example:
"Enter an integer greater than 0: "
Input: 8
Output: &3lR(c$2
"Enter an integer greater than 0: "
Input: 4
Output: I*#f
Etc, etc...
I think I can figure out the rest myself, such as generating a random (a real random, not a pseudo-random), doing the necessary loop to print an error message if the input is less than or equal to 0. I would prefer method hints over code anyway.
Thank you.

Use a loop with StringBuilder:
String randomString(int lengthOfString){
int minChar = 33;
int maxChar = 126;
StringBuilder result = new StringBuilder();
for (int i = 0; i < lengthOfString; i++){
result.append((char) generateRandomBetweenTwoNumbers(minChar, maxChar));
}
return result.toString();
}

Once you use your random number generator you can just construct the String by converting the int's to char's:
String output = (char)40 + "" + (char)60....

Here's a way to do it using code a beginner would have seen; I don't recommend this.
import java.util.Random;
public class stack {
public static void main(String[] args) {
int length = 8;
char character = 0;
String output = "" + character;
Random random = new Random();
for (int i = 0; i < length; i++) {
character = (char) (random.nextInt(126 - 33 + 1) + 33);
output += character;
}
System.out.println(output);
}
}

Related

how to print count of each character in a string using java

Hey I am trying to figure out the logic in counting the each character in a string by comparing it to the first character in the string but I cannot seem to figure out the rest. If anyone can help complete this.
public class Main {
public static void main(String[] args) {
String word = "AaaaABBbccKLk";
countLetter(word);
}
public static void countLetter(String word){
int count = 0;
char firstChar = word.toLowerCase().charAt(0);
char ch;
for(int i = 0 ; i<word.length(); i++){
ch = word.toLowerCase().charAt(i);
if(ch == firstChar){
System.out.println(ch + "=" + count);
count++;
}
if(ch != firstChar && count > 0){
count=0;
System.out.println(ch + "=" + count);
count= count + 1;
}
}
}
}
I assume you may want something like this:
class Main {
public static void main(String[] args) {
String word = "AaaaABBbccKLk";
countLetter(word);
}
public static void countLetter(String word){
int[] charCount = new int[26];
word = word.toLowerCase();
for(int i = 0; i < word.length(); i++){
char letter = word.charAt(i);
int index = (int)letter - 97;
charCount[index]++;
}
for(int i = 0; i < charCount.length; i++){
System.out.println("Occurrences of " + (char)(i + 97) + " :" + charCount[i]);
}
}
}
Though this code only works for Strings with characters A-Z, you can easily make this work for a larger range of characters by expanding the size of charCount and using an ASCII table.
The way this code works is that it creates an integer array of size 26 (the number of English letters) and then lowercases the String because in programming, lowercase and uppercase letters are actually different.
Next, we iterate through the word and convert every letter into an index by converting it to its ASCII value and subtracting 97 so that we get characters in the range 0 to 25. This means that we can assign each letter to an index in our array, charCount.
From here, we just increment the element of our array that corresponds to the index of each letter.
Finally, we just print out every letter and its frequency.
Let me know if you have any questions! (Also in the future, try to give a bit more insight into your process so it is easier to guide you instead of just giving the answer).

StringBuilder.insert() not changing output

I'm trying to make a short program that converts any string into T H I S F O N T.
For example: "This is a test sentence" turns into "T H I S I S A T E S T S E N T N C E"
I have a StringBuilder inside a while loop, but using finale.insert(i, '\t'); doesn't work.
import java.util.Scanner;
public class Executable {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String x;
int i = 0;
System.out.print("Input text here: ");
x = input.nextLine();
StringBuilder finale = new StringBuilder(x.toUpperCase());
while(i > finale.length()) {
if(finale.substring(i, i) == " ") {
i += 2;
finale.insert(i, '\t');
}
}
System.out.println(finale);
}
}
Any help?
You have a few issues with your code. Before I present an implementation that works, let's look at those other issues.
Your while loop checks if i > finale.length(). Since i = 0 the while loop never has a chance to begin.
You are comparing strings using == and this is not correct. == is used to confirm two objects are equal, not the value of two strings. You would need to use string.equals() instead.
You're doing too much in your loop anyway. Using a simple for loop can accomplish the goal quite simply.
Here is a new loop you can use instead of what you have:
for (int i = 1; i < finale.length(); i++) {
finale.insert(i++, " ");
}
The output: T H I S F O N T
For those unfamiliar with for loops, here's a very simple breakdown of how the above is structured.
The for loop is defined in three parts:
for (variable_to_increment; repeat_until_this_condition_is_met; modify_variable_on_each_iteration) {
// Code to be executed during each pass of the loop
}
First, we define a variable that we can track on each loop: int i = 1. By setting i = 1, we are going to skip the first character in the string.
The next statement, i < finale.length() means that we want to keep repeating this loop until we reach the length of our string. For example, if the string is 5 characters long and we've run the loop 4 times, i now equals 5 and is no longer less than the string's length, so the loop ends.
The last part is i++. This tells Java what we want to do with i after each loop. In this case, we want to increment the value by 1 each time the loop repeats.
Everything inside the brackets is, obviously, the code we want to execute on each loop.
You're saying while i>finale.length() but i is initialized as 0. You never enter the while loop.
Some issues with your code (see inline comments):
import java.util.Scanner;
public class Executable {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String x;
int i = 0;
System.out.print("Input text here: ");
x = input.nextLine();
StringBuilder finale = new StringBuilder(x.toUpperCase());
while(i > finale.length()) { // this condition is incorrect. Initially
// this condition will always be false
// if you input some sentence. It should be
// i < finale.length()
if(finale.substring(i, i) == " ") { // here preferably you should use
// equals method to compare strings
i += 2;
// you are only incrementing the i if the ith
// substring equals " ". Firstly, substring(i,i)
// will return empty string because the second argument
// is exclusive
finale.insert(i, '\t');
}
}
System.out.println(finale);
}
}
If you want to have an alternate method (not very optimal) for doing what you want to do, you can try the following approach:
import java.util.Scanner;
public class Executable {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String x;
int i = 0;
System.out.print("Input text here: ");
x = input.nextLine();
String finale = x.toUpperCase().replaceAll(" ","").replaceAll("", " ");
System.out.println(finale);
}
}
First, convert the string to uppercase --> then remove all spaces between the words --> then insert spaces between all letters. The code line which does this is,
String finale = x.toUpperCase().replaceAll(" ","").replaceAll("", " ");
Here is a sample run:
Input text here: This is a sentence
T H I S I S A S E N T E N C E
The correct way with your method would be, just increment until you have twice the size of the initial String
while (i < x.length() * 2) {
finale.insert(i, '\t');
i += 2;
}
An easier way would be with a classic for-loop:
StringBuilder finale = new StringBuilder();
for (char c : x.toUpperCase().toCharArray()) {
finale.append(c).append('\t');
}
Use a for loop since you know the number of iterations:
Scanner input = new Scanner(System.in);
String x;
System.out.print("Input text here: ");
x = input.nextLine();
StringBuilder finale = new StringBuilder(x.toUpperCase());
int len = finale.length();
for (int i = 1; i < 2 * len; i+=2 ) {
finale.insert(i, '\t');
}
System.out.println(finale);
You are comparing strings with ==. Never do that; use equals instead.
For future readers: this job can be done elegantly using Java 8 Streams:
String result = str.chars()
.filter(i -> i != ' ')
.mapToObj(t -> (char) t)
.map(Character::toUpperCase)
.map(Character::valueOf)
.collect(Collectors.joining(" ");

whats the simplest way to write a palindrome string using a while loop in java

I've searched about everywhere but I just can't find anything very concrete. I've been working on this code for awhile now but it keeps stumping me.
public static void main(String[] args) {
System.out.println(palindrome("word"));
}
public static boolean palindrome(String myPString) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a word:");
String word = in.nextLine();
String reverse = "";
int startIndex = 0;
int str = word.length() -1;
while(str >= 0) {
reverse = reverse + word.charAt(i);
}
}
There's a lot of ways to accomplish this using a while loop.
Thinking about simplicity, you can imagine how could you do this if you had a set of plastic separated character in a table in front of you.
Probably you'll think about get the second character and move it to the begin, then get the third and move to begin, and so on until reach the last one, right?
0123 1023 2103 3210
WORD -> OWRD -> ROWD -> DROW
So, you'll just need two code:
init a variable i with 1 (the first moved character)
while the value of i is smaller than total string size do
replace the string with
char at i plus
substring from 0 to i plus
substring from i+1 to end
increment i
print the string
The process should be:
o + w + rd
r + ow + d
d + row +
drow
Hope it helps
Here is an piece of code I write a while back that uses almost the same process. Hope it helps!
String original;
String reverse = "";
System.out.print("Enter a string: ");
original = input.nextLine();
for(int x = original.length(); x > 0; x--)
{
reverse += original.charAt(x - 1);
}
System.out.println("The reversed string is " +reverse);

binary to decimal program isn't giving correct answer java

So i have to write a program for homework where it takes a binary number and prints out its the decimal form. I've tried and and i just can't really get it. Like im printing out what it's doing every time in the loop and it looks like im getting the wrong value when i multiply the inputed data by the 2^i. If someone could help, that would be amazing
import java.util.Scanner;
public class Homework {
public static void main(String[] args) {
#SuppressWarnings("resource")
Scanner userinput = new Scanner(System.in);
System.out.println("Enter a binary number (only 1's or 0's): ");
String binary_number = userinput.next();
int value = 0;
int square_value = 0;
for (int i = 0; i < binary_number.length(); i++) {
char binary_place_holder = binary_number.charAt(i);
square_value = (int) Math.pow(2, i);
if (binary_place_holder == '1') {
value = (square_value*binary_place_holder+value);
}
System.out.println(binary_place_holder+ " " + square_value + " " + value);
}
System.out.print(binary_number + " == " + value);
}
}
The way you determine the exponent is wrong: The exponent is not i.
You need to realize that you are looking at the string from left to right side so from the highest bit.
This means the first character's exponent is 2^string_length-1.
Second character's exponent is 2^string_length-2 and so on.
Therefore as the index i becomes larger, i.e. as we are scanning the input left to right, the exponent value becomes smaller.
So the exponent is:
int exponent = binary_number.length() - 1 - i;
Note: You can of course do things in reverse and start from the end of the input string and determine the exponent that way, I just wanted to do less changes to your code.
Also, you should add a check to make sure the input is a valid binary number. You can write your own function to do it but a simpler solution is to use regex matching:
binary_number.matches("[01]+")
This will return true if the string binary_number contains only '0' and '1' characters, and false otherwise.
Applying all these changes to your code:
public static void main(String[] args) {
#SuppressWarnings("resource")
Scanner userinput = new Scanner(System.in);
System.out.println("Enter a binary number (only 1's or 0's): ");
String binary_number = userinput.next();
if(!binary_number.matches("[01]+")) {
System.err.println("\nPlease enter a valid binary number");
} else {
int value = 0;
for (int i = 0; i < binary_number.length(); i++) {
if (binary_number.charAt(i) == '1') {
int exponent = binary_number.length() - 1 - i;
value += (int) Math.pow(2, exponent);
}
}
System.out.print(binary_number + " == " + value);
}
}
This might be considered cheating but you could go all like
System.out.println(Integer.parseInt(binary_number, 2));

recognized a numbers and letters in a inputted string

so far i have no problem in getting the length but the recognizing the numbers from letters is hard can any one help me here Thanks for the helps heres the new code my new problem is in counting the elements in the string in will not count the numbers inputted like a Address Example 99 San pedro st philippines ..... it will only count San pedro st philippines .........
import java.util.Scanner;
public class Exercise3
{
public static void main(String [] args)
{
Scanner scan= new Scanner(System.in);
System.out.println("Enter String:");
String s=scan.nextLine();
s = s.replace(" ","");
System.out.println("Total of Elements is: " + s.length());
int nDigits =0,nLetters =0,sum =0;
for(int i =0;i<s.length();i++)
{
Character ch = s.charAt(i);
if(Character.isDigit(ch)){
nDigits++;
sum += Integer.parseInt(ch.toString());
}
else if (Character.isLetter(ch)){
nLetters++;
}
}
System.out.println("The sum of numbers in the string: " + sum);
}
}
}
It looks like your problem is with the line sum += Integer.parseInt(s.toString());. You're taking the string value of the entire InputStream, which is almost certainly what you don't want. I assume you intended to do sum += Integer.parseInt(s.charAt(i).toString());, which will give you just the value of each individual digit. Take in mind in the string hello43world, it would return 7 (4+3), not 43.
EDIT: To do what you actually want - which is the number of letters in the string, try
public static int getSum(String s)
{
int sum = 0;
for(int i = 0; i < s.length(); i++)
{
if(Character.isLetter(s.charAt(i)))
{
sum ++;
}
}
return sum;
}
This will only count the characters in the string - much easier than trying to not count everything that isn't a character.

Categories

Resources