For example, if a user were to input "ABZ748FJ9K" as a string, how would I pinpoint the max value of that string (in this case it is 9), and then output it back to the user.
Any non-numeric character is supposed to be ignored.
I tried doing some if-else ladder, but that would require me to list out every number, and it wasn't behaving the way I wanted it to anyways. I know there must be a better solution. Some help would be greatly appreciated. Thanks!
import java.util.Scanner;
public class Question{
public static void main(String args[]){
Scanner input = new Scanner(System.in);
System.out.println("Please enter a string");
String userInput = input.next();
int finalMax = max(userInput);
System.out.println("The maximum value is " + finalMax);
}
public static int max(String s){
int x = s.length();
int y = 0;
for (int i=0; i < x; i++){
if (s.charAt(i) == 9){
y=9;
}
else if (s.charAt(i) == 8){
y=8;
}
}
return y;
}
}
}
Try this:
public static int max(String s){
s=s.replaceAll("\\D","");
int x = s.length();
int y = Character.getNumericValue(s.charAt(0));
for (int i=1; i < x; i++){
if (Character.getNumericValue(s.charAt(i)) > y){
y=Character.getNumericValue(s.charAt(i));
}
}
return y;
}
s=s.replaceAll("\\D","") will make sure all character in your string is a digit by replacing all non-digit character with ""
Use the function below instead of your version:
public static int max(String s){
int x = s.length();
int y = 0;
Character temp = null;
for (int i=0; i < x; i++){
char ch = s.charAt(i);
if (ch >= '0' && ch <='9' && (temp == null || temp < ch )){
temp = s.chartAt(i);
}
}
return Integer.valueOf(temp);
}
Start a max value with 0, then u will loop the string. Each loop u must verify if it is char or int, if int then check if it is > than the max value, if so, set the new max value.
I leave as a challenge to u, to think about each position of the string will be treated as a char.
Cheers. Good luck.
you should try something like:
public static int max(String s){
int max = -1;
char current;
for(int i = 0; i<s.length; i++){
current = s.charAt(i);
if(current > '0' && current < '9')
if(current > max)
max = current;
}
return max;
}
Related
I am creating a hash function by myself for my university assignment. My hash function works something like this ... It will take a string as input and add the ASCII values of every character into a integer variable named sum. This is done in the function named hash_func. Then in the function named MYHashfunc I have used recursion to decrease the value of sum such that it can be a value lesser than the size of the array in which I will store data in using my hash function. Since I am using seperate chaining method to resolve collisions , I used a LinkedList array.
But I am getting a stack overflow error when the function hash_func is called inside MYhashfunc. The code is given below:-
package hashfunction;
import java.util.LinkedList;
import java.util.Scanner;
public class Hashfunction {
public static int MyhashFUNC(String str,int A){
int X=0;
int sum = hash_func(str);
if(sum<A)
return sum;
else{
X = X+sum%10;
sum /= 10;
return(MyhashFUNC(str, A));
}
}
public static int hash_func(String str) {
int sum = 0;
int len = str.length();
for (int i = 0; i < len; i++) {
if (str.charAt(i) >= '0' && str.charAt(i) <= '9') {
sum += (int) str.charAt(i);
} else if (str.charAt(i) >= 'a' && str.charAt(i) <= 'z' ||
str.charAt(i) >= 'A' && str.charAt(i) <= 'Z') {
sum += (int) str.charAt(i);
}
}
return sum;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N;
int z;
N = sc.nextInt();
String[] str_array = new String[N];
LinkedList<String>[] l_list = new LinkedList[N];
for (int i = 0; i < N; i++) {
l_list[i] = new LinkedList<String>();
}
for (int i = 0; i < N; i++) {
str_array[i] = sc.next();
}
for (int i = 0; i < N; i++) {
z = MyhashFUNC(str_array[i],N);
if(l_list[z].peek()!="-1"){
l_list[z].set(z, str_array[i]);
}
else{
l_list[z].add(str_array[i]);
}
}
for (int i = 0; i < N; i++) {
int size = l_list[i].size();
for (int j = 0; j < size; j++) {
System.out.println(l_list[i].get(j));
}
}
}
}
In the method
public static int MyhashFUNC(String str,int A){
int X=0;
int sum = hash_func(str);
if(sum<A)
return sum;
else{
X = X+sum%10;
sum /= 10;
return(MyhashFUNC(str, A)); // Call again MyhashFUNC with same parameters
}
}
if sum >= a you enter the else block and you call again the same method with the same parameters. This will generate the StackOverFlow.
Here's the problem: Look at the return for your function:
return(MyhashFUNC(str, A));
It calls itself again and again and again, without anything to stop it. You keep adding stack frames to the call stack until you get - wait for it - a stack overflow.
This is the hallmark of recursion without a stopping condition.
The Problem is,
This is recursive function, So on every recursive call your input parameter should be change/different/updated.
public static int MyhashFUNC(String str,int A){
int X=0;
int sum = hash_func(str);
if(sum<A)
return sum;
else{
X = X+sum%10;
sum /= 10;
return(MyhashFUNC(str, A));//you are not updating any value and calling same function recursively. this will cause StackOverflowError.
}
}
I am trying to make an int method that converts a binary number into a base 10 number. I think my loop is structured correctly, but I cant figure out how to relate index position to an exponent. Basically if there is a '1' in the string, i want to return it as 2 to the power of whatever the index position of that char is. Also, this would require me to inverse the index (so that the 0 position is the rightmost char of the string. Here is what I have so far:
public static int BinaryToNumber(String numberInput)
{
int len = numberInput.length();
for(int i=len-1; i<len; i--)
{
if(i == '1');
{
return n;
}
}
return 0;
}
Thank you in advance!
I would prefer the Java built-in routines when possible - as I said in my comment Integer.parseInt(numberInput, 2);. By convention, Java method names begin with a lower case letter. Finally, you can fix your code (and I added a small test harness) with something like,
public static int binaryToNumber(String numberInput) {
if (numberInput == null) {
return 0;
}
int ret = 0;
char[] ni = numberInput.trim().toCharArray();
for (int i = 0; i < ni.length; i++) {
if (ni[i] == '1') {
// This is 2 ^ (n) where (n) is based on the position from the right.
ret += 1 << ni.length - i - 1;
}
}
return ret;
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
String t = Integer.toBinaryString(i);
System.out.printf("%s = %d%n", t, binaryToNumber(t));
}
}
this is my implementation for the problem
public static void main(String[] args) {
String str = "100101";
System.out.println(toDecimal(str));
}
private static int toDecimal(String binary) {
int result = 0;
for(int i = 0; i < binary.length(); i++) {
int a = (int) binary.charAt(i) - 48;
double secondPart = 1 << (binary.length()-1) - i;
result += a * secondPart;
}
return result;
}
I hope that helps
Salam
Hi I have to create a method that takes the word message, and counts how many times the character e appears this is what I have but I always get 0. any suggestions?
public class run
{
public static void main(String[] args)
{
String message ="message";
int count=0;
for(int i=0; i>=message.length()-1;i++)
{
char ch = message.charAt(i);
char e='e';
if( ch == e)
{
count = count +1;
}
}
System.out.println(count);
}
}
for(int i=0; i>=message.length()-1;i++)
This will never enter the loop (except for some short-message edge cases where it will then stay in the loop for quite a while) since you have the comparison sense around the wrong way. You need:
for (int i = 0; i < message.length(); i++)
And you don't really need those extra variables, this will do fine:
int count = 0;
for (int i = 0; i < message.length(); i++)
if (message.charAt(i) == 'e')
count++;
Here is another recursive method:
public int countE(String str) {
int count = 0;
if (str.charAt(0) == 'e')
count++;
if (str.length() > 1) {
count += countE (str.substring(1));
}
return count;
}
Heres a recursive solution:
public static int countChar (String message, char e)
{
int charOccurences = 0;
for (int i = 0 ; i < message.length () ; i++)
{
if (message.charAt (i) == e)
{
charOccurences++;
message = message.substring (0, i) + message.substring (i + 1);
return charOccurences + countChar (message, e);
}
}
return charOccurences;
}
I've been stuck on this problem for two hours now. Basically I need to reverse a string (which I've done no problem), then swap every nth letter (which is where im stuck).
Here is what I have so far:
public class StringMethods {
public static void main(String[] args) {
String s = "Hey there";
int n = 2;
System.out.println(reverseString(s));
System.out.println(reverseStringChallenge(s, n));
}
private static String reverseString(String s) {
String reversed = "";
for (int i = s.length() - 1; i >= 0; i--) {
reversed = reversed + s.charAt(i);
}
return reversed;
}
private static String reverseStringChallenge(String s, int n) {
String reversed = "";
String swapped = "";
for (int i = s.length() - 1; i >= 0; i--) {
reversed = reversed + s.charAt(i); // normal reverse
}
char [] charArray = reversed.toCharArray(); //Strings are immutable, convert string to char array
for(int i = 0; i < charArray.length; i++) {
if(i%n == 0) {
//this is where im stuck
}
}
return swapped;
}
}
I know that strings are immutable in java so I need to convert the reversed string into a char array, and then loop through the array but not sure what to do here.
Any advice would be really appreciated. its doing my head in.
Edit: sorry what I mean by swap every nth letter is that say n = 2. then every second letter gets swapped with its previous one.
You didn't clarify the swap logic, but how about something like this:
for(int i = n; i < charArray.length; i += n) {
char a = charArray[i-n];
char b = charArray[n];
charArray[i-n] = b;
charArray[n] = a;
}
Here's a basic swap
int n = 1;
int n1 = 2;
int temp = n; // variable to hold n value
n = n2; // make n = n2
n2 = temp; // make n2 = n
// now n = 2
// and n2 = 1
Not really sure from your question what it is you're trying to do, so I can't really give a definite answer
If you are swapping the current char with the next char you could do something like:
private static String reverseStringChallenge(String s, int n)
{
String reversed = StringUitls.reverse(s);
StringBuilder sb = new StringBuilder();
char [] charArray = reversed.toCharArray();
for(int i = 0; i < charArray.length; i++) {
if(i%n == 0)
{
sb.append(charArray[i+1]).append(charArray[i]);
i++;
}else{
sb.append(charArray[i]);
}
}
return sb.toString();
}
I'm excuse null and out of bound checks =) good luck
My problem is how to count but not count the same character twice. Like comparing 'aba' to 'are' should give 1 as result since it has only one char in common.
This is where I got so far:
public int sameChars (Vector<String> otherStrs){
int result = 0;
String original = "aba";
for (int h= 0; h< otherStrs.size(); h++) {
String targetStr = otherStrs.get(h);
for (int i=0; i< original.length(); i++) {
char aux = original.charAt(i);
for (int j=0; j< Math.min(original.length(), targetStr.length()); j++) {
char targetAux = targetStr.charAt(j);
if (aux == targetAux) {
result++;
break;
}
}
}
}
return result;
}
Ideas are welcome, thanks.
You can create a hash of character count from the original string. Then for each target string, check if it has a char that has a non-zero value in your hash. This will prevent scanning your original string more than once.
Pseudocode:
For each char c in original string {
hash[c]++
}
For each target string str {
For each char c_ in str {
if hash[c_] > 0 {
result++;
}
}
}
This smells like homework, so here's the just the basic idea: You need to keep track of the distinct characters you've already counted as being in both places. A Set might be a good way to do this. Before incrementing your counter, check to see if the character you're looking at is already in that Set.
I am not sure to understand your requirement: do you want to count the number of times the distinct characters found in the reference string original, here "aba" thus 'a' and 'b', are found in a set of strings stored in the Vector otherStrs?
If that's the case, I would advise first to reduce the original string to distinct characters (looking for and removing duplicates, or using a Map). Then loop over the strings in the Vector and do the same for each string (removing duplicates or using a Map) before incrementing your counter each time a character is found in common.
Just out of curiosity, what is the end goal of this computation?
Here's my implementation:
public static int commonChars(String s1, String s2) {
if (s1 == null || s1.isEmpty())
throw new IllegalArgumentException("Empty s1");
if (s2 == null || s2.isEmpty())
throw new IllegalArgumentException("Empty s2");
char[] a1 = s1.toCharArray();
char[] a2 = s2.toCharArray();
Arrays.sort(a1);
a1 = removeDups(a1);
Arrays.sort(a2);
a2 = removeDups(a2);
int count = 0;
for (int i = 0, j = 0; i < a1.length && j < a2.length;) {
if (a1[i] == a2[j]) {
i++;
j++;
count++;
}
else if (a1[i] > a2[j])
j++;
else
i++;
}
return count;
}
public static char[] removeDups(char[] array) {
char[] aux = new char[array.length];
int c = 1;
aux[0] = array[0];
for (int i = 1 ; i < array.length; i++) {
if (array[i] != array[i-1])
aux[c++] = array[i];
}
return Arrays.copyOf(aux, c);
}