Written code that converts decimal to hexadecimal - but wrong order output - java

I have written a code that will convert a decimal number to a hexadecimal. Let's take as example the decimal number 123456. My code will give output 042e1, so the total wrong order of the correct result 1e240.
My question, what I need to do to change the order of my output? I planned to convert to String and use new StringBuilder(hi).reverse().toString(). But this seems too complicated, I mean, how shall I take my outputs and convert them to string..? There must be an easier way.
I hope you can help me. I'm very happy I managed to get that far without any help, but I don't know how to get thisy work. This is no homework so feel free to help if you have some time :)
Here is my code:
import java.util.Scanner;
public class Convert{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
double x = input.nextInt();
double result = x;
do{
result = result / 16;
int temp = (int)result;
double rest = result*16-temp*16;
if((int)rest == 10){
System.out.print('a');
}
if((int)rest == 11){
System.out.print('b');
}
if((int)rest == 12){
System.out.print('c');
}
if((int)rest == 13){
System.out.print('d');
}
if((int)rest == 14){
System.out.print('e');
}
if((int)rest == 15){
System.out.print('f');
}
if((int)rest != 10 && (int)rest != 11 && (int)rest != 12 && (int)rest != 13 && (int)rest != 14 && (int)rest != 15){
System.out.print((int)rest);
}
}while((int)result != 0);
}
}

First, you'll need to make a StringBuilder object:
StringBuilder builder = new StringBuilder(); // place this before the do while block
then within each if block do this:
if((int)rest == 10){
builder.append("a");
}
if((int)rest == 11){
builder.append("b");
}
if((int)rest == 12){
builder.append("c");
}
....
....
Considering you've mentioned:
My code will give output 042e1, so the total wrong order of the
correct result 1e240.
then after the do while loop, simply reverse() it to yield the output 1e240:
System.out.println(builder.reverse());

Related

Make an algorithm start again?

So I'm pretty new to coding with Java (started yesterday). What I am trying to do is to make an Input of an Integer, if the int c it is higher than 1 or lower than 0 (if it is not 1 or 0), I want it to start again. If int c equals either 1 or 0, I want the alogrithm to continue. I tried to insert some kind of loops after if(c > 1 || c < 0) but it does not seem to work and only spams my console with the result. Is there any easy way to make the algorithm start over again? I'm already trying to fix this for more than 2 hours, but I'm just confusing me over and over again.
// more code up here but it is unimportant
int c = sc.nextInt();
if(c > 1 || c < 0) {
result = result + wrong;
System.out.println(result);
} else if (c == 1) {
result = result + notImplemented;
System.out.println(result);
} else if (c == 0) { //more code follows here but is unimportant
So you want to ask for input again, i assume.
A simple way could be:
int c = sc.nextInt();
while (c > 1 || c < 0) {
c = sc.nextInt();
}
//code continues
You can use while in this case and use break to exit:
while (scanner.hasNext()) {
int c = sc.nextInt();
if(c > 1 || c < 0) {
result = result + wrong;
System.out.println(result);
} else if (c == 1) {
result = result + notImplemented;
System.out.println(result);
break;
} else if (c == 0) {
...
break;
}
}
scanner.close();
You need to use a loop so you have
while(true){
int c = sc.nextInt();
if(c > 1 || c < 0) {
result = result + wrong;
System.out.println(result);
break;
} else if (c == 1) {
result = result + notImplemented;
System.out.println(result);
} else if (c == 0) { //more code follows here but is unimportant
...
}
Since you say you are new, I'll do a little explanation:
A While loop repeats what is in it's code block (i.e within the { }) for as long as a certain condition is true. In the case of my answer I did while(true) meaning it will keep repeating until something causes it to stop. In this case I used a break which forces the loop to end/stop.
Use hasNextInt() and a while loop to iterate over the data:
while (sc.hasNextInt()) {
int aInt = sc.nextInt();
//logic here
}
Documentation for hasNextInt() method:
https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#hasNextInt()
You can put your code in a function (which I hope is already the case) and then when you don't have the expected result and want to call it again, just do so by calling your function inside itself.
It's called recursion.
You can learn more here .
For example :
// more code up here but it is unimportant
public void myFunction(){
int c = sc.nextInt();
if(c > 1 || c < 0) {
result = result + wrong;
System.out.println(result);
} else if (c == 1) {
result = result + notImplemented;
System.out.println(result);
} else if (c == 0) { //more code follows here but is unimportant
}
//You want to call your function again
myFunction();
}

Having trouble with JFile Chooser and Buffered Reader

I am trying to create a program that will evaluate expressions using a stack for a project for a class. I am not done with it yet, I am just getting things to go onto one of two stacks, an operators stack and an operands stack. Everything was working that way I intended until I created a method that would check the priority of the operators stack, how it works is plus and minus signs have lowest priority then it goes multiplication and division signs and greater than or equal signs have highest priority. This method in my code is called checkPred and when this method is commented out my JFile Chooser works and reads in the data from the file but when its not commented out my JFile Chooser does not work and in my try/catch statement it executes the catch block which results in an output of Error!. The .txt file I am reading from contains this: 4*6*5-9
import java.io.*;
import java.util.*;
import javax.swing.JFileChooser;
public class Evaluate
{
static Stack<Character> operators = new Stack<Character>();
static Stack<Character> operands = new Stack<Character>();
public static void main(String args[])
{
JFileChooser chooser = new JFileChooser();
int status;
status = chooser.showOpenDialog(null);
if(status == JFileChooser.APPROVE_OPTION)
{
try
{
FileReader reader = new FileReader(chooser.getSelectedFile().getAbsolutePath());
BufferedReader buff = new BufferedReader(reader);
String line;
while((line = buff.readLine()) != null)
{
getCharAt(line);
}
buff.close();
}
catch(Exception ex)
{
System.out.println("Error!");
}
}
else
{
System.out.println("Open File dialog canceled");
}
}
public static void getCharAt(String x)
{
int charToInt;
for(int i = 0; i < x.length(); i++)
{
charToInt = x.charAt(i);
if(charToInt >= 48 && charToInt != 60 && charToInt != 62 )
{
operands.push(x.charAt(i));
}
else
{
if(checkPred(x.charAt(i),operators.peek()))
{
operators.push(x.charAt(i));
}
}
}
System.out.println(operands);
System.out.println(operators);
}
public static boolean checkPred(char op1, char op2)
{
int plusMinus = 1;
int multDivide = 2;
int greaterLess = 3;
int op1Value = 0;
int op2Value = 0;
if(op1 == 43 || op1 == 45)
{
op1Value = plusMinus;
}
else if(op1 == 42 || op1 == 47)
{
op1Value = multDivide;
}
else if(op1 == 60 || op1 == 62)
{
op1Value = greaterLess;
}
if(op2 == 43 || op2 == 45)
{
op2Value = plusMinus;
}
else if(op2 == 42 || op2 == 47)
{
op1Value = multDivide;
}
else if(op2 == 60 || op2 == 62)
{
op2Value = greaterLess;
}
if(op1Value > op2Value)
return true;
else
return false;
}
}
Look at this part of your code:
if(checkPred(x.charAt(i),operators.peek()))
{
operators.push(x.charAt(i));
}
On your first operator(the first '*') operators.peek() is called in the condition before operators.push() is called a single time.
This results in a EmptyStackException which is caught by the catch block in your main method.
You can replace the section which is you are adding operators with this code. Otherwise the first time you are calling checkPred method you got nothing in the operators Stack to peek.
if (operators.empty()) {
operators.push(x.charAt(i));
} else if (checkPred(x.charAt(i), operators.peek())) {
operators.push(x.charAt(i));
}
There is nothing wrong with the JFile Chooser or with the Buffered Reader. What causes the problem is that before you call operators.push(), you will need to populate the operands stack, otherwise it's going to throw an exception.
I am not sure how you are going to finish this calculator program, but if you need need to check the precedence the first time, you could do this:
Add an element to the operators stack first, any character that you will not use later as an operator, like:
operators.push('#'); // # = 64 in ascii
Complement your checkPred(char,char) method in a way that comparing 'any operator' and # will always yield that the 'any operator' has a higher precedence. You could start your method like this:
public static boolean checkPred(char op1, char op2){
if (op1 == 64) return false;
if (op2 == 64) return true;
One last thing, I am not an ASCII master, I needed to look up the values for each character you are using. If you convert the characters into ints and then put them inside if statements (or use comments like // 43 = '+'), it makes your code more readable and it will be much clearer for you as well when you look at this program again in a few weeks, months time.

Else if condition being ignored?

I'm new to Java and i have to make a small application that will calculate GCD of up to 5 numbers.
If the input is nothing before 5 numbers have been entered, the application will calculate it on the already given numbers
Unfortunately my code seems to ignore my else if statement that will make sure it doesn't try to add "" to a int array.
This is the part that i am struggling on, i have already tried contains instead of equals but with no result.
Am i writing the !input.. wrong? The code runs correct when i try to add a 0, it will not execute the else if.
But if i enter "" to make the application run the first part of the if statement it will go to the else if after its done and try to add "" to the array which of course results in an error.
I'm sure its something small i am missing or am unaware of, but i can't seem to figure it out.
}else if(Integer.parseInt(input) != 0 || !input.equals(""));{
ggdGetallen[count] = Integer.parseInt(input);
count++;
txtGetal.selectAll();
}
Full code
private void txtGetalActionPerformed(java.awt.event.ActionEvent evt) {
String input = txtGetal.getText();
//Berekenen van het kleinste getal in het array
if(count > 4 || input.equals("")){
int kleinsteGetal = ggdGetallen[0];
for (int getal : ggdGetallen){
if (getal < kleinsteGetal && getal != 0){
kleinsteGetal = getal;
}
}
boolean isDividableBy;
boolean ggdFound = false;
while(!ggdFound){
for (int getal : ggdGetallen) {
if (getal != 0){
isDividableBy = (getal % kleinsteGetal == 0);
ggdFound = true;
if(!isDividableBy){
kleinsteGetal--;
ggdFound = false;
break;
}
}
}
}
lblResultaat.setText(String.format("De grootste gemene deler is %d", kleinsteGetal));
}else if(Integer.parseInt(input) != 0 || !input.equals(""));{
ggdGetallen[count] = Integer.parseInt(input);
count++;
txtGetal.selectAll();
}
}
remove semicolon from your else if.

Java-Finding whether given numbe is prime or not by using recursive method call

I had done a lot of googling about it but unable to figure out the right answer. While I am running the below code i am always getting output as "not prime even though the input is prime number like 13".
Please help me out.
import java.util.Scanner;
public class PrimeRecurssion {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int number = sc.nextInt();
System.out.println("Your given number is:" + prime(number,2));
}
public static String prime(int x,int temp )
{
if(x%temp == 0)
{
return("not a prime");
}
if(x != temp-1)
{
return prime(x,temp+1);
}
else
return("prime");
}
}
try
if(x - 1 != temp)
{
return prime(x,temp+1);
}
or
if(x != temp + 1)
{
return prime(x,temp+1);
}
at the moment you compare x with temp - 1
eg. x = 13, temp = 12 what leads to 13 != 12-1
=> so prime(13, 13) is called, which returns with "no prime"
Try to change
if(x != temp-1)
to
if(x != temp+1)
It will not cure all bugs you have, but probably fix it a bit.
public static String prime(int x,int temp )
{
if(x == 1)
{
return "prime";
}
if(x != temp)
{
if(x%temp == 0)
{
return("not a prime");
}
else
{
return prime(x,temp+1);
}
}
else
return("prime");
}
This works because you only want to return prime if you have reached the number itself otherwise you will hit a not prime before that point. Look at the code and see if you can figure out what is going on.

Infix to Postfix using stacks and Precedence of Operators [duplicate]

This question already has answers here:
Handling parenthesis while converting infix expressions to postfix expressions
(2 answers)
Closed 5 years ago.
I know there are similar questions to this already on SO but I can't find one which solves the problem I'm having. I am trying to make a method which converts infix notation expressions to postfix notation, while implementing precedence of operators in order to get correct output.
I have made my own stack class with the usual methods (push, pop, peek etc.) and it works absolutely fine. My problem is that for more complicated expressions such as A-(B+C^D^C)/D*B , I am getting the wrong output. The result of the conversion should be ABCDC^^+D/B*- whereas i keep on getting ABCDC^^+D/-B
here is my method:
public static String infixToPostfix(char[] expressionArray, CharStack opStack){
String output = "";
int length = expressionArray.length;
for(int i = 0; i < length; i++){
if(isOperatorOrBracket(expressionArray[i])){
if(priorityAtInput(expressionArray[i]) >= priorityAtStack(opStack.peek())){
opStack.push(expressionArray[i]);
}else if(priorityAtInput(expressionArray[i]) == priorityAtStack(opStack.peek())){
output = output + expressionArray[i];
}else{
while(opStack.peek() != '('){
output = output + opStack.pop();
}
opStack.pop();
}
}else{
output = output + expressionArray[i];
}
}
while(!opStack.empty()){
if(opStack.peek() != '('){
output = output + opStack.pop();
}else if(opStack.peek() == '('){
opStack.pop();
}
}
return output;
}
Please let me know if you need to any of the component methods. Any help greatly appreciated!
After an hour of staring at the screen I found the problem. Thank goodness for the debugger in eclipse!
public static String infixToPostfix(char[] expressionArray, CharStack opStack){
String output = "";
int length = expressionArray.length;
for(int i = 0; i < length; i++){
if(isOperatorOrBracket(expressionArray[i])){
if(priorityAtInput(expressionArray[i]) >= priorityAtStack(opStack.peek())){
opStack.push(expressionArray[i]);
}else if(priorityAtInput(expressionArray[i]) < priorityAtStack(opStack.peek())){
while(priorityAtInput(expressionArray[i]) < priorityAtStack(opStack.peek())){
output = output + opStack.pop();
if(opStack.peek() == '('){
opStack.pop();
break;
}else if(priorityAtInput(expressionArray[i]) >= priorityAtStack(opStack.peek())){
opStack.push(expressionArray[i]);
break;
}
}
}else{
while(opStack.peek() != '('){
output = output + opStack.pop();
}
opStack.pop();
}
}else{
output = output + expressionArray[i];
}
}
while(!opStack.empty()){
if(opStack.peek() != '('){
output = output + opStack.pop();
}else if(opStack.peek() == '('){
opStack.pop();
}
}
return output;
}

Categories

Resources