find the value of variable given in a string - java

Given a equation :
433+4H8= 871
H can be anyside of equation. Find the value of H and replace it in given equation.
The output should be :
433+438=871
I have tried the following code but conversion of string to int does not work...
import java.util.Scanner;
import java.io.*;
class hole
{
public static void main(String[] args)
{
Scanner reader= new Scanner(System.in);
int[] nums= new int[3];
String str= reader.nextLine();
String str_1= str.replaceAll("=","+");
String[] split= str_1.split("[+]");
for (int k=0; k<split.length; k++)
{
String ex= split[k];
nums[k]= Integer.parseInt(ex);
}
}
}

4H8 isn't an integer, so parseInt won't work on it.
It seems like you still have a bit of a way to go on this, so I won't spoil your fun by giving you the code, just some ideas.
Assuming the equation is always X + Y = Z, which X, Y and Z being some integers, one of which can contain an H...
You need to have a couple of cases:
If the H is in X, you can get X by subtracting Y from Z.
If the H is in Y, you can get Y by subtracting X from Z.
If the H is in Z, you can get Z by adding X and Y.
But this still doesn't give you H. For this, you can simply find the position of the H in the string we have and extract the digit at that position in the number calculated above.
So before calling parseInt, you should look for the H and simply store the string instead if you find it.
parseInt also doesn't like spaces, so you should remove those in some way or another.
If equations aren't always in the form X + Y = Z (i.e. you can also have subtraction, multiplication, division and/or multiple terms), it gets a bit more complicated.

Why would you not just subtract the final answer minus the first number and build the third number. Splitting the string is redundant as you can just use simple math to solve for x.
871-433 = 438
h=3
public static void main(String[] args)
{
int a = 433;
int b = 871;
int c = b - a;
String s = "4H8";
char x;
int location = 0;
for(int i = 0; i < s.length(); i++)
{
char d = s.charAt(i);
if(d.isDigit()){
}
else{
location = i;
x = d;
}
}
String solve = c.toString();
System.out.println(x + "=" + solve.charAt(location) );
}

Try this (comments are self explanatory):
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int[] nums = new int[3];
int varIndex = 0;
int result = 0;
String str = reader.nextLine();
//remove spaces and split into 3 parts based on symbols
String[] components = str.replaceAll(" ", "").split("\\+|=");
for (int i = 0; i < components.length; i++) {
try {
nums[i] = Integer.parseInt(components[i]);
} catch (Exception e) {
varIndex = i; //this component contains "H"
}
}
//Calculate the value of the number which has "H"
switch (varIndex) {
case 0:
result = nums[2] - nums[1]; break;
case 1:
result = nums[2] - nums[0]; break;
case 2:
result = nums[0] + nums[1]; break;
}
nums[varIndex] = result;
//Print the output
System.out.println(nums[0] + " + " + nums[1] + " = " + nums[2]);
System.out.println("H = " + (String.valueOf(result)).charAt(components[varIndex].indexOf('H')));
}

Try below program , This works only for input a+b=c format
Below program is giving correct output
import java.util.Scanner;
public class Hole {
public static void main(String args[])
{
int hLocation = 0;
int result;
char hValue;
Scanner in=new Scanner(System.in);
String str=in.nextLine().replaceAll(" ", "");
String[] split= str.split("[+=]");
for(int i=0;i<split.length;i++){
if(split[i].contains("H")){
hLocation=i;
}
}
if(hLocation==0){
result=Integer.parseInt(split[2])-Integer.parseInt(split[1]);
}else if(hLocation==1){
result=Integer.parseInt(split[2])-Integer.parseInt(split[0]);
}
else{
result=Integer.parseInt(split[0])+Integer.parseInt(split[1]);
}
hValue= String.valueOf(result).charAt(1);
str=str.replace('H', hValue);
System.out.println(str);
}
}

Try this:
public static void main(String[] args)
{
Scanner reader = new Scanner(System.in);
int[] nums = new int[3];
boolean[] isNum = new boolean[3];
String str = reader.nextLine();
// String str_1= str.replaceAll("=","+");
String[] split = str.split("[+=]");
int i = 0;
for (int k = 0; k < split.length; k++) {
try {
String s = split[k];
isNum[k] = true;
nums[i] = Integer.parseInt(s);i++;
} catch (NumberFormatException e) {
// TODO: handle exception
isNum[k] = false;
}
}
int tot ;
if(str.indexOf("H")>str.indexOf("=")){
tot = nums[1] + nums[0];
}else{
tot = nums[1] - nums[0];
}
for (int k = 0; k < split.length; k++) {
if(!isNum[k]){
int indx = split[k].indexOf("H");
String h = Integer.toString(tot).charAt(indx)+"";
h = str.replace("H",h);
System.out.println("New expression :"+h);
}
}
}

Related

What is wrong with this swapping program in Java, why and what should I do?

I am making a multiple string input random swap without using a temp variable.
But when I input, this happens a few times:
This happens more frequently... (note that the first output is always null and some outputs occasionally repeat)
My code:
import java.util.Arrays;
import java.util.Scanner;
public class myFile {
public static boolean contains(int[] array, int key) {
Arrays.sort(array);
return Arrays.binarySearch(array, key) >= 0;
}
public static void println(Object line) {
System.out.println(line);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String finalText = "";
String[] input = new String[5];
String[] swappedInput = new String[input.length];
int[] usedIndex = new int[input.length];
int swapCounter = input.length, useCounter;
for (int inputCounter = 0; inputCounter < input.length; inputCounter++) { //input
println("Enter input 1 " + (inputCounter + 1) + ": ");
input[inputCounter] = in.nextLine();
}
while (--swapCounter > 0) {
do{
useCounter = (int) Math.floor(Math.random() * input.length);
}
while (contains(usedIndex, useCounter));
swappedInput[swapCounter] = input[swapCounter].concat("#" + input[useCounter]);
swappedInput[useCounter] = swappedInput[swapCounter].split("#")[0];
swappedInput[swapCounter] = swappedInput[swapCounter].split("#")[1];
usedIndex[useCounter] = useCounter;
}
for (int outputCounter = 0; outputCounter < input.length; outputCounter++) {
finalText = finalText + swappedInput[outputCounter] + " ";
}
println("The swapped inputs are: " + finalText + ".");
}
}
Because of randomality some times useCounter is the same as swapCounter and now look at those lines (assume useCounter and swapCounter are the same)
swappedInput[swapCounter] = input[swapCounter].concat("#" + input[useCounter]);
swappedInput[useCounter] = swappedInput[swapCounter].split("#")[0];
swappedInput[swapCounter] = swappedInput[swapCounter].split("#")[1];
In the second line you are changing the value of xxx#www to be www so in the third line when doing split you dont get an array with two values you get an empty result thats why exception is thrown in addition you should not use swappedInput because it beats the pourpuse (if i understand correctly yoush shoud not use temp values while you are using addition array which is worse) the correct sollution is to only use input array here is the solution
public class myFile {
public static boolean contains(int[] array, int key) {
Arrays.sort(array);
return Arrays.binarySearch(array, key) >= 0;
}
public static void println(Object line) {
System.out.println(line);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String finalText = "";
String[] input = new String[5];
int[] usedIndex = new int[input.length];
int swapCounter = input.length, useCounter;
for (int inputCounter = 0; inputCounter < input.length; inputCounter++) { //input
println("Enter input 1 " + (inputCounter + 1) + ": ");
input[inputCounter] = in.nextLine();
}
while (--swapCounter >= 0) {
do {
useCounter = (int) Math.floor(Math.random() * input.length);
}
while (contains(usedIndex, useCounter));
// Skip if results are the same
if (useCounter == swapCounter) {
swapCounter++;
continue;
}
input[swapCounter] = input[swapCounter].concat("#" + input[useCounter]);
input[useCounter] = input[swapCounter].split("#")[0];
input[swapCounter] = input[swapCounter].split("#")[1];
usedIndex[useCounter] = useCounter;
}
for (int outputCounter = 0; outputCounter < input.length; outputCounter++) {
finalText = finalText + input[outputCounter] + " ";
}
println("The swapped inputs are: " + finalText + ".");
}
}

Java - NumberFormatException when using .parseInt(String)

I am trying to run a loop to see if an int is sorted. however the int has to be converted from a string. here is my code.
public static void main(String[] args) {
// TODO code application logic here
Scanner maxVal = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
System.out.println("enter the max value of ordered squares:");
int max = maxVal.nextInt();
for(int i = 0; i*i <= max; i++){
int L = String.valueOf(i*i).length();
String sq = String.valueOf(i*i);
String [] digits = new String[L];
for(int a = 0; a < L; a++){
digits [a] = Character.toString(sq.charAt(a));
if(L == 1){
System.out.print(sq + "");
}else if(Integer.parseInt(digits [a]) < Integer.parseInt(digits[a+1])){
System.out.print(sq);
}else{
}
}
}
}
when I run it, I get an error :
Exception in thread "main" java.lang.NumberFormatException: null
0149 at java.lang.Integer.parseInt(Integer.java:542)
at java.lang.Integer.parseInt(Integer.java:615)
why does Integer.parseInt() not work
Your problem is that digits[a+1] hasn't been defined yet. I see that on line 2 you have
digits[a] = Character.toString(sq.charAt(a));
and you're iterating over a in a for loop, so I daresay that digits[a+1] hasn't been assigned yet.
UPDATE 1
Check out this solution, it shows how to properly catch that exception and how to avoid it:
Java: Good way to encapsulate Integer.parseInt()
UPDATE 2
I decided to add a fixed version of your code:
public static void main(String[] args) {
// TODO code application logic here
Scanner maxVal = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
System.out.println("enter the max value of ordered squares:");
int max = maxVal.nextInt();
for(int i = 0; i*i <= max; i++){
int L = String.valueOf(i*i).length();
String sq = String.valueOf(i*i);
String [] digits = new String[L];
for(int a = 0; a < L; a++){
digits [a] = Character.toString(sq.charAt(a));
if(L == 1 || a == 0){
System.out.print(sq + "");
}else if(Integer.parseInt(digits [a]) < Integer.parseInt(digits[a+1])){
System.out.print(sq);
}else{
}
}
}
}
While I don't know the utility of your code, but this implementation might be simpler:
public static void main(String[] args) {
// TODO code application logic here
Scanner maxVal = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
System.out.println("enter the max value of ordered squares:");
int max = maxVal.nextInt();
for(int i = 0; i*i <= max; i++){
long sq = i*i;
if(sq > 9){
String[] digits = sq.toString().split("");
//Notice that I start at index 1, so I can do [a-1] safely
for(int a = 1; a < digits.length; a++){
if(Integer.parseInt(digits [a-1]) < Integer.parseInt(digits[a])){
System.out.print(sq);
//I guess we don't want a number like 169 (13*13) to be displayed twice, so:
break;
}
}
} else {
System.out.print(sq);
}
}
}

Count Occurrence of each letter in a loop and display with letter with the most number of occurences

I'm having trouble in using this code I found on the net. my goal is to count the number of times a letter show and display the letter with the most occurrence and if there are 2 or more letters that occurred at the same number of times then they will both show up.
This is my current output:
Current Output
Here is the code i found on the net and working with:
public void fcount(String str)
{
int[] occurence = new int[255];
// Scanner scanner = new Scanner(System.in);
// str = scanner.nextLine();
// optional to put eveyting in uppercase
str = str.toUpperCase();
// convert to char
char[] digit = str.toCharArray();
// count
for(int i = 0; i < digit.length; i++)
occurence[digit[i]]++;
// find max
int max = 0; // max value
char maxValue = 0; // max index
for(int i = 0; i < occurence.length; i++)
{
// new max ?
if(occurence[i] > max) {
max = occurence[i];
maxValue = (char) i;
}
}
// result
System.out.println("Character used " + max + " times is: " + (char) maxValue);
// return "";
}
And Here is the the loop where i'm using it:
public void calpha()
{
char startUpper = 'A';
String cones = null;
for (int i = 0; i < 12; i++) {
cones = Character.toString(startUpper);
System.out.println(startUpper);
}
fcount(cones);
}
There is an error in you loop:
cones = Character.toString(startUpper);
You are just re-assigning the value of cones, so fcount receives a string containing only the last character.
A solution is
cones += Character.toString(startUpper);
You have an issue in your int[] occurence = new int[255]; statement and usage: occurence[digit[i]]++ may lead to IndexOutOfBoundsException since char type is up to 2^16
Your code can not deal with non-ANSII characters. Mine does.
import java.util.*;
class Problem {
public static void main(String args[]) {
final String input = "I see trees outside of my window.".replace(" ", "");
final List<Character> chars = new ArrayList<>(input.length());
for (final char c : input.toCharArray()) {
chars.add(c);
}
int maxFreq = 0;
final Set<Character> mostFrequentChars = new HashSet<>();
for(final char c : chars) {
final int freq = Collections.frequency(chars, c);
if (freq > maxFreq) {
mostFrequentChars.clear();
mostFrequentChars.add(c);
maxFreq = freq;
}
else {
if (freq == maxFreq) {
mostFrequentChars.add(c);
}
}
}
for (Character c : mostFrequentChars) {
System.out.println(c);
}
}
}
Try this code:
public static void main(String[] args) throws IOException {
char startUpper = 'A';
String cones = "";
for (int i = 0; i < 12; i++) {
cones += Character.toString(startUpper);
System.out.println(startUpper);
}
fcount(cones);
}
public static void fcount(String str) {
HashMap<Character, Integer> hashMap = new HashMap<Character, Integer>();
HashSet<Character> letters = new HashSet<Character>();
str = str.toUpperCase();
//Assume that string str minimium has 1 char
int max = 1;
for (int i = 0; i < str.length(); i++) {
int newValue = 1;
if (hashMap.containsKey(str.charAt(i))) {
newValue = hashMap.get(str.charAt(i)) + 1;
hashMap.put(str.charAt(i), newValue);
if (newValue>=max) {
max = newValue;
letters.add(str.charAt(i));
}
} else {
hashMap.put(str.charAt(i), newValue);
}
}
System.out.println("Character used " + max + " times is: " + Arrays.toString(letters.toArray()));
// return "";
}

Java words reverse

I am new to Java and I found a interesting problem which I wanted to solve. I am trying to code a program that reverses the position of each word of a string. For example, the input string = "HERE AM I", the output string will be "I AM HERE". I have got into it, but it's not working out for me. Could anyone kindly point out the error, and how to fix it, because I am really curious to know what's going wrong. Thanks!
import java.util.Scanner;
public class Count{
static Scanner sc = new Scanner(System.in);
static String in = ""; static String ar[];
void accept(){
System.out.println("Enter the string: ");
in = sc.nextLine();
}
void intArray(int words){
ar = new String[words];
}
static int Words(String in){
in = in.trim(); //Rm space
int wc = 1;
char c;
for (int i = 0; i<in.length()-1;i++){
if (in.charAt(i)==' '&&in.charAt(i+1)!=' ') wc++;
}
return wc;
}
void generate(){
char c; String w = ""; int n = 0;
for (int i = 0; i<in.length(); i++){
c = in.charAt(i);
if (c!=' '){
w += c;
}
else {
ar[n] = w; n++;
}
}
}
void printOut(){
String finale = "";
for (int i = ar.length-1; i>=0;i--){
finale = finale + (ar[i]);
}
System.out.println("Reversed words: " + finale);
}
public static void main(String[] args){
Count a = new Count();
a.accept();
int words = Words(in);
a.intArray(words);
a.generate();
a.printOut();
}
}
Got it. Here is my code that implements split and reverse from scratch.
The split function is implemented through iterating through the string, and keeping track of start and end indexes. Once one of the indexes in the string is equivalent to a " ", the program sets the end index to the element behind the space, and adds the previous substring to an ArrayList, then creating a new start index to begin with.
Reverse is very straightforward - you simply iterate from the end of the string to the first element of the string.
Example:
Input: df gf sd
Output: sd gf df
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
public class Count{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter string to reverse: ");
String unreversed = scan.nextLine();
System.out.println("Reversed String: " + reverse(unreversed));
}
public static String reverse(String unreversed)
{
ArrayList<String> parts = new ArrayList<String>();
String reversed = "";
int start = 0;
int end = 0;
for (int i = 0; i < unreversed.length(); i++)
{
if (unreversed.charAt(i) == ' ')
{
end = i;
parts.add(unreversed.substring(start, end));
start = i + 1;
}
}
parts.add(unreversed.substring(start, unreversed.length()));
for (int i = parts.size()-1; i >= 0; i--)
{
reversed += parts.get(i);
reversed += " ";
}
return reversed;
}
}
There is my suggestion :
String s = " HERE AM I ";
s = s.trim();
int j = s.length() - 1;
int index = 0;
StringBuilder builder = new StringBuilder();
for (int i = j; i >= 0; i--) {
Character c = s.charAt(i);
if (c.isWhitespace(c)) {
index = i;
String r = s.substring(index+1, j+1);
j = index - 1;
builder.append(r);
builder.append(" ");
}
}
String r=s.substring(0, index);
builder.append(r);
System.out.println(builder.toString());
From adding debug output between each method call it's easy to determine that you're successfully reading the input, counting the words, and initializing the array. That means that the problem is in generate().
Problem 1 in generate() (why "HERE" is duplicated in the output): after you add w to your array (when the word is complete) you don't reset w to "", meaning every word has the previous word(s) prepended to it. This is easily seen by adding debug output (or using a debugger) to print the state of ar and w each iteration of the loop.
Problem 2 in generate() (why "I" isn't in the output): there isn't a trailing space in the string, so the condition that adds a word to the array is never met for the last word before the loop terminates at the end of the string. The easy fix is to just add ar[n] = w; after the end of the loop to cover the last word.
I would use the split function and then print from the end of the list to the front.
String[] splitString = str.split(" ");
for(int i = splitString.length() - 1; i >= 0; i--){
System.out.print(splitString[i]);
if(i != 0) System.out.print(' ');
}
Oops read your comment. Disregard this if it is not what you want.
This has a function that does the same as split, but not the predefined split function
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the string : ");
String input = sc.nextLine();
// This splits the string into array of words separated with " "
String arr[] = myOwnSplit(input.trim(), ' '); // ["I", "AM", "HERE"]
// This ll contain the reverse string
String rev = "";
// Reading the array from the back
for(int i = (arr.length - 1) ; i >= 0 ; i --) {
// putting the words into the reverse string with a space to it's end
rev += (arr[i] + " ");
}
// Getting rid of the last extra space
rev.trim();
System.out.println("The reverse of the given string is : " + rev);
}
// The is my own version of the split function
public static String[] myOwnSplit(String str, char regex) {
char[] arr = str.toCharArray();
ArrayList<String> spltedArrayList = new ArrayList<String>();
String word = "";
// splitting the string based on the regex and bulding an arraylist
for(int i = 0 ; i < arr.length ; i ++) {
char c = arr[i];
if(c == regex) {
spltedArrayList.add(word);
word = "";
} else {
word += c;
}
if(i == (arr.length - 1)) {
spltedArrayList.add(word);
}
}
String[] splitedArray = new String[spltedArrayList.size()];
// Converting the arraylist to string array
for(int i = 0 ; i < spltedArrayList.size() ; i++) {
splitedArray[i] = spltedArrayList.get(i);
}
return splitedArray;
}

Parsing individual letters from string in JAVA

I've almost got it except when I run the program it parses all but the first letter of the string Hello World: "e l l o w o r l d." Heres my code; what am I missing?
import java.util.Scanner;
public class encodeTesting {
public static void main(String []Args){
//Scanner scan = new Scanner (System.in);
String x = "Hello World "; //TEST STRING
//System.out.println(x.length()); //Console log test
char[] y = new char[x.length()]; // Array Y
//Defining Variables:
int i;
int z = 0;
int a = 1;
while(a<x.length()){ //should repeat as many times as needed to parse String X
//Parse Algorithm follows:
y[z] = x.charAt(x.length() - a);
System.out.println(y[z]);
z = z + 1;
a = a + 1;
}
}
public static void main(String[] Args) {
String x = "Hello World ";
char[] y = new char[x.length()];
int i;
int z = 0;
int a = 1;
while (a <= x.length()) {
y[z] = x.charAt(x.length() - a);
System.out.println(y[z]);
z = z + 1;
a = a + 1;
}
}
You need to use:
while (a <=x.length())
So that when x.charAt(x.length() - a); evaluates at x.charAt(0); getting the first character of the string.
You could make this simple and do a basic for loop.
public static void main(String[] Args){
String x = "Hello World ";
int length = x.length();
char[] y = new char[length];
for(int i = 0; i < length; i++){
y[i] = x.charAt(length - i - 1);
System.out.println(y[i]);
}
}
If you want to do something for each character in your string, this is the way to do it:
public static void main (String[] args){
String test = "Hello world";
for(char c: test.toCharArray()) {
//do your operations here
System.out.print(c);
}
}
//Output: Hello World
Read the for-loop as "for each character in test"
By the looks of it you just want to convert your string to a character array, in which case just use this:
String myStringVariable = "abc";
char[] stringAsArray = myStringVariable.toCharArray();
Or you can even do it like this:
char[] stringAsArray = "Hello world".toCharArray();

Categories