Output incorrect [duplicate] - java

This question already has an answer here:
Output of numbers are incorrect sometimes.
(1 answer)
Closed 9 years ago.
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);
}
}

Right now you would be getting the same output if your input was -++
You never parse for the order or a, b, c and d. You always assume the order a->b->c->d.
So d-c+a+b will be: a-b+c+d which is consistent with the output you provided(100-5+10+13 = 118)
OP's CODE
for (i = 0; i < InputText.length(); i++)
{
k = InputText.charAt(i);
if ((k == '+') || (k == '-'))
{
if (j <= 2) operators[j++] = k;
}
}
/OP'S CODE
In this loop, when k is not an operator, you should be reading which letter it is, and store the order in which the letters appeared. Or build some other kind of mapping. In any case you can't just ignore non-operator characters because they are part of the input.

Let's debug this a little, add a few system outs...
this is what you would see for each step
100.0 - 5.0
95.0 + 10.0
105.0 + 13.0
118.0
your value array is {100,5,10,13} and your operator array is {-,+,+}
you have not mapped a = 100, b = 5, c= 10, d = 13, unless you map those then parse the operands using the mapping based on the non operand input keys, it is not going to work.
So, if I were to use the character's int values, I would be able to translate it this way.
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, operatorsAndOperands[] = new char[3];
for (i = 0; i <= 2; i++)
operatorsAndOperands[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;
}
for (int l = 0; l < values.length; l++) {
System.out.println(values[l]);
}
} 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().toUpperCase();
} catch (IOException f) {
System.out.println(f);
return;
}
if(InputText.length() > 0){
operatorsAndOperands = new char[InputText.length()];
} else {
System.out.println("No Operations specified");
return;
}
for (i = 0; i < InputText.length(); i++) {
k = InputText.charAt(i);
operatorsAndOperands[j++] = k;
}
result = 0;
for (i = 0; i < operatorsAndOperands.length; i++) {
System.out.println(operatorsAndOperands[i] + " " + (int)operatorsAndOperands[i]);
if(i+1<operatorsAndOperands.length)
System.out.println(operatorsAndOperands[i+1]);
switch(operatorsAndOperands[i]){
case '+':
if(operatorsAndOperands[i+1] != '+' && operatorsAndOperands[i+1] != '-'){
result+=values[(int)operatorsAndOperands[i+1] - (int)'A'];
i++;
}
break;
case '-':
if(operatorsAndOperands[i+1] != '+' && operatorsAndOperands[i+1] != '-'){
result-=values[(int)operatorsAndOperands[i+1] - (int)'A'];
i++;
}
break;
default:
result = values[(int)operatorsAndOperands[i] - (int)'A'];
break;
};
System.out.println(result);
}
System.out.println(result);
}
}

Related

Palindrome program works fine for a single test case but keeps taking input otherwise

public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int test_cases = Integer.parseInt(br.readLine());
if (test_cases >= 1 && test_cases <= 20) {
String[] ans = new String[test_cases];
for (int i = 0; i < test_cases; i++) {
char[] n = br.readLine().toCharArray();
int k = 0;
int j = n.length - 1;
while (k <= j) {
if (n[k] == n[j]) {
k++;
j--;
ans[i] = "wins";
}
else
ans[i] = "loses";
}
}
for (String s : ans)
System.out.println(s);
}
}
catch (Exception x) {
}
}
PROBLEM STATEMENT: The first line of the input contains an integer T, the number of testcases. This is followed by T lines containing an integer N. For each input output "wins" if the number is a palindrome and "loses" if not, in a new line.
For test_cases=1, the program works fine but for test_cases>1 the program keeps taking input. I have solved the palindrome problem but I still can't understand what is wrong with this code. Can anybody explain to me why does it keeps taking input?
For non palindrome, your code runs in infinite loop. Just add break for that.
while (k <= j) {
if (n[k] == n[j]) {
k++;
j--;
ans[i] = "wins";
}
else {
ans[i] = "loses";
break;
}
}
This can be one of the solution.
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int test_cases = Integer.parseInt(br.readLine());
if (test_cases >= 1 && test_cases <= 20) {
for (int i = 0; i < test_cases; i++) {
char[] n = br.readLine().toCharArray();
int k = 0;
int j = n.length - 1;
boolean flag=false;
while (k <= j) {
if (n[k] == n[j]) {
k++;
j--;
flag=true;
}
else{
flag=false;
break;
}
}
if(flag) System.out.println("wins");
else System.out.println("loses");
}
}
}
catch (Exception x) {
}
}
For a string which is not a palindrome, your loop runs infinitely.
Also, you need not store the results in an array for all the test cases, you can print it every time for each test case. However, if you intend to store strings and display results later, you can use something like StringBuffer classes.

Extract the particular portion from a String

I have the below String variable
String s = "abc,xyz,lmn,ijk";
I want to extract only the portion of the String (i.e - 'lmn')
And, Should not use in-built functions like, SubString(), Split(), IndexOf(). But I can use charArray()
And this question was asked in my interview.
I tried the below code,
But not sure how to proceed. Can any one please provide your thoughts?
String s = "abc,xyz,lmn,ijk";
int counter = 0;
char[] ch = s.toCharArray();
for (int i = 0; i < ch.length; i++) {
if (ch[i] == ',') {
counter++;
}
}
Here's one way:
public static void main(String[] args) {
String s = "abc,xyz,lmn,ijk";
char[] ch = s.toCharArray();
int counter = 0;
int place = 2;
for (int i = 0; i < ch.length-2; i++) {
if(ch[i] == ',') {
counter++;
}
if(counter == place && ch[i] != ',') {
System.out.print(ch[i]);
}
}
}
It prints everything after the second comma, but before the third one.
public static void main(String[] args) {
// TODO Auto-generated method stub
String s = "abc,xyz,lmn,ijk";
StringBuffer sb=new StringBuffer();
char[] ch = s.toCharArray();
for (int i = 0; i < ch.length; i++) {
if(','==(ch[i]))
{
if (sb.toString().equals("lmn")) {
System.out.println(sb.toString());
}
else
{
int length=sb.length();
sb.delete(0, length);
}
}
else
{
sb.append(ch[i]);
}
}
}
I would do it this way.
String s = "abc,xyz,lmn,ijk";
String x = "c,x"; // String to found
String r = "";
boolean coincidence = false;
int a=0; // Initial index if of the first character in x is found
int b=0; // Last index If it was possible to search for the last character of x
int c=0; // Index "iterator" on String x
char[] ch = s.toCharArray();
for (int i = 0; i < ch.length; i++) {
if(c == x.length())
break;
else{
if(ch[i] == x.charAt(c) && !coincidence){
a = i; b = i; c++;
coincidence = true;
}
else if(ch[i] == x.charAt(c) && coincidence){
b++; c++;
}else{
coincidence = false;
a = 0; b = 0; c = 0;
}
}
}
System.out.println("String: " + s);
System.out.println("String to find: " + x);
System.out.println("Was found? " + ((coincidence)? "Yes" : "No"));
if(coincidence){
System.out.println("Intervals indexes in String: ["+a + "," + b +"]");
// String extration
for (int i = a; i <= b; i++)
r += s.charAt(i);
System.out.println("String extracted: " + r);
}

Using java, input string="aabbcdeaaaabbb" and the output must be aaaa

Using java, input string="aabbcdeaaaabbb" and the output must be aaaa, as sequence here is having repeated 4 times a. Can anyone help me to get this "aaaa" as output using java implementation.
Algorithm to find the Longest substring having same character repeated.
for eg:
I/P: aabbcdefaaaacccccc O/P: cccccc
Please check my program below and suggest any optimization for faster processing:
public class LongestSubString {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(
System.in));
System.out
.println("Enter a word to find longest substring with same characters repeated");
String word = reader.readLine();
System.out.println("Entered word is: " + word);
System.out.println("Longest repeated characters substring is: "
+ subStringFinder(word));
}
/*
*longest substring finder with same character repeated
*/
public static String subStringFinder(String word) {
char[] tokens = word.toCharArray();
int len = tokens.length;
int wordLen = word.length();
System.out.println("len of input word: " + wordLen);
List<String> myList = new ArrayList<>();
StringBuilder strConcat = new StringBuilder("");
for (int j = 0; j <= len - 1; j++) {
if (j + 1 > len - 1) {
if ((strConcat.length() >= 1)
&& (strConcat.charAt(strConcat.length() - 1) == (tokens[j]))) {
strConcat.append("" + tokens[j]);
myList.add(strConcat.toString());
}
}
else {
if (tokens[j] == tokens[j + 1]) {
if ((strConcat.length() >= 1)
&& (strConcat.charAt(strConcat.length() - 1) == (tokens[j]))) {
strConcat.append("" + tokens[j]);
myList.add(strConcat.toString());
} else {
strConcat = new StringBuilder("");
strConcat.append("" + tokens[j]);
}
} else {
if ((strConcat.length() >= 1)
&& (strConcat.charAt(strConcat.length() - 1) == (tokens[j]))) {
strConcat.append("" + tokens[j]);
myList.add(strConcat.toString());
} else {
strConcat = new StringBuilder("");
strConcat.append("" + tokens[j]);
}
}
}
}
int max = 0, index = 0;
for (int i = 0; i < myList.size(); i++) {
String strEle = myList.get(i);
int strLen = strEle.length();
if (max < strLen) {
max = strLen;
index = i;
}
}
return myList.get(index);
}
}
I believe your code is overly complicated. You don’t need a StringBuilder nor an ArrayList. I tried to understand your intention, but then skipped it and wrote my own version instead. Hope it helps anyway.
public static String subStringFinder(String word) {
if (word == null || word.isEmpty()) {
return word;
}
char currentChar = word.charAt(0);
int longestStart = 0;
int longestLength = 0;
int currentStart = 0;
int currentLength = 1;
for (int ix = 1; ix < word.length(); ix++) {
if (word.charAt(ix) == currentChar) {
currentLength++;
} else {
if (currentLength > longestLength) {
longestStart = currentStart;
longestLength = currentLength;
}
currentChar = word.charAt(ix);
currentStart = ix;
currentLength = 1;
}
}
if (currentLength > longestLength) {
longestStart = currentStart;
longestLength = currentLength;
}
return word.substring(longestStart, longestStart + longestLength);
}
String in = "aabbcdeaaaabbb";
String t;
ArrayList<String> out = new ArrayList<String>();
String l="";
int c=0;
String n;
for(int i=0;i<in.length;i++) {
n=in.substring(i, i+1); //get the current character
if(n.equals(l)){
l=n; c++;
}
else {
t=n;
for(int j=1;j<c;j++) {
n+=t;
}
c=0;
out.add(n);
c=0;
}
}

can someone help me clear these errors

I am trying to do a summation puzzle, the questions asks to use summation puzzles by enumerating and testing all possible configurations and then it says use it to solve the examples given. The examples given were
pot + pan = bib
dog+cat= pig
boy + girl = baby
I keep getting an error saying left hand side of assignment must be a variable
charSet.charAt(setIndex++) = stringTwo.charAt(loop);
cannot convert from int to bool.
if (exists = 0)
Also in my code where I try to display the output it doesn't run.
import java.util.Scanner;
public class Recursion
{
// Example program
public static String stringOne = new String(new char[10]);
public static String stringTwo = new String(new char[10]);
public static String stringThree = new String(new char[11]);
public static String charSet = new String(new char[11]);
public static int numberOne;
public static int numberTwo;
public static int numberThree;
public static int maxCharCount;
public static int[] numberSet = new int[10];
public static void checkForEquality()
{
numberOne = numberTwo = numberThree = 0;
int loop;
int subloop;
for (loop = 0; loop < stringOne.length(); loop++)
{
for (subloop = 0; subloop < maxCharCount; subloop++)
{
if (stringOne.charAt(loop) == charSet.charAt(subloop))
{
if (loop == 0 && numberSet[subloop] == 0)
return;
//generate the number
numberOne = (numberOne * 10) + numberSet[subloop];
}
}
}
for (loop = 0; loop < stringOne.length(); loop++)
{
for (subloop = 0; subloop < stringTwo.length(); subloop++)
{
if (stringTwo.charAt(loop) == charSet.charAt(subloop))
{
if (loop == 0 && numberSet[subloop] == 0)
return;
//generate the numeber
numberTwo = (numberTwo * 10) + numberSet[subloop];
}
}
}
for (loop = 0; loop < stringThree.length(); loop++)
{
for (subloop = 0; subloop < maxCharCount; subloop++)
{
if (stringThree.charAt(loop) == charSet.charAt(subloop))
{
if (loop == 0 && numberSet[subloop] == 0)
return;
//generate the number
numberThree = (numberThree * 10) + numberSet[subloop];
}
}
}
if (numberOne + numberTwo == numberThree)
{
//display the output
System.out.print(" Summation Puzzle solved. ");
System.out.print("\n");
System.out.print(stringOne);
System.out.print("<==>");
System.out.print(numberOne);
System.out.print("\n");
System.out.print(stringTwo);
System.out.print("<==>");
System.out.print(numberTwo);
System.out.print("\n");
System.out.print(stringThree);
System.out.print("<==>");
System.out.print(numberThree);
System.out.print("\n");
//loop to show the result
for (loop = 0; loop < maxCharCount; loop++)
{
System.out.print(charSet.charAt(loop));
System.out.print("<==>");
System.out.print(numberSet[loop]);
System.out.print("\n");
}
System.exit(0);
}
}
public static void generateCombinations(int indexCounter, int[] availableSet)
{
int loop;
if (indexCounter != 0)
{
for (loop = 0; loop < 10; loop++)
{
numberSet[indexCounter] = loop;
if (availableSet[loop] == 1)
{
availableSet[loop] = 0;
generateCombinations(indexCounter + 1, availableSet);
availableSet[loop] = 1;
}
}
}
if (indexCounter == maxCharCount)
{
checkForEquality();
}
}
public static void createCharSet()
{
int loop;
int setIndex;
int exists;
int subloop;
setIndex = 0;
for (loop = 0; loop < stringOne.length(); loop++)
{
exists = 0;
for (subloop = 0; subloop < setIndex; subloop++)
{
if (stringOne.charAt(loop) == charSet.charAt(subloop))
{
exists = 1;
}
}
if (exists == 0)
{
charSet = StringFunctions.changeCharacter(charSet, setIndex++, stringOne.charAt(loop));
}
}
for (loop = 0; loop < stringTwo.length(); loop++)
{
exists = 0;
for (subloop = 0; subloop < setIndex; subloop++)
{
if (stringTwo.charAt(loop) == charSet.charAt(subloop))
{
exists = 1;
}
}
if (exists == 0)
{
charSet = StringFunctions.changeCharacter(charSet, setIndex++, stringTwo.charAt(loop));
}
}
for (loop = 0; loop < stringThree.length(); loop++)
{
exists = 0;
for (subloop = 0; subloop < setIndex; subloop++)
{
if (stringThree.charAt(loop) == charSet.charAt(subloop))
{
exists = 1;
}
}
if (exists == 0)
{
charSet = StringFunctions.changeCharacter(charSet, setIndex++, stringThree.charAt(loop));
}
}
maxCharCount = setIndex;
}
public static void calculateSummation()
{
int loop;
if (maxCharCount > 10)
{
System.out.print("Please check the input again");
return;
}
else
{
int[] avaliableSet = new int[10];
for (loop = 0; loop < 10; loop++)
{
avaliableSet[loop] = 1;
}
generateCombinations(0, avaliableSet);
}
}
public static void main(String[]args)
{
Scanner scan = new Scanner(System.in);
System.out.print(" Enter the first String :");
stringOne = scan.next();
System.out.print(" Enter the second String :");
stringTwo = scan.next();
System.out.print(" Enter the thirsd String :");
stringThree = scan.next();
createCharSet();
System.out.print(" The character set formed from the given string = ");
System.out.print(charSet);
calculateSummation();
checkForEquality();
}
}
A lot of your problems are stemming from the syntax errors in the code you've written. For example:
line 74: if (stringThree.charAt(loop) == charSet.charAt(subloop) != null)
charSet.charAt(subloop) != null is an invalid comparison since the != operator cannot be used for booleans when comparing to null. If you're trying to determine if the characters return from .charAt(var) exist, use parentheses to make independent comparisons of each object.charAt(var) to null.
line 183: charSet = tangible.StringFunctions.changeCharacter(charSet, setIndex++, stringOne.charAt(loop));
tangible is ironically not tangible, as the variable does not exist locally or has not been defined globally.
charSet.charAt(setIndex++) = stringTwo.charAt(loop);
charSet.charAt(setIndex++) is a method that returns a character. This does not mean you can set the character at the specified index like it's a variable.
line 227: if (exists = 0)
You must use == when conducting comparisons in a conditional.
line 269: Scanner scan = new Scanner(System.in);
The Scanner class was not imported and thus cannot be used.
line 283: charSet.charAt(maxCharCount) = '\0';
Again, you can't use .charAt(var) to set the character at that index like it's a variable.
All of these problems can be self-determined by using a proper IDE, such as Eclipse.
Edit: Try to spend a little more time with pencil and paper working out the logic of your program before writing the code to represent your algorithm. This way you have focus and can write more comprehensive, commented, cleaner code. Here is a bit of a guide to help condense your existing project.

Java for loop error

I am trying to get user input for sortValues[] array using the for statement (enter character 1, enter character 2, etc).
However, when I execute this, the program will not allow me to enter for character 2, instead skipping directly to character 3, as seen below.
How to resolve this? The code is included below.
thanks!
static public void s_1d_char () {
int counter=0;
int x=0;
c.print("How many characters? ");
counter = readInt();
char[] sortValues = new char[counter+1];
for (x=1;x<=counter;x++) {
System.out.println("Enter character "+(x)+":");
sortValues[x] = readChar();
}
}
readChar implementation (this is from a library):
public synchronized char readChar ()
{
char result, ch;
if (ungotChar != EMPTY_BUFFER)
{
result = (char) ungotChar;
ungotChar = EMPTY_BUFFER;
return (result);
}
if (lineBufferHead != lineBufferTail)
{
result = lineBuffer [lineBufferTail];
lineBufferTail = (lineBufferTail + 1) % lineBuffer.length;
return (result);
}
startRow = currentRow;
startCol = currentCol;
if (currentRow > maxRow)
{
startRow++;
currentCol = 1;
}
// Turn cursor on if necessary
consoleCanvas.setCursorVisible (true);
// Wait for a character to be entered
while (true)
{
ch = getChar ();
if (ch == '\n')
{
clearToEOL = false;
if (echoOn)
print ("\n");
clearToEOL = true;
lineBuffer [lineBufferHead] = '\n';
lineBufferHead = (lineBufferHead + 1) % lineBuffer.length;
break;
}
if (ch == '\b')
{
if (lineBufferHead == lineBufferTail)
{
consoleCanvas.invertScreen ();
}
else
{
int chToErase;
lineBufferHead = (lineBufferHead + lineBuffer.length - 1) % lineBuffer.length;
chToErase = lineBuffer [lineBufferHead];
if (echoOn)
{
if (chToErase != '\t')
{
erasePreviousChar ();
}
else
{
int cnt;
eraseLineOfInput ();
cnt = lineBufferTail;
while (cnt != lineBufferHead)
{
print (lineBuffer [cnt]);
cnt = (cnt + 1) % lineBuffer.length;
}
}
}
}
} // if backspace
else if (ch == '\025')
{
if (echoOn)
{
eraseLineOfInput ();
}
lineBufferHead = lineBufferTail;
}
else
{
if (echoOn)
{
print (ch);
}
lineBuffer [lineBufferHead] = ch;
lineBufferHead = (lineBufferHead + 1) % lineBuffer.length;
}
} // while
result = lineBuffer [lineBufferTail];
lineBufferTail = (lineBufferTail + 1) % lineBuffer.length;
// Turn cursor on if necessary
consoleCanvas.setCursorVisible (false);
return (result);
}
I recommend getting user input with a scanner:
import java.util.Scanner;
// ...
int counter = 0;
System.out.println("How many characters?");
Scanner keyboard = new Scanner(System.in);
counter = keyboard.nextInt();
char[] sortValues = new char[counter+1];
// Start your index variable off at 0
for (int x = 0; x < counter; x++) {
System.out.println("Enter character "+(x)+":");
keyboard = new Scanner(System.in);
String line = keyboard.nextLine();
sortValues[x] = line.charAt(0);
}
This will capture the first character of the line. If the user enters more than one character, the program will read only the first.
Also, you should really start your index variable x off at 0, considering arrays are 0-based indexed.
instead of readChar() try:
sortValues[x] = Integer.parseInt(System.console().readLine());
How to read integer value from the standard input in Java

Categories