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 2 years ago.
Improve this question
I have to Print something like this
But i face Runtime error and wrong answer
input:
153
output:
1:1
5:55555
3:333
get an integer and print each number in its size
import java.util.Scanner;
public class q9774 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
String entery = Integer.toString(n);
char[] E = entery.toCharArray();
for (char value : E) {
System.out.print(value + ": ");
if (value == 0) continue;
else {
for (int i = 0; i < Integer.parseInt(String.valueOf(value)); i++) {
System.out.print(value);
}
System.out.println();
}
}
}
}
Since Java-11, you can use String#repeat to repeat a string for a given number of times.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
String entry = Integer.toString(n);
for (char value : entry.toCharArray()) {
System.out.print(value + ": ");
System.out.println(String.valueOf(value).repeat(Character.getNumericValue(value)));
}
}
}
A sample run:
153
1: 1
5: 55555
3: 333
An alternative way to process each character can be to split the string on each character and then repeat it for number of times equal to its numeric value.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
String entry = Integer.toString(n);
for (String s : entry.split("")) {// Split on each character
System.out.print(s + ": ");
System.out.println(s.repeat(Integer.parseInt(s)));
}
}
}
Here is one way of doing it.
converts the int to a String and then to a char[] array
prints the character followed by itself repeated.
any character digit - '0' is a numeric value of the same quantity represented by the character. So the character '7' has the int value of '7' - '0' or 7.
int i = 153;
for (char c : Integer.toString(i).toCharArray()) {
System.out.printf("%c:%s%n", c, (c+"").repeat(c-'0'));
}
Prints
1:1
5:55555
3:333
I added a nested loop for each digit and I repeat that nested loop according to index of value in string by j <= i; condition:
Scanner input = new Scanner(System.in);
int n = input.nextInt();
String entery = Integer.toString(n);
char[] E = entery.toCharArray();
for (int i = 0; i < E.length; i++) {
for (int j = 0; j <= i; j++) {
System.out.print(E[i]);
}
System.out.println();
}
Related
In this program I have been having trouble to get the terminal window I suspect it might be a runtime error .I am using blue J btw. Also I dont understand why the code used this
f[ch-'A']++;
Please help out with a tracing for this program.
This is the code:
import java.util.*;
public class frequency
{
public static void main(String args[])
{
Scanner sc= new Scanner(System.in);
int f[]= new int[26];
System.out.println("enter a string");
String input = sc.nextLine();
input= input.toUpperCase();
for(int i=0; i<input.length();i++)
{
char ch=input.charAt(i);
if (Character.isLetter(ch))
f[ch-'A']++;
}
System.out.println("Characters Frequency");
for(int i=0;i<26;i++)
{
if( f[i]!=0)
{
System.out.println((char) (i+'A') + "\t\t" + f[i]);
}
}
}
}
Because it is converting the text to uppercase
input= input.toUpperCase();
each char can have the ascii value of A subtracted (see https://www.asciitable.com/) to obtain an index into the array.
'B' - 'A' == 1 etc
test
enter a string
stupid sod
Characters Frequency
D 2
I 1
O 1
P 1
S 2
T 1
U 1
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
package com.jetbrains;
import java.util.Objects;
import java.util.Scanner;
public class SA {
public static void main(String[] args) {
//scanner object
Scanner input = new Scanner(System.in);
//comment
System.out.println("Please enter a line of text below:");
String letters = input.nextLine(); //User's string input
if (letters.length() < 7) {
System.out.println("The input is too short.");
}
//variables
int l = letters.length()-5; //where the last 5 characters are located in user's input string
String answer = letters.substring(l) + letters.substring(2,l) + letters.substring(0, 2); // first 2 & last 5 swapped
if (letters.length() > 7) {
System.out.println("Convert to upper cases:");
System.out.println(letters.toUpperCase());
System.out.println("Swap the first 2 characters with the last 5 characters:"); // Swap
System.out.println(answer);
System.out.println("Is it a palindrome?");
for (int i = (letters.length() - 1); i >= 0; i--) {
char backwards = (letters.charAt(i));
for (int n = letters.indexOf(0); n >= 0; n++) {
char forwards = (letters.charAt(n));
if (Objects.equals(forwards, backwards)) {
System.out.println("True");
else
System.out.println("False");
}
}
}
}
}
}
I've tried comparing my user's input by making the for-loop outputs into char variables but it always returns false. I'm not sure how to fix this last bit, I've tried doing other things but I am completely stumped. My class hasn't learned StringBuilder or StringBuffer so I cannot use them in my code. Any tips or hints would be very helpful, thank you.
I have modified your code little bit to get the correct result -
import java.util.Scanner;
public class StringAnalysis {
public static void main(String[] args) {
//Create scanner object
Scanner input = new Scanner(System.in);
//Comment to the user
System.out.println("Please enter a line of text below:");
String letters = input.nextLine(); //User's string input
if (letters.length() < 7) {
System.out.println("The input is too short. No analysis to be performed.");
}
//variables
int l = letters.length() - 5; //States the index number of where the last 5 characters are located in user's input string
String answer = letters.substring(l) + letters.substring(2, l) + letters.substring(0, 2); // first 2 & last 5 swapped
if (letters.length() > 7) {
System.out.println("Analysis #1: Convert to upper cases:"); // Upper case
System.out.println(letters.toUpperCase());
System.out.println("Analysis #2: Swap the first 2 characters with the last 5 characters:"); // Swapping
System.out.println(answer);
System.out.println("Analysis #3: Is it a palindrome?");
String backwards = "";
for (int i = (letters.length() - 1); i >= 0; i--) {
backwards = backwards + letters.charAt(i);
}
if(letters.equalsIgnoreCase(backwards)) {
System.out.println("True");
} else {
System.out.println("False");
}
}
}
}
You have a problem on the second loop for checking palindrome , i tried to solve it , but eventhough , it compares every backward letters to all forwards which is logically wrong , here is something better you can do :
System.out.println("Analysis #3: Is it a palindrome?");
boolean response = true;
for (int i = 0 ; i < letters.length() ; i++) {
String backwards = String.valueOf(letters.charAt(i));
String forwards = String.valueOf(letters.charAt(letters.length()-i-1));
if(!backwards.equals(forwards)) {
response = false;
}
}
System.out.println(response);
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 6 years ago.
Improve this question
I have written a simple test program for a larger program, where I need to validate the String by a range of letters from a through to g.
The below test program should ask for a letter, then if within range of a-g print an acceptance message, else say 'oops' and ask again.
Try this Code:
public static void main(String... params) {
Scanner s = new Scanner(System.in);
Character minValue = 'a';
Character maxValue = 'g';
while (true) {
System.out.print("enter a char between a-g: ");
Character input = s.nextLine().charAt(0);
if (input >= minValue && input <= maxValue) {
System.out.println("Ok");
} else {
System.out.println("oops");
System.exit(0);
}
}
}
You can get a char from String using charAt(index).
You can check if the char is withing given range using simple comparison like c >= 'a' && c <= 'g'.
First, I don't think you should name your variable "a".
Aniways, I would validate my input like this:
a.compareTo(maxValue) >= 0 && a.compareTo(minValue) <= 0 && a.length == 1
Please try with the below code:
import java.util.Scanner;
import java.util.Scanner;
public class StringValidation {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String a = null;
char minValue = 'a';
char maxValue = 'g';
boolean loop = true;
int i = 0;
while (loop) {
System.out.print("enter a char between a-g: ");
a = input.nextLine();
if ((int) minValue <= (int) a.charAt(i)) {
if ((int) maxValue <= (int) a.charAt(i)) {
System.out.println("Oops! ");
System.out.print("enter a char between a-g: ");
i++;
input.nextLine();
} else {
System.out.println("Accepted");
break;
}
}
}
input.close();
}
}
I was writing some code for my class and I ran into this error, String index out of range. I checked to see if it might be the string = null but that's not the case. I'm guessing it has to do with my if statement in the method but I couldn't find how to fix it anywhere. Any help is appreciated, thank you very much!
import java.util.*;
public class Occurences {
public static void main(String[] args) {
int check = 0;
char characterInput = ' ';
do {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a string: ");
String input = scan.next();
System.out.println("Enter a character to find it's occurence in the string: ");
characterInput = scan.next().charAt(0);
int i = count(input, characterInput);
System.out.println(characterInput + ", is in " + input + ", " + i + " times.");
System.out.println("To continue enter any number, to exit enter -1: ");
check = scan.nextInt();
} while (check != -1);
}
public static int count(String input, char characterInput) {
int cnt = 0;
int j = input.length();
while (j > 0) {
if (input.charAt(j) == characterInput) {
cnt += 1;
}
j--;
}
return cnt;
}
}
The error happens on line 21: int j = input.length(), as others mentioned in the comments, java, and most programming languages, index strings and array types by zero-indexing - starting from zero. So you have to either 1) start counting at 0 or 2) stop counting at one-less-than the length of the string(array), which is why line 21 needs to be either:
int j = input.length()-1;
or as you solved it using method 1:
setting int j=0;
I am supposed to do this :
For an input number print frequency of each number in the order of its occurrence.For eg :
Input:56464
Output:
Number-Frequency
5 -1
6 -2
4 -2
I cannot use any other libraries except java.lang and Scanner to input
So I tried this :
package practice2;
import java.util.Scanner;
public class DigitFrequency2
{
private static Scanner sc;
public static void main(String[] args)
{
sc = new Scanner(System.in);
System.out.println("Enter an integer number");
String sb = sc.nextLine();
System.out.println("Number\tFrequency");
int i,x,c = 0;
for(i=0;i<sb.length();i++)
{
c = 0;
for(x = i+1;x<sb.length();x++)
{
if(sb.charAt(i) == sb.charAt(x) && sb.charAt(i) != '*' && sb.charAt(x) != '*')
{
c++;
sb.replace(sb.charAt(x),'*');
}
}
if(c>0)
{
System.out.println(sb.charAt(i)+" \t"+c);
}
}
}
}
Number Frequency
6 1
4 1
Where am I going wrong please help.
Simple way is this. Won't bother commenting as it is clear whats going on.
Scanner in = new Scanner(System.in);
while (true) {
System.out.print("Input String: ");
String line = in.nextLine();
while (!line.isEmpty()) {
char c = line.charAt(0);
int length = line.length();
line = line.replace(String.valueOf(c), "");
System.out.println(c + " " + (length - line.length()));
}
}
There are few problems with sb.replace(sb.charAt(x),'*');:
replace replaces all characters, not just first one which is why your c can't be grater than 1.
Strings are immutable so since replace can't edit original string, it returns new one with replaced characters which you can store back in sb reference.
Anyway if you would be able to use other Java resources beside java.lang.* or java.util.Scanner simple approach would be using Map which will map character with number of its occurrences. Very helpful here is merge method added in Java 8 allows us to pass key initialValue combination of old and new value
So your code can look like:
String sb = ...
Map<Character, Integer> map = new TreeMap<>();
for (char ch : sb.toCharArray()) {
map.merge(ch, 1, Integer::sum);
}
map.forEach((k, v) -> System.out.println(k + "\t" + v));
Problem is that as mentioned, String is immutable, so String.replace() just returns a new string and it does not (cannot) modify the original. Either you should use StringBuilder, or store the returned value (e.g. sb = sb.replace(sb.charAt(x),'*');).
Going further, since you initialize c with 0, it will stay 0 if there is no other occurrence of the character in question (sb.charAt(i)), so your algorithm won't detect and print digits that occur only once (because later you only print if c > 0).
Counting occurrences (frequency) of characters or digits in a string is a simple operation, it does not require to create new strings and it can be done by looping over the characters only once.
Here is a more efficient solution (one of the fastest). Since digits are in the range '0'..'9', you can create an array in which you count the occurrences, and by looping over the characters only once. No need to replace anything. Order of occurrence is "remembered" in another order char array.
char[] order = new char[10];
int[] counts = new int[10];
for (int i = 0, j = 0; i < sb.length(); i++)
if (counts[sb.charAt(i) - '0']++ == 0)
order[j++] = sb.charAt(i); // First occurrence of the digit
And print in order, until the order array is filled:
System.out.println("Number\tFrequency");
for (int i = 0; order[i] != 0; i++)
System.out.println(order[i] + "\t" + counts[order[i] - '0']);
Example output:
Enter an integer number
56464
Number Frequency
5 1
6 2
4 2
For completeness here's the complete main() method:
public static void main(String[] args) {
System.out.println("Enter an integer number");
String sb = new Scanner(System.in).nextLine();
char[] order = new char[10];
int[] counts = new int[10];
for (int i = 0, j = 0; i < sb.length(); i++)
if (counts[sb.charAt(i) - '0']++ == 0)
order[j++] = sb.charAt(i); // First occurrence of the digit
System.out.println("Number\tFrequency");
for (int i = 0; order[i] != 0; i++)
System.out.println(order[i] + "\t" + counts[order[i] - '0']);
}
Note:
If you would want to make your code safe against invalid inputs (that may contain non-digits), you could use Character.isDigit(). Here is only the for loop which is safe against any input:
for (int i = 0, j = 0; i < sb.length(); i++) {
char ch = sb.charAt(i);
if (Character.isDigit(ch)) {
if (counts[ch - '0']++ == 0)
order[j++] = ch; // First occurrence of ch
}
}
This should be a good code to print frequency using user input:
public static void main(String args[])
{
System.out.println("Please enter numbers ");
String time = in.nextLine(); //USER INPUT
time = time.replace(":", "");
char digit[] = {time.charAt(0), time.charAt(1), time.charAt(2), time.charAt(3)};
int[] count = new int[digit.length];
Arrays.sort(digit);
for (int i = 0; i < digit.length; i++)
{
count[i]++;
if (i + 1 < digit.length)
{
if (digit[i] == digit[i + 1])
{
count[i]++;
i++;
}
}
}
for (int i = 0; i < digit.length; i++)
{
if (count[i] > 0)
{
System.out.println(digit[i] + " appears " + count[i]+" time(s)");
}
}
}