I'm writing a java code currently for class and I'm trying to figure out how to implement a run length encoding on a user input. The main problem I'm having it with comparing the first letter with the next and that letter with the next and so on to see if they're the same letter. Currently I have:
System.out.print("Enter a string: ");
String s1 = reader.nextLine();
int sum = 0;
char ast = '*';
//System.out.println("Run length encoded version of string: ");
for (int counter = 0; s1.charAt(counter) <= s1.length()-1; counter++) {
for (int j = 0; s1.charAt(counter) == s1.charAt(j)+1; j++) {
sum++;
counter++;
}
if (sum >= 4) {
System.out.print(ast + s1.charAt(counter) + sum);
}
else {
System.out.print(s1.charAt(counter));
}
}
I know where the big problem comes from in this and why it doesn't work but, namely from the
for (int j = 0; s1.charAt(counter) == s1.charAt(j)+1; j++) {
sum++;
counter++;
}
segment as it just goes infinitely. Is there a proper way to do this? The professor mentioned it can be done without loops and while I can see it being possible I can't see it being short. Any help would be appreciated, thanks!
String str="ayyusaab";
char[] ch=str.toCharArray();
for(int i=0;i<ch.length-1;i++){
for(int j=i+1;j<ch.length-1;j++){
if(ch[i]==ch[j]) {
System.out.println(ch[i]+" at Index "+i +"with j at "+j);
}
}
}
Related
I'm completely new to coding and my teacher is terrible at explaining things. I have no idea what's going on in the class, and I really need help with this!
I've made lots of pyramid patterns before, but this is one I can't figure out.
I know how to get user input too, but I just need help understanding why this won't work. He briefly explained how to code this problem to us, but it doesn't work no matter how many times I change and try it.
I have to create a pyramid using the number of lines the user inputs. So if the user entered 5, this is what it should look like:
*
**
***
****
*****
So the number of spaces on the first line is four, the second one has three spaces, and so on until you get to zero.
This is the code (which gives a completely inaccurate output):
System.out.print("\f");
System.out.println("Enter a valid number between 1 and 20.");
int num = 0;
int counter = 1;
num = keyNum.nextInt();
for (int i = 1; i == num; i++)
{
for (int j = 1; j == (num -= counter); j++)
{
System.out.print(" ");
}
for (int k = 1; k == counter; k++)
{
System.out.print("*");
}
System.out.println("");
counter++;
}
Please help! I feel so stupid.
I doubt your teacher will accept this. But it is just a one liner for fun
int num = 20;
IntStream.range(0, num).forEach(i -> System.out.println(String.format("%" + num + "s", new String(new char[i+1]).replace("\0", "x"))));
It's mostly right, but you are starting the loops from 1, but they really should be starting from 0, and the condition in the for loops shouldn't have == which just makes it run once.
for (int i = 0; i < num; i++) {
for (int j = 0; j <= (num - counter); j++) {
System.out.print(" ");
}
for (int k = 0; k < counter; k++) {
System.out.print("*");
}
System.out.println("");
counter++;
}
it's pretty close mostly the for loop is wrong.
for(initialization;condition;increment)
the for loop only executes when the condition is true. In your case the conditions don't really make sense. Try changing it. also your counter and i are the same thing :)
Interesting coding exercise. You got it almost right anyway as others pointed out.
There are hundred ways to solve the problem.
Here is just a variation that saves a loop...
int lines=5;
for (int i=0; i<lines; i++) {
for (int k=0; k<lines; k++) {
System.out.print( (k < lines - i - 1) ? " " : "*");
}
System.out.println();
}
Another solution using a single (explicit) loop:
for (int i = 1; i <= num; i++) {
int expectedSpaces = num - i;
String spaces = repeat(" ", expectedSpaces);
String asterisks = repeat("*", i);
System.out.println(spaces + asterisks);
}
}
private static final String repeat(String toBeRepeated, int length) {
return new String(new char[length]).replace("\0", toBeRepeated);
}
As mentioned elsewhere, loop variables such as i usually start at 0 since such variables can be used as an array/List index. However, in this case there is no related array or List so sarting at 1 simplifies the logic.
I worked on something similar, this is what I did, you could give it a try. It takes a user input and displays spaces and "#"...
int size = n;
for (int i = 0; i <= size-1; i++){
for(int j = size -1; j > i; j-){
System.out.print(" ");
}
for(int j = 0; j <= i; j++){
System.out.print("#");
}
System.out.println();
}
The output would be:
#
##
###
####
#####
######
I got a school assignment that I have to create a program that prints the first recurring character in a given string.
For example, if the input is "helloo", then it should output as "l". I wrote the following code but it prints "l" and "o" both.
String text = "helloo";
int length = text.length();
for (int i = 0; i <= length - 1; i++) {
char curChar = text.charAt(i);
for (int j = i + 1; j <= length - 1; j++) {
if (curChar == text.charAt(j)) {
System.out.println(curChar);
break;
}
}
}
Can someone help me out with this? Thanks for any answers!
You're breaking just the inner loop but not the outer loop. You can use break with a label for the outer loop. For example:
String text = "helloo";
int length = text.length();
outerloop:
for (int i = 0; i <= length - 1; i++) {
char curChar = text.charAt(i);
for (int j = i + 1; j <= length - 1; j++) {
if (curChar == text.charAt(j)) {
System.out.println(curChar);
break outerloop;
}
}
}
Get more information here - How to break out of nested loops in Java?
Hope this helps, but you should try doing your school assignments yourself.
I realize that you are asking for a direct fix to your current approach. But for those who might read this question in the future, there is a very sleek approach here using regular expressions:
String text = "helloo";
String match = text.replaceAll("^.*?(.)\\1.*", "$1");
System.out.println(match);
l
Demo
The basic idea of the pattern ^.*?(.)\1 is to consume the least number of characters in the string until we hit a single character which is followed by that same character.
Here's another variant:
String text = "helloo";
ArrayList<String> a = new ArrayList<String>(Arrays.asList(text.split(Pattern.quote(""))));
for(int i = 0; i < a.size()-1;i++) {
if(a.get(i).compareTo(a.get(i+1)) == 0) {
System.out.println(a.get(i));
break;
}
class FirstRepeatingChar
{
public static void main(String args[])
{
String s="hello";
for(int i=0;i<s.length();i++)
{
for(int j=0;j<s.length();j++)
{
if(s.charAt(i)==s.charAt(j))
{
System.out.println(" the First non repeating character is " +s.charAt(i));
break;
}
}
}
}
}
OK, i know this question was asked many times here, but i still don't get it, how to find the first repeated character in a string ?
I did something which was close, but it gave me all repeated characters instead of only the first one.
Here's what i did :
private static void stringChar(){
String s = "sababa";
int count = 0;
char c[] = s.toCharArray();
System.out.println("Duplicate characters are :");
for(int i = 0; i < s.length(); i++){
for(int j = i + 1; j < s.length(); j++){
if(c[i] == c[j]) {
System.out.println(c[j]);
count++;
break;
}
}
}
}
One quick and dirty (yet effective) approach which comes to mind is to maintain a map whose keys are the characters. In this case, we don't even need a formal map, because we can use an integer array which maps to the underlying ASCII values of the characters.
The basic idea here is to walk down the string, and check the array if we have seen it before. If so, then print that character and exit.
int[] nums = new int[128]; // assuming only basic ASCII characters
String str = "stuff";
for (int i=0; i < str.length(); ++i) {
int index = str.charAt(i);
if (nums[index] != 0) {
System.out.println("The first repeated character is: " + str.charAt(i));
break;
}
++nums[index];
}
Demo
You need to break the outer loop if you have already found the repeating character.
boolean found = false;
for(int i = 0; i < s.length(); i++){
for(int j = i + 1; j < s.length(); j++){
if(c[i] == c[j]) {
System.out.println(c[j]);
found = true;
break;
}
}
if (found) {
break;
}
}
If you want the count of it
int count = 0;
char repeatingChar = '0'; //dummy to overcome compiler warning
for(int i = 0; i < s.length(); i++){
for(int j = i + 1; j < s.length(); j++){
if(c[i] == c[j]) {
repeatingChar = c[j];
count++;
}
}
if (count > 0) {
System.out.println("Repeating char is " + repeatingChar + ". Occurred " + count + " times");
break;
}
}
The first repeated char is one you have seen before as you iterate the chars in the string. You can keep track of the first time you see a char with a Boolean array. The array is indexed with the char value. Java automatically "widens" char to int. So, for each char, check if it's been seen before and if not, mark that it has been seen.
String s = "sababa";
boolean[] seenChars = new boolean[Character.MAX_VALUE + 1]; // initialized to all false.
for (char c : s.toCharArray()) {
if (Character.isSurrogate(c)) throw new IllegalArgumentException("No first char seen before seeing a surrogate. This algorithm doesn't work for codepoints needing surrogates in UTF-16.");
if (seenChars[c]) {
System.out.println("First repeated char is: " + c);
break;
}
seenChars[c] = true;
}
You might notice that I've been saying char instead of character. Character is not a well-defined term. Java's text datatypes use the UTF-16 encoding of the Unicode character set. Some Unicode codepoints require two UTF-16 code units (char), which are sometimes called surrogate pairs. Since they are not all unique as individual chars, the algorithm doesn't work if they are present. For example, try String s = "sab🚲aba"; (You can also write it as "sab\uD83D\uDEB2aba".) The answer would be "a", again. But now try String s = "sab🚲🚶aba"; (You can also write it as "sab\uD83D\uDEB2\uD83D\uDEB6aba".) The answer should still be "a" but the algorithm would say "\uD83D" (which of course can't be displayed because it is only part of a codepoint).
Short and Simple >
void findFirstDupChar() {
String s = "google";
Integer dupIndex = s.length() - 1;
boolean isDuplicateExists = false;
Map<Character, Integer> map = new LinkedHashMap<>();
char[] words = s.toCharArray();
for (int i = 0; i < words.length; i++) {
Integer index = map.put(words[i], i);
if (index != null) {
if (index < dupIndex) {
dupIndex = index;
isDuplicateExists = true;
}
}
}
System.out.println(isDuplicateExists ? words[dupIndex] + ", index=" + dupIndex : "No duplicateds found");
}
This will print output as following >
g, index=0
So , I am trying to create a program which calculates the score of an exam . What we have to do is give a pattern as a string consisting X's and 0's i.e 000XXX000XXX, where the value of 'X' is 0 and the value of each zero is 1 and for every consecutive '0' the value increases by 1 . If suppose there are 2 or more consecutive 0's and then an 'X' the value of '0' is reset to 1.if the program seems common to you , then , yes this is a problem from an OJ and it was given to me by a senior from my university to solve.Now the thing is I have figured out how the code works and solved the problem.But there seems to be an issue in the code.
package javaapplication4;
import java.util.Scanner;
public class JavaApplication4 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T, score = 0, f = 0, g = 0;
String str;
int len;
T = sc.nextInt();
for (int i = 1; i <= T; i++) {
str = sc.nextLine();
len = str.length();
for (int j = 0; j < len; j++) {
if (str.charAt(j) == '0') {
f++;
score = score + f;
}
else if(str.charAt(j) == 'X')
{
f = 0;
score = score + g;
}
}
System.out.println(score);
}
}
}
As you can see from the code , I first give an Input for the number of test cases and as soon as I press enter , the code displays the value of score (which is 0) automatically without doing any think inside the for loop.
I have rechecked all the curly braces, but I cannot find the bug in the code. I would be happy if I could get some help.
Output:
4
0
The sc.nextInt() causes the sc.nextLine() to be triggered so you get the output of a empty string that's why it's zero, by using sc.nextLine() for input of your test case number you can prevent this:
int score = 0;
System.out.println("Enter test case:");
int testCase= Integer.parseInt(sc.nextLine());
for (int i = 1; i <= testCase; ++i)
{
System.out.println("Enter pattern:");
String str = sc.nextLine();
for (int j = 0; j < str.length(); j++)
{
if (str.charAt(j) == '0')
{
score += 1;
}
else if (str.charAt(j) == 'X')
{
score += 0;
}
}
System.out.println(score);
score = 0; // reset score to zero for the next test case
}
See this link regarding the sc.nextInt() issue : Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods
I have attempted to complete the following exercise however the output isn't as expected.
You should print a number of pluses equal to the number entered by the user, followed by a list of numbers, so that in total exactly 20 characters are printed. The numbers printed should be the last digit of the current position in the list. Example: +++++678901234567890 if the number entered by the user was 5.
Here's my code:
package interact;
import java.util.Scanner;
public class Interact {
public static void main(String[] args) {
Scanner scanner = new Scanner (System.in);
{int value,k
for (int i=0; i<num1; i++) {
System.out.print("+");}
for (int j=0; j<20-num1; j++) {
if (num1>9) {k=num1-10;}
else k=num1+1;
System.out.print(k);
}
}
The output if 6 is entered is ++++++77777777777777. The numbers aren't incrementing - why not?
You aren't incrementing k or num1, so k becomes whatever number the user enters + 1, and keeps printing that out. You need to update k. First set k=num1. Then change your loop to:
if (k>9) {k=0;}
else k++;
System.out.print(k);
Since, your num1 remains same throughout the below loop.
for (int j=0; j<20-num1; j++) {
if (num1>9) {k=num1-10;}
else k=num1+1;
System.out.print(k);
}
But if you do like this it'll work
k=num1+1;
for (int j=0; j<20-num1; j++) {
if (k>9) {k=0;}
System.out.print(k);
k++;
}
This should fix it for you :)
i can answer any questions you got on the modification :)
good luck :)
int value, k;
for (int i = 0; i < num1; i++) {
System.out.print("+");
}
k=num1;
for (int j = 0; j < 20 - num1; j++) {
if (k >= 9) {
k = 0;
}
else
k++;
System.out.print(k);
}