I can't believe i've gotten this far. My problem is my output. This program is suppose to take input from the user and increment each letter by 2. So after taking the String from the user I turn there message into a char array. then while outputing it I added 2 to each letter. and my ouput is acssii numbers. I need it to be the actual letter. how do I do this?
import java.util.*;
public class Encryption {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String userMessage = " ";
Scanner input = new Scanner (System.in);
System.out.print ("Please enter your Message:");
userMessage = input.nextLine().toUpperCase();
char arr[] = userMessage.toCharArray();
for (int i=0; i< arr.length;i++){
System.out.print(arr[i] + 2);
}
}
}
Example input : "Thank you"
Example output : 867467807734918187
Please explain to me why this is happening.
You may try casting the incremented value to char. Also, we can use the modulus operator to make sure that letters wrap around appropriately, e.g. Z should become B:
String userMessage = "ALFXYZ";
char arr[] = userMessage.toCharArray();
for (int i=0; i< arr.length;i++) {
int nextNum = 65 + (arr[i] + 2 - 65) % 26;
System.out.print((char)nextNum);
}
Demo
Your current code, as you wrote it, is printing numbers because of the casting rules.
Java cannot know ahead of time that arr[i] + 2 will be within the bounds of char (0-65535) so it will treat that expression as a number.
If you're sure the value of arr[i]+2 will never exceed this range then you can safely cast back to a char:
System.out.print((char)(arr[i] + 2));
Java converts some primitive types automatically.
If c is a char and i is an int, then c + i will be treated as an int.
PrintStream, the type of System.out, has many overloads of print; the one chosen depends on the type of the argument.
Cast your addition back to char and it should work:
(char)(arr[i] + 2)
Related
I know similar questions have been asked. I've read through them and have developed what I thought was a reasonable solution to my problem. However, when I run the code it does not perform as I think it should. I'm obviously missing something here.
I need to read in a string (a propositional logic statement) and determine how many variables it has. My thought process is: convert the string to a charArray and compare the elements. If a certain element is a letter AND is not equal to another element in the array, it is a new variable, thus adding to the variable count, and also needs to be stored in a separate array for later use.
public class PropLogic {
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
String statement;
int numOfVariables = 0;
System.out.println("Enter your propositional statement:");
statement = stdin.nextLine();
char[] charStatement = statement.toCharArray();
char[] variables;
variables = new char[25];
// Counts number of variables in statement
for (int i = 0; i < statement.length(); i++){
for(int j = i + 1; j < statement.length(); j++){
if(Character.isLetter(charStatement[i]) && (charStatement[i] !=
charStatement[j])){
variables[i] = charStatement[i];
numOfVariables++;
}
}
}
System.out.println("The number of variables is " + numOfVariables);
System.out.println("The variables are " + new String(variables));
}}
With input "hello" I get output of 9 variables and that the variables are "hell" when I want to be getting 4 variables that are "hello".
Why don't you use a Set. A set has the property that you can enter the same object only once into it. Here is one version:
Set<Character> set = new LinkedHashSet<>();
for(int i = 0; i< statement.length(); i++) {
set.add(statement.charAt(i));
}
System.out.println("The number of variables is " + set.size());
System.out.println("The variables are ");
set.forEach(System.out::println);
You don't need to use char array since String has the methods CharAt() and contains().
Then you have to run through your String. When you find a new letter (which mean this letter is not in the already found array), you put it in the already found array and you increment your counter. (note that the counter is useless since it as the same value as the length of the already found array). You should obtain something like this :
String statement = stdin.nextLine();
String variables = ""; //empty String
//Go through the whole String statement
for (int i = 0; i < statement.length(); i++){
//Check if this letter was not already found and it's a letter
if(!variables.contains(statement.charAt(i)) && Character.isLetter(statement.charAt(i)) ){
//Add this letter to the found ones
variables.concat(String.valueOf(statement.charAt(i)));
}
}
System.out.println("The number of variables is " + variables.length());
System.out.println("The variables are " + variables);
I see two problems:
Problem 1. Think about what happens, for example, with the "h" of "hello." You compare it, in turn, to "e", "l", "l", and "o", and for each of them, you add a new variable. What you want is to add a new variable only if ALL of the future letters are not equal to the "h." This is why you are getting 9 variables total: you add one for each of the following comparisons:
(h, e), (h, l), (h, l), (h, o)
(e, l), (e, l), (e, o)
(l, o)
(l, o)
This is also why you are getting "hell" as your final variables array. The o is never compared to anything, so never gets added to the array.
What you really want to do is go through the entire rest of the string, and check if anything is equal to the current letter. You can do this with a boolean flag. Here is pseudocode:
for i = 0 to len(charArray):
isNewVariable = isLetter(charArray[i])
for j = i+1 to len(charArray):
if charArray[i] == charArray[j]:
isNewVariable = false
if isNewVariable:
Add charArray[i] to variables
Problem 2. You are filling in the wrong index of your variables array. You want to fill in variables[numOfVariables], not variables[i]. Let's say the first and seventh letters are variables; then you want variables[0] and variables[1] to be set to the two variables, not variables[0] and variables[6], which is what your current code does.
Hope this helps! If you fix these two errors, your code will work; however, as other answers point out, this general strategy is not the best for this specific task. Incrementally adding to an array (like variables) is best done with an ArrayList; even better, a Set is exactly suited for the task of finding just the unique elements of an array.
what is happening here is, check if char exists in temp string with 'temp.indexOf(char)', it returns 1 if it exists at an index of that string and 0 otherwise.
so if 0, then add and loop to next char.
public static void main( String[] args ){
Scanner stdin = new Scanner(System.in);
String statement;
int numOfVariables = 0;
System.out.println("Enter your propositional statement:");
statement = stdin.nextLine();
char[] charStatement = statement.toCharArray();
char[] variables;
variables = new char[25];
String temp = "";
for (int i = 0; i < statement.length(); i++){
char current = statement.charAt(i);
if (temp.indexOf(current) < 0){
temp = temp + current;
}
}
System.out.println("The number of variables is " + temp.length());
System.out.println("The variables are " + temp);
}
A key to success in writing good programs is to make sure it has as few lines of code as possible and it doesn't repeat an operation that it has already performed or that is not even needed.
If you think about your problem statement, basically, all you need to do is extract letters from a given input string and remove duplicates. With advance programming languages like Java, String operations shouldn't take more than a couple of lines of codes. If it is more than 2 lines, in most cases, it has a lot of boiler plate code.
See if the following line of code meets your objective.
Set<String> variables = Arrays.stream(statement.split("")).filter(str -> Character.isLetter(str.charAt(0))).collect(Collectors.toSet());
If you are OK with not insisting on char[] variables and use List<Character> instead, this does the job
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class PropLogic {
public static List<Character> parseVariables(char[] input) {
List<Character> candidates = new ArrayList<>();
for (int i = 0; i < input.length; i++){
Character c = input[i];
if( Character.isLetter(c) && !candidates.contains(c)) {
candidates.add(c);
}
}
return candidates;
}
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
System.out.println("Enter your propositional statement:");
char[] charStatement = stdin.nextLine().toCharArray();
List<Character> variables = parseVariables(charStatement);
System.out.println("The number of variables is " + variables.size());
System.out.println("The variables are " + variables);
}
}
Sample output:
Enter your propositional statement:
hello1
The number of variables is 4
The variables are [h, e, l, o]
Here's a 1-liner:
String[] variables = statement.replaceAll("[^a-z]|(.)(?=.*\\1)", "").split("(?<=.)");
This uses regex to remove (by replacing with a blank) all non-lowercase letters OR all letters that are repeated later on (ie remove dupes).
Then it splits after each letter giving you the final array of unique letters from the input.
Note that this creates a String[] rather than a char[], which you can just as easily use. If you really want a char[], you can do this:
String[] variables = statement.replaceAll("[^a-z]", "").chars()
.distinct().mapToObject(c -> (char)c).toArray();
I am practising with algorithms, and I have this problem where I have to state how many of each of the letters in the word appear. e.g. input = floor , output = f1l1o2r1. I have the following code:
public static void main(String[] args) {// TODO code application logic here
Scanner inword = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
System.out.println("Enter word");
String word = inword.nextLine();
int length = word.length();
char[] wordArray = word.toCharArray();
for(int i = 0; i<length; i++){
int count = StringUtils.countMatches(word, String.valueOf(wordArray[i]));
System.out.print(wordArray[i] + count);
}
}
but instead I get this as output: 103109113113115 , when I enter floor as input
Your problem is that you print out the ascii-code value of the char. Try
System.out.print(wordArray[i]+"" + count);
instead of
System.out.print(wordArray[i] + count);
First, you should use countMatches(word, wordArray[i]); But that will not solve the entire problem. For example, your approach would lead to an output of "f1l1o2o2r1", and for the word "boohoo", you would get "b1o4o4h1o4o4".
You need to rethink how to do it if you want the output to show the number of consecutive same letters ("b1o2h1o2"), or if you want the number of each letter, specified only once, in order of first appearance ("b1o4h1"), or the number of appearances of letters alphabetically ("b1h1o4").
Considering the implementation of StringUtils.countMatches() is correct, the problem lies in the line
System.out.print(wordArray[i] + count);
Here, when you do wordArray[i], it returns a char. However, doing +count, converts that char into its ASCII value, and adds up count to it.
To fix it, try doing:-
System.out.print(wordArray[i] + " " + count);
B's and G's this is driving me nuts. I am hoping one of you guru's can save me from stuff my head int he toilet and singing! I am trying to copy one array fo char's to another without copying the whitespaces. This is not final code in the sense that it only accounts for ' ' and not the various other forms of whitespace i.e \t. But that is not the main issue.
import java.io;
import java.util.*;
public class tester
{
public static void main(String args[]) throws Exception
{
Scanner in = new Scanner(new File("intxt.txt"));
String x = "";
while(in.hasNext())
{
x = in.nextLine();
}
System.out.println("This line has " + x.length() + "characters.");
char[] charAr = x.toCharArray();
for(int i = 0; i<charAr.length; i++)
{
//prints the int representation of all values
System.out.print((int)charAr[i] + " ");
}
char[] out = new char[charAr.length];
for(int i =0; i<out.length; i++)
{
char y = ' ';
if(charAr[i] != y)
{
System.out.println("in here " + (int)y);
out[i] = charAr[i];
}
}
for(int i = 0; i<out.length; i++)
{
//should print hellothere
System.out.print(out[i]+" ");
}
}
}
A char array, when constructed, is filled with 0.
Your loop sets the output char array element i to the same value as the input char array element i if this element is not a whitespace. Otherwise, it leaves the output element as it is (and its value is thus 0).
You need to have seperate indices for your input array and your output array, since you want to skip white spaces. So, assuming the input array has 8 chars and two of them are white spaces, the 6 first elements of your output array should be filled, and the last two ones should be set to whatever you want them to be set.
0 1 2 3 4 5 6 7 8 9 10
input: h e l l o t h e r e
output: h e l l o t h e r e ?
You see in the above example that the indices of the characters don't match.
I assume this is some kind of homework. If it's not, then by all means use a StringBuilder to build your output string.
while(in.hasNext())
{
x = in.nextLine();
}
Shouldn´t be the rest of your code also be within this loop? This loop is pretty meaningless besides picking the last line in "intxt.txt".
What's wrong with your code?
I think a good piece of advice would be that if you're not sure about the correctness of the procedure/algorithm you're using, adding input-dependent stuff is not clever ...
Hence, I'd initialize x with the value you're expected to read from the input file. Is that the string hello there, right? So instead of
Scanner in = new Scanner(new File("intxt.txt"));
String x = "";
while(in.hasNext())
{
x = in.nextLine();
}
I would simply write
String x = "hello there";
NOTE: I'm assuming it is a typo, but if it's not, first line is wrong. I think you were meant to write
import java.io.*;
Moreover, write variable identifiers that are more meaningful. lineRead is better than x, imho.
EDIT: If your expecting to read hellothere, with no blanks between characters, you should remove the whitespace appended to every out[i].
System.out.println(out[i]);
First off i am pretty fresh when it comes to java. My program is supposed to ask the user for strings and print what they just put in. It is then supposed to change all characters to lowercase and remove all spaces from the strings and print this. After this, it is supposed to print a character array of the alphabet and use an asterisk (*) to show each time a character occurs in the string (I dont even know where to start here). Right now it just prints the String in an array(not correct). This is what I have so far. It will print either the string with no spaces or the original but not both. My object/array naming is atrocious and i apologize in advance. Any guidance would be greatly appreciated
EDIT: here is the question
In this assignment you are to write a program that will do the following:
Ask the user to input a positive integer m, and then read that integer. Use a
Scanner object declared in main to read this integer.
Call a method that will ask the user to input m strings. As the strings are
read, they should be concatenated into a single string st. After reading the m strings and forming the single string st, the method should return st. NOTE: This method will have two parameters, an int to receive m and a Scanner object to receive the Scanner object declared in main.
In main print the concatenated string received from the method.
In main convert the String object to lower case.
In main convert the lower case String object to an array of char. (All letters
will be lower case.)
In main print the character array just created. (Requires a looping structure.)
Call a method that will compress the character array in the following way.
The method will count the letters of the alphabet in the array, create a new array whose size is equal to that count, and copy only the letters of the original array into the new array. Return the new array.
In main declare an integer array of size 26. Call a method with two parameters, a character array x (which will contain only lower case letters, and an integer array z that will receive the one declared in main). The method will set all entries in the integer array to zero. It will then process through the lower case letter array and count the number of times each letter occurs. HINT: z[x[i]-97]++ can do the counting. The ASCII code for a is 97, so if x[i] is ‘a’, then z[0] will be incremented. ‘b’ would cause z[1] to be incremented, etc. The integer array now contains a frequency distribution for the letters in the array of lowercase letters.
Call a method with one integer array parameter (which will receive the frequency distribution array) and print each letter on a new line followed by the number of stars equal to the integer value in that array element. This must be neatly aligned. Hint: if i is an index with 0 ≤ 𝑖 ≤ 25, then (char)(i+97) is a lower case letter of the alphabet.
package lab6;
import java.util.Scanner;
public class Lab6 {
public char sent[];
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("enter the number of strings you want: ");
int m = input.nextInt();
Lab6 loo = new Lab6();
loo.print(loo.loop(m));
}
public String loop(int m) { //print the string that was entered
String total = " ";
for (int i = 1; i <= m; i++) {
Scanner input = new Scanner(System.in);
System.out.println("enter string: " + i);
String st = input.nextLine();
total += st + "";
}
System.out.println(total);
return total;
}
public void print(String ht) { //print array
String st = ht.toLowerCase().replaceAll("\\s", "");
sent = st.toCharArray();
for (int i = 0; i < sent.length; i++) {
System.out.println(sent[i]);
}
}
}
Sounds like computer science is not your cup of tea. I Strongly recommend you refactor this code and try to figure out why it does what it does.
public void print(String ht) { // print array
String st = ht.toLowerCase().replaceAll("\\s", "");
sent = st.toCharArray();
int[] alphabet = new int[26];
//set all values to 0
for(int i = 0 ; i < alphabet.length ; i++){
alphabet[i] = 0;
}
//Loop through all characters and increment corresponding value
for(int i = 0 ; i < sent.length ; i++){
alphabet[sent[i] - 97]++;
}
//Print character + asterisk for each time the character is used
for(int i = 0 ; i < alphabet.length ; i++){
System.out.print((char)(i + 97) + ": ");
for(int nChars = 0 ; nChars < alphabet[i] ; nChars++){
System.out.print("*");
}
System.out.println();
}
}
This question already has answers here:
Java compressing Strings
(21 answers)
Closed 8 years ago.
I am trying to write a Java program which takes in as input a string and counts the number of occurrences of characters in a string and then prints a new string having the character followed by the no of occurrences.
E.G.
Input String:
aaaabb
Output String:
a4b2
Input String:
aaaaabbbc
Output String:
a5b3c1
I am posting my java code.
It is throwing StringOutOfBoundException
/*Write a routine that takes as input a string such as "aabbccdef" and o/p "a2b2c2def" or "a4bd2g4" for "aaaabddgggg".*/
import java.util.Scanner;
public class CountingOccurences {
public static void main(String[] args) {
Scanner inp= new Scanner(System.in);
String str;
char ch;
int count=0;
System.out.println("Enter the string:");
str=inp.nextLine();
while(str.length()>0)
{
ch=str.charAt(0);
int i=0;
while(str.charAt(i)==ch)
{
count =count+i;
i++;
}
str.substring(count);
System.out.println(ch);
System.out.println(count);
}
}
}
This is the problem:
while(str.charAt(i)==ch)
That will keep going until it falls off the end... when i is the same as the length of the string, it will be asking for a character beyond the end of the string. You probably want:
while (i < str.length() && str.charAt(i) == ch)
You also need to set count to 0 at the start of each iteration of the bigger loop - the count resets, after all - and change
count = count + i;
to either:
count++;
... or get rid of count or i. They're always going to have the same value, after all. Personally I'd just use one variable, declared and initialized inside the loop. That's a general style point, in fact - it's cleaner to declare local variables when they're needed, rather than declaring them all at the top of the method.
However, then your program will loop forever, as this doesn't do anything useful:
str.substring(count);
Strings are immutable in Java - substring returns a new string. I think you want:
str = str.substring(count);
Note that this will still output "a2b2a2" for "aabbaa". Is that okay?
public class StringTest{
public static void main(String[] args){
String s ="aaabbbbccccccdd";
String result="";
StringBuilder sb = new StringBuilder(s);
while(sb.length() != 0){
int count = 0;
char test = sb.charAt(0);
while(sb.indexOf(test+"") != -1){
sb.deleteCharAt(sb.indexOf(test+""));
count++;
}
//System.out.println(test+" is repeated "+count+" number of times");
result=result+test+count;
}
System.out.println(result);
}
}
I don't want to give out the full code. So I want to give you the challenge and have fun with it. I encourage you to make the code simpler and with only 1 loop.
Basically, my idea is to pair up the characters comparison, side by side. For example, compare char 1 with char 2, char 2 with char 3, and so on. When char N not the same with char (N+1) then reset the character count. You can do this in one loop only! While processing this, form a new string. Don't use the same string as your input. That's confusing.
Remember, making things simple counts. Life for developers is hard enough looking at complex code.
Have fun!
Tommy "I should be a Teacher" Kwee
if this is a real program and not a study project, then look at using the Apache Commons StringUtils class - particularly the countMatches method.
If it is a study project then keep at it and learn from your exploring :)
You should be able to utilize the StringUtils class and the countMatches() method.
public static int countMatches(String str,
String sub)
Counts how many times the substring appears in the larger String.
Try the following:
int count = StringUtils.countMatches("a.b.c.d", ".");
I think what you are looking for is this:
public class Ques2 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = br.readLine().toLowerCase();
StringBuilder result = new StringBuilder();
char currentCharacter;
int count;
for (int i = 0; i < input.length(); i++) {
currentCharacter = input.charAt(i);
count = 1;
while (i < input.length() - 1 && input.charAt(i + 1) == currentCharacter) {
count++;
i++;
}
result.append(currentCharacter);
result.append(count);
}
System.out.println("" + result);
}
}
Try this:
import java.util.Scanner;
/* Logic: Consider first character in the string and start counting occurrence of
this character in the entire string. Now add this character to a empty
string "temp" to keep track of the already counted characters.
Next start counting from next character and start counting the character
only if it is not present in the "temp" string( which means only if it is
not counted already)
public class Counting_Occurences {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("Enter String");
String str=input.nextLine();
int count=0;
String temp=""; // An empty string to keep track of counted
// characters
for(int i=0;i<str.length();i++)
{
char c=str.charAt(i); // take one character (c) in string
for(int j=i;j<str.length();j++)
{
char k=str.charAt(j);
// take one character (c) and compare with each character (k) in the string
// also check that character (c) is not already counted.
// if condition passes then increment the count.
if(c==k && temp.indexOf(c)==-1)
{
count=count+1;
}
}
if(temp.indexOf(c)==-1) // if it is not already counted
{
temp=temp+c; // append the character to the temp indicating
// that you have already counted it.
System.out.println("Character " + c + " occurs " + count + " times");
}
// reset the counter for next iteration
count=0;
}
}
}