Output of numbers are incorrect sometimes. - java

This is my task, Given an input of an expression consisting of a string of letters and operators (plus sign, minus sign, and letters. IE: ‘b-d+e-f’) and a file with a set of variable/value pairs separated by commas (i.e: a=1,b=7,c=3,d=14) write a program that would output the result of the inputted expression.
For example, if the expression input was ("a + b+c -d") and the file input was ( a=1,b=7,c=3,d=14) the output would be -3.
Hi I am trying to do a simple java code which outputs a number if i add 4 letters. When I do different combinations like d-c+a+b it gives me a inccorect number like 118.0. Can someone tell me where in my code my calculations are wrong..
Thank you
the ValVarPairs.txt contains these numbers-> a=100,b=5,c=10,d=13
This is what i coded.
package com.ecsgrid;
import java.io.*;
public class testC {
public static void main(String[] args) {
int i = 0,j = 0;
double result, values[] = new double[4];
char k, operators[] = new char[3];
for (i = 0; i <= 2; i++)
operators[i] = '+'; // default is to add the values
File myfile;
StreamTokenizer tok;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String InputText;
i = 0;
try {
myfile = new File("C:\\VarValPairs.txt");
tok = new StreamTokenizer(new FileReader(myfile));
tok.eolIsSignificant(false);
while ((tok.nextToken() != StreamTokenizer.TT_EOF) && (i <= 3)){
if ((tok.ttype == StreamTokenizer.TT_NUMBER))
values[i++] = tok.nval;
}
}
catch(FileNotFoundException e) { System.err.println(e); return; }
catch(IOException f) { System.out.println(f); return; }
System.out.println("Enter letters and operators:");
try {
InputText = in.readLine();
}
catch(IOException f) { System.out.println(f); return; }
for (i = 0; i < InputText.length(); i++)
{
k = InputText.charAt(i);
if ((k == '+') || (k == '-'))
{
if (j <= 2) operators[j++] = k;
}
}
result = values[0];
for (i = 0; i <= 2; i++){
if (operators[i] == '+')
result = result + values[i+1];
else
result = result - values[i+1];
}
System.out.println(result);
}
}

I'm not sure where your calculations are wrong, but you could do something like this:
EDITED CODE:
import java.io.*;
import java.util.*;
public class test{
public static int a;
public static int b;
public static int c;
public static int d;
public static int fin = 0;
public static String temp;
public static void main(String[] args){
try{
Scanner input = new Scanner(new File("yourfile.txt"));
temp = "";
while(input.hasNext()){ //stores the letters
temp = temp + input.next();
}
input.close();
}
catch(Exception e){
}
/*
THIS IS IF THE FILE yourfile.txt IS IN THIS FORMAT EXACTLY:
a=1
b=2
c=3
d=4
*/
for(int i = 0; i < temp.length(); i++){ //intitializes the values
String message = "" + temp.charAt(i);
if(message.equals("a") || message.equals("b") || message.equals("c") || message.equals("d")){
String val = "" + temp.charAt(i+2);
setValue(message,val);
}
}
Scanner enter = new Scanner(System.in);
System.out.print("ENTER EXPRESSION: ");
String ex = enter.nextLine();
for(int b = 0; b < ex.length(); b++){
String m = ""+ ex.charAt(b);
if(b == 0){
if(m.equals("a") || m.equals("b") || m.equals("c") || m.equals("d")){
fin = fin + getValue(m);
}
}
else{
if(m.equals("a") || m.equals("b") || m.equals("c") || m.equals("d")){
String check = "" + ex.charAt(b-1);
if(check.equals("+")){
fin = fin + getValue(m);
}
if(check.equals("-")){
fin = fin - getValue(m);
}
}
}
}
System.out.println(fin);
}
public static void setValue(String variable, String value){
if(variable.equals("a")){
a = Integer.parseInt(value);
}
if(variable.equals("b")){
b = Integer.parseInt(value);
}
if(variable.equals("c")){
c = Integer.parseInt(value);
}
if(variable.equals("d")){
d = Integer.parseInt(value);
}
}
public static int ret = 0;
public static int getValue(String var){
if(var.equals("a")){
ret = a;
}
if(var.equals("b")){
ret = b;
}
if(var.equals("c")){
ret = c;
}
if(var.equals("d")){
ret = d;
}
return ret;
}
}
There are some problems in your code where you use "==" instead of .equals()

Related

Reverse encoded string

i am asking for help on how i would go about reversing my code so that the input 'A2B5C2' will give me the output 'AABBBBBCC', any suggestions?
Thanks
public static void printRLE(String str) {
int n = str.length();
for (int i = 0; i < n; i++) {
// Count occurrences of current character
int count = 1;
while (i < n - 1 && str.charAt(i) == str.charAt(i + 1)) {
count++;
i++;
}
// Print character and its count
System.out.print(str.charAt(i));
System.out.print(count);
}
}
public static void main(String[] args) {
String str = "AABBBBBCC";
printRLE(str);
}
To get the case, the number will more than 9, I'd suggest a simple regex to match letter+number, then just repeat the letter the number of times you need :
static String getRevRLE(String str) {
StringBuilder res = new StringBuilder();
Matcher m = Pattern.compile("([a-zA-Z][0-9]+)").matcher(str);
while (m.find()) {
String g = m.group();
res.append(g.substring(0, 1).repeat(Integer.parseInt(g.substring(1))));
}
return res.toString();
}
Using the Streams API you can reduce to
static String getRevRLE(String str) {
return Pattern.compile("([a-zA-Z][0-9]+)").matcher(str).results()
.map(MatchResult::group)
.map(g -> g.substring(0, 1).repeat(Integer.parseInt(g.substring(1))))
.collect(Collectors.joining());
}
Testing
public static void main(String[] args) {
String str = "AABBBBBCCCCCCCCCCCCCCCCCCCC";
String rle = getRLE(str);
String res = getRevRLE(rle);
System.out.println(res + " " + res.equals(str)); // AABBBBBCCCCCCCCCCCCCCCCCCCC true
}
Here you go:
public static String encode(String input) {
String output = "";
while (true) {
char c = input.charAt(0);
String countStr = "";
char current;
for (int i = 1; i < input.length() && Character.isDigit(current = input.charAt(i)); i++)
countStr += current;
int count = Integer.parseInt(countStr);
for (int i = 0; i < count; i++)
output += c;
int trimLength = 1 + countStr.length();
if (trimLength >= input.length())
return output;
else
input = input.substring(trimLength);
}
}
You can do this task like this:
public static String printRLE(String str) {
int n = str.length();
String result = "";
for (int i = 0; i < n - 1; i++) {
char ch = str.charAt(i);
if (!Character.isDigit(ch)) {
if (Character.isDigit(str.charAt(i + 1))) {
int fi = i + 1;
i += 2;
while (i < n && Character.isDigit(str.charAt(i))) i++;
int repeat = Integer.parseInt(str.substring(fi, i));
result += String.valueOf(ch).repeat(repeat);
i--;
} else result += ch;
}
}
return result;
}
public static void main(String[] args) {
String str = "10A10B32C1";
System.out.println(printRLE(str));
}
, output
AAAAAAAAAABBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBC

Multiplication of two Binary Numbers given as Strings

so I have a code that should multiplicate two Binary Numbers as String without using ParseInt. My code actually works by far but it's multiplicating as decimal numbers. Something in the part where it should do the addition is wrong.
Thanks for any kind of help!
public static String multiply(String binary1, String binary2)
String b1 = new StringBuilder(binary1).reverse().toString();
String b2 = new StringBuilder(binary2).reverse().toString();
int[] m = new int[binary1.length()+binary2.length()];
for (int i = 0; i < binary1.length(); i++) {
for (int j = 0; j < binary2.length(); j++) {
m[i+j] += (b1.charAt(i)-'0')*(b2.charAt(j)-'0');
}
}
StringBuilder sb = new StringBuilder();
for(int i=0; i < m.length; i++) {
int mod = m[i]%10;
int carry = m[i]/10;
if (i+1 < m.length) {
m[i + 1] = m[i + 1] + carry;
}
sb.insert(0, mod);
}
// delete leading zeros
while (sb.charAt(0) == '0' && sb.length() > 1) {
sb.deleteCharAt(0);
}
return sb.toString();
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("1. Faktor: ");
String input1 = scan.next("(0|1)*");
System.out.print("2. Faktor: ");
String input2 = scan.next("(0|1)*");
scan.close();
System.out.println("Ergebnis: " + multiply(input1, input2));
}
}
You may not use Integer.parseInt but nobody forbid you to implement your own parser:
private static int parseBinaryString(String s) {
int binary = 0;
for (int i = s.length() - 1, c; i >= 0; i--) {
binary <<= 1;
c = s.charAt(i);
if (c == '1') {
binary++;
} else if (c != '0') {
throw new NumberFormatException(s);
}
}
return binary;
}
Which can then be simply used like this in your multiply method:
private static String multiply(String a, String b) {
return Integer.toBinaryString(parseBinaryString(a) * parseBinaryString(b));
}
And if you can't use Integer.toBinaryString you can implement that method yourself:
private static String toBinaryString(int i) {
StringBuilder binary = new StringBuilder();
for (int t = i; t != 0; t >>= 1) {
binary.append((i & t) != 0 ? 1 : 0);
}
return binary.toString();
}

The requirement is, the output will print one number followed by a character then a number and so on

I have am assignment suppose there is a string 11234aBcD the out put should be 1a1B2c3D4 and I am unable to do it, First and the second output I have done. And I have to do using java.
I am adding my code:
package Testx;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
public class Test3optmz {
public static void main(String[] args)
{
// TODO Auto-generated method stub
Scanner gaba = new Scanner( System.in );
String variable;
System.out.print("Enter String:");
variable = gaba.nextLine();
SeparateGaba(variable);
}
public static void SeparateGaba(String str)
{
String Catch_num = "";
String Catch_let = "";
String upper="";
String lower="";
String holdl="";
String holdn="";
for (int i = 0; i < str.length(); i++)
{
char a = str.charAt(i);
if (Character.isDigit(a))
{
Catch_num = Catch_num + a;
} else
{
Catch_let = Catch_let + a;
}
}
System.out.println("FIRST OUTPUT:"+Catch_num+Catch_let);// i am separating the numbers and alphabets
for(int j=0;j <Catch_let.length();j++)
{
char x = Catch_let.charAt(j);
if (Character.isUpperCase(x))
{
upper += x;
}
else
{
lower += x;
}
}
char[] num = Catch_num.toCharArray();
Arrays.sort(num);
String n =new String(num);
char[] ordr = lower.toCharArray();
Arrays.sort(ordr);
String alfa1 =new String(ordr);
char[] ord = upper.toCharArray();
Arrays.sort(ord);
String alfa =new String(ord);
String t= alfa1 + alfa;
char [] fin = t.toCharArray();
Arrays.sort(fin);
String fal = new String(fin);
Character[] chars = new Character[fal.length()];
for (int f=0; f < fal.length();f++)
chars[f] = fal.charAt(f);
Arrays.sort(chars, new Comparator<Character>()
{
public int compare(Character c1, Character c2)
{
int cmp = Character.compare(
Character.toLowerCase(c1.charValue()),
Character.toLowerCase(c2.charValue())
);
if (cmp != 0) return cmp;
return Character.compare(c1.charValue(), c2.charValue());
}
});
StringBuilder sb = new StringBuilder(chars.length);
for (char c : chars) sb.append(c);
fal = sb.toString();
System.out.println("SECOND OUTPUT= "+n+fal);// now i am arranging the alphabet in ascending order avoiding capital and small ex 1234eBaC it will come as 1234aBce
}
}
well thanks for not helping me out i helped my self
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
public class Test4 {
public static void main(String[] args)
{
// TODO Auto-generated method stub
Scanner gaba = new Scanner( System.in );
String variable;
System.out.print("Enter String:");
variable = gaba.nextLine();
SeparateGaba(variable);
}
public static void SeparateGaba(String str)
{
String Catch_num = "";
String Catch_let = "";
String upper="";
String lower="";
for (int i = 0; i < str.length(); i++)
{
char a = str.charAt(i);
if (Character.isDigit(a))
{
Catch_num = Catch_num + a;
} else
{
Catch_let = Catch_let + a;
}
}
System.out.println("FIRST OUTPUT:"+Catch_num+Catch_let);
for(int j=0;j <Catch_let.length();j++)
{
char x = Catch_let.charAt(j);
if (Character.isUpperCase(x))
{
upper += x;
}
else
{
lower += x;
}
}
char[] num = Catch_num.toCharArray();
Arrays.sort(num);
String n =new String(num);
char[] ordr = lower.toCharArray();
Arrays.sort(ordr);
String alfa1 =new String(ordr);
char[] ord = upper.toCharArray();
Arrays.sort(ord);
String alfa =new String(ord);
String t= alfa1 + alfa;
char [] fin = t.toCharArray();
Arrays.sort(fin);
String fal = new String(fin);
Character[] chars = new Character[fal.length()];
for (int f=0; f < fal.length();f++)
chars[f] = fal.charAt(f);
Arrays.sort(chars, new Comparator<Character>()
{
public int compare(Character c1, Character c2)
{
int cmp = Character.compare(
Character.toLowerCase(c1.charValue()),
Character.toLowerCase(c2.charValue())
);
if (cmp != 0) return cmp;
return Character.compare(c1.charValue(), c2.charValue());
}
});
StringBuilder sb = new StringBuilder(chars.length);
for (char c : chars) sb.append(c);
fal = sb.toString();
System.out.println("SECOND OUTPUT= "+n+fal);
/*GABA come on let seeeeeeeee*/
try
{
for(int i=0;i<n.length();i++)
{
char a= n.charAt(i);
System.out.print(a);
for(int j=0; j<fal.length();j++)//1
{
char b = fal.charAt(j);
if(j>=i)
{
System.out.print(b);
break;
}
}
}
}
catch(Exception e)
{
System.out.println("Your letter length should match with char len");
}
}
}
Enter String:14a5Bc
FIRST OUTPUT:145aBc
SECOND OUTPUT= 145aBc
THE out put i was looking for --->1a4B5c

Adding Binary Numbers in JAVA. NumberFormatException

The problem is when I enter a decimal input. For example 10001.10.
It says NumberFormatException. But when I input just a number without decimal like "1001110" its works fine.
import java.util.*;
import java.util.Arrays;
public class Binary {
public static void main (String[] args)
{
Scanner in = new Scanner(System.in);
String[] Condition = { "0", "1", "." };
//Accept First Input
String numInp1="";
System.out.print("Enter First Binary Number: ");
numInp1 = in.nextLine();
//Accept Second Input
String numInp2="";
System.out.print("Enter Second Binary Number: ");
numInp2 = in.nextLine();
//numInp1
String _Array1 []=new String[numInp1.length()];
//numInp2
String _Array2 []=new String[numInp2.length()];
//Catch error in numInp1/_Array1
boolean flag1 = false;
for(int i = 0; i < _Array1.length; i++)
{
_Array1[i] = String.valueOf(numInp1.charAt(i));
int cnt = 0;
for (int j = 0; j < Condition.length; j++)
{
if (!_Array1[i].equals(Condition[j]))
{
cnt++;
}
else
{
break;
}
if (cnt == 3)
{
flag1 = true;
}
}
}
//Catch error in numInp2//_Array2
boolean flag2 = false;
for(int i = 0; i < _Array2.length; i++)
{
_Array2[i] = String.valueOf(numInp2.charAt(i));
int cnt = 0;
for (int j = 0; j < Condition.length; j++)
{
if (!_Array2[i].equals(Condition[j]))
{
cnt++;
}
else
{
break;
}
if (cnt == 3)
{
flag2 = true;
}
}
}
//Getting which of the Array has Higher Input
if(flag2 == false && flag1 == false)
{
int HigherLength = 0;
if(_Array1.length >= _Array2.length)
{
HigherLength = _Array1.length + _Array2.length;
}
else
{
HigherLength = _Array2.length + _Array1.length;
}
//Declaring the size of higher length as the size of Equals[] Array
int Equals[] = new int[HigherLength];
int _Array1Int[] = new int[_Array1.length];
int _Array2Int[] = new int[_Array2.length];
for(int i = 0;i<_Array1.length;i++)
{
if(_Array1[i].equals("."))
{
_Array1[i] = "6";
}
_Array1Int[i] = Integer.parseInt(_Array1[i]);
}
for(int i = 0;i<_Array2.length;i++)
{
if(_Array2[i].equals("."))
{
_Array2[i] = "6";
}
_Array2Int[i] = Integer.parseInt(_Array2[i]);
}
//_________________________
int numInp1int = Integer.parseInt(numInp1);
int numInp2int = Integer.parseInt(numInp2);
int i,m,n,sum,carry=0;
for(i=Equals.length-1;i>=0;i--)
{
m=numInp1int%10;
n=numInp2int%10;
numInp1int=numInp1int/10;
numInp2int=numInp2int/10;
sum=m+n+carry;
if(sum==1)
{
Equals[i]=1;
carry=0;
}
else if(sum==2)
{
Equals[i]=0;
carry=1;
}
else if(sum==3)
{
Equals[i]=1;
carry=1;
}
else
{
Equals[i]=m+n+carry;
}
}
String Equals1[] = new String[Equals.length];
for(i=0;i<Equals.length;i++)
{
try{
Equals1[i] = String.valueOf(Equals[i]);
}
catch (NumberFormatException nfe)
{
nfe.printStackTrace();
}
if (Equals1[i].equals("6"))
{
Equals1[i] = ".";
}
System.out.print(Equals1[i]);
}
}
}
}
Do below changes in your code
Remove below 2 lines-
int numInp1int = Integer.parseInt(numInp1);
int numInp2int = Integer.parseInt(numInp2);
Replace with below code -
StringBuilder strNum1 = new StringBuilder();
for (int num : _Array1Int)
{
strNum1.append(num);
}
int numInp1int = Integer.parseInt(strNum1.toString());
StringBuilder strNum2 = new StringBuilder();
for (int num : _Array2Int)
{
strNum2.append(num);
}
int numInp2int = Integer.parseInt(strNum2.toString());
Updating _Array1 and _Array2 does not change numInp1int and numInp2int which you are trying to parse as Integer.
You should learn to interpret error messages in the stack trace. Here you can clearly see where the problem is:
Exception in thread "main" java.lang.NumberFormatException: For input string: "10001.1"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at q35640801.Binary.main(Binary.java:120)
It's in the call parseInt() of class Integer. It cannot parse decimal numbers like 10001.10

Find non-repeated character in a string

I have to create a program for returning the next non-repeated character..
ex I give ... tweet
and it should return output as w...
public class str_next {
public static void main(String args[]) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the string");
String s = br.readLine();
revString(s);
}
static char revString(String str) {
int i = 0;
int j;
int n = str.length();
for (i = 0; i < n; i++) {
for (j = i + 1; j < n; j++) {
char c = str.charAt(i);
char d = str.charAt(j);
if (c != d) {
System.out.print(d);
}
}
}
}
}
I am getting error as .. missing return statement..
Can anyone please tell me.. How do I solve such a problem.. Where am I wrong..?
To solve your problem simply add,
return d;
in your function. But it's better to understand how this actually works:
Functions/Methods are written as
accessor_type return_type function_name(parameter_list)
{
//stuff to do in your code
}
For e.g.
public char returnChar(int a)
| | | |
| | | |
^ ^ ^ ^
accessor return name parameter
this means that this function will return a character.
In the sense, you need to a char like this in your function
return char;
Try reading up on methods and their return types. :)
References:
Defining Methods
Return a value from a method
you have not written the return statement.Use return ;
You have written the return type for revString(String str) as char and you are not returning any character.
Change that return type to void
or add line return d; to the method
You have missing the return statement in your code.
here is the code which returns what you want
CODE
public static Character findFirstNonRepeated(String input) {
// create a new hashtable:
Hashtable<Character, Object> hashChar = new Hashtable<Character, Object>();
int j, strLength;
Character chr;
Object oneTime = new Object();
Object twoTimes = new Object();
strLength = input.length();
for (j = 0; j < strLength; j++) {
chr = new Character(input.charAt(j));
Object o = hashChar.get(chr);
/*
* if there is no entry for that particular character, then insert
* the oneTime flag:
*/
if (o == null) {
hashChar.put(chr, oneTime);
}
/*
*/
else if (o == oneTime) {
hashChar.put(chr, twoTimes);
}
}
/*
* go through hashtable and search for the first nonrepeated char:
*/
int length = strLength;
for (j = 0; j < length; j++) {
chr = new Character(input.charAt(j));
Object c = null;
if (hashChar.get(chr) == oneTime)
return chr;
}
/*
* this only returns null if the loop above doesn't find a nonrepeated
* character in the hashtable
*/
return null;
}
Use like this
char my = findFirstNonRepeated("twwwweety");
System.out.println(my);
This will return y.
Add each character to a HashSet and check whether hashset.add() returns true, if it returns false ,then remove the character from hashset. Then getting the first value of the hashset will give you the first non repeated character.
Algorithm:
for(i=0;i<str.length;i++)
{
HashSet hashSet=new HashSet<>()
if(!hashSet.add(str[i))
hashSet.remove(str[i])
}
hashset.get(0) will give the non repeated character.
Try this,
// Split the string into characters
// Check if entry exists in the HashMap, if yes- return the character, if No- inert the element with value 1
public static void main(String[] args) {
String s = "rep e atit";
char c = nonRepeat(s);
System.out.println("The first non repeated character is:" + c);
}
private static char nonRepeat(String ss) {
char c;
HashMap<Character, Integer> hm = new HashMap<Character, Integer>();
for (int i = 0; i < ss.length(); i++) {
c = ss.charAt(i); // get each chaar from string
if (hm.containsKey(c)) {// char is already in map, increase count
hm.put(c, hm.get(c) + 1);
return c;
} else {
hm.put(c, 1);
}
}
return '0';
}
IN JAVA
using for loop only.....
it is very easy....you can do it without collection in java..
just try it.....
public class FirstNonRepeatedString{
public static void main(String args[]) {
String input = "tweet";
char process[] = input.toCharArray();
boolean status = false;
int index = 0;
for (int i = 0; i < process.length; i++) {
for (int j = 0; j < process.length; j++) {
if (i == j) {
continue;
} else {
if (process[i] == process[j]) {
status = false;
break;
} else {
status = true;
index = i;
}
}
}
if (status) {
System.out.println("First non-repeated string is : " + process[index] + " INDEX " + index);
break;
}
}
}
}
public class JavaPractice {
public static void main(String args[])
{
System.out.println("Enter input String");
Scanner s= new Scanner(System.in);
String input= s.nextLine();
int length=input.length();
for(int i=0;i<length;i++)
{
int temp=0;
for(int j=0;j<length;j++)
{
if(input.charAt(i)==input.charAt(j))
{temp++;}
}
if(temp==1)
{System.out.println(input.charAt(i));}
}
}
}
your program should be like this:
import java.io.*;
public class str_next {
public static void main(String args[]) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the string");
String s = br.readLine();
revString(s);
}
static char revString(String str) {
int i = 0;
int j;
int n = str.length();
for (i = 0; i < n; i++) {
for (j = i + 1; j < n; j++) {
char c = str.charAt(i);
char d = str.charAt(j);
if (c != d) {
System.out.print(d);
}
}
}
return 0;
}
}

Categories

Resources