I need to solve this problem where i need to convert hexadecimal numbers to decimals.
Issue
I have compiled it without any errors, but my output came out wrong. Can someone show how to fix these errors?
Code
import java.util.Scanner;
import java.io.*;
class HexToDecException extends Exception {
public HexToDecException(String msg) {
super(msg);
}
}
public class Main {
public static int hexToDec(String hex) throws HexToDecException {
char currentChar;
int dec=0;
int power = 0;
for(int i=hex.length()+1;i>=0;i--){// by reverse
currentChar = hex.charAt(i);
if(currentChar>='0' && currentChar<='9'){
dec+= Math.pow(16,power)*(currentChar - '0');
power++;
}
else if(currentChar>='a' && currentChar<='f'){
dec+= Math.pow(16,power)*(currentChar - 'a' + 10);
power++;
}
else if(currentChar>='A' && currentChar<='G'){
dec+= Math.pow(16,power)*(currentChar - 'A' + 10);
power++;
}
else
throw new IllegalArgumentException("Invalid Character in Hexadecimal string");
}
return power;
}
public static void main(String[] args){
Scanner scan = null;
try{
scan = new Scanner(System.in);
int n = scan.nextInt();
for(int i=0;i<n;i++)
System.out.println(hexToDec(scan.next()));
}
catch(Exception ex){
ex.printStackTrace();
}
finally{
System.out.println("That's all.");
}
}
}
Example
Input:
5 6B 5 4AZ A5 9
Expected Output:
107 5 Invalid hexadecimal number 165 9
Output that i got:
That's all
Your solution is close. Here are changes to make so that it runs correctly:
modify the return statement of hexToDec() to return the decimal number you've constructed, not the power, so change this: return power to this: return dec
modify throws clause to this: throw new HexToDecException("Invalid hexadecimal number"); – use the custom exception you defined, and edit the string message to match the output you're expecting
change the for loop in hexToDec() so it that properly checks each position in the input string, so change this: for (int i = hex.length() + 1 to this: for (int i = hex.length() - 1. Maybe read up on how String.length() works in relation to charAt(). If a string has a length N, the corresponding "Nth" position in that string has to be referenced by N-1. N itself would never work, and N+1 would also not work.
finally, rewrite the main loop to wrap the call to hexToDec() in a try-catch, and print the exception message if an exception is thrown:
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
for (int i = 0; i < n; i++) {
String nextInput = scan.next();
try {
int x = hexToDec(nextInput);
System.out.print(x + " ");
} catch (HexToDecException e) {
System.out.print(e.getMessage() + " ");
}
}
After those changes, this input:
5 6B 5 4AZ A5 9
will produce this output:
107 5 Invalid hexadecimal number 165 9
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have to Print something like this
But i face Runtime error and wrong answer
input:
153
output:
1:1
5:55555
3:333
get an integer and print each number in its size
import java.util.Scanner;
public class q9774 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
String entery = Integer.toString(n);
char[] E = entery.toCharArray();
for (char value : E) {
System.out.print(value + ": ");
if (value == 0) continue;
else {
for (int i = 0; i < Integer.parseInt(String.valueOf(value)); i++) {
System.out.print(value);
}
System.out.println();
}
}
}
}
Since Java-11, you can use String#repeat to repeat a string for a given number of times.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
String entry = Integer.toString(n);
for (char value : entry.toCharArray()) {
System.out.print(value + ": ");
System.out.println(String.valueOf(value).repeat(Character.getNumericValue(value)));
}
}
}
A sample run:
153
1: 1
5: 55555
3: 333
An alternative way to process each character can be to split the string on each character and then repeat it for number of times equal to its numeric value.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
String entry = Integer.toString(n);
for (String s : entry.split("")) {// Split on each character
System.out.print(s + ": ");
System.out.println(s.repeat(Integer.parseInt(s)));
}
}
}
Here is one way of doing it.
converts the int to a String and then to a char[] array
prints the character followed by itself repeated.
any character digit - '0' is a numeric value of the same quantity represented by the character. So the character '7' has the int value of '7' - '0' or 7.
int i = 153;
for (char c : Integer.toString(i).toCharArray()) {
System.out.printf("%c:%s%n", c, (c+"").repeat(c-'0'));
}
Prints
1:1
5:55555
3:333
I added a nested loop for each digit and I repeat that nested loop according to index of value in string by j <= i; condition:
Scanner input = new Scanner(System.in);
int n = input.nextInt();
String entery = Integer.toString(n);
char[] E = entery.toCharArray();
for (int i = 0; i < E.length; i++) {
for (int j = 0; j <= i; j++) {
System.out.print(E[i]);
}
System.out.println();
}
This question already has answers here:
try/catch with InputMismatchException creates infinite loop [duplicate]
(7 answers)
Closed 2 years ago.
my program is suppose to add 10 to an array of random numbers when the user enter an integer , the array of random numbers will be displayed and adds 10 to them under the first array and if the user doesn't enter an int then the try catch statement catches the error displaying an error message, so what i want to do is add a loop in the try catch statement that makes the user enter an int when they don't this is what i tried so far and didn't work
public class tryandcatch {
public static void main(String[] args) {
int[] tab=new int[10];
int i;
Scanner inp=new Scanner(System.in);
while(true) {
try{
System.out.println("Please enter an integer number");
i=inp.nextInt();
for(i=0;i<tab.length;i++){
tab[i]=((int)(Math.random()*100));
System.out.print(tab[i]+" ");
}
addTen(tab);
System.out.print("\n");
for(i=0;i<tab.length;i++)System.out.print(tab[i]+" ");
break;
}
catch(InputMismatchException e){
System.out.println("The number must be integer");
i=inp.nextInt();
}
}
}
static void addTen(int[] x){
int i;
for(i=0;i<x.length;i++) x[i]+=10;
}
}
Use Integer.parseInt(Scanner::nextLine()) instead of Scanner::nextInt(). Check this to learn more about it.
For simplicity, you can use a boolean variable to track if loopback is required.
Do it as follows:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int[] tab = new int[10];
int n;
Scanner inp = new Scanner(System.in);
boolean valid;
do {
valid = true;
try {
System.out.print("Please enter an integer number: ");
n = Integer.parseInt(inp.nextLine());
for (int i = 0; i < tab.length; i++) {
tab[i] = ((int) (Math.random() * 100));
System.out.print(tab[i] + " ");
}
addTen(tab);
System.out.println();
for (int i = 0; i < tab.length; i++) {
System.out.print(tab[i] + " ");
}
} catch (NumberFormatException e) {
System.out.println("The number must be integer");
valid = false;
}
} while (!valid);
}
static void addTen(int[] tab) {
for (int i = 0; i < tab.length; i++) {
tab[i] += 10;
}
}
}
A sample run:
Please enter an integer number: a
The number must be integer
Please enter an integer number: 10.5
The number must be integer
Please enter an integer number: 5
21 50 83 72 95 60 61 64 98 95
31 60 93 82 105 70 71 74 108 105
Note that I have used do...while which guarantees that the code inside the loop block will be executed at least once. In this particular case, the use of do...while has also made the code easier to understand. However, the use of do...while to solve this problem is optional and you can continue using while instead of do...while if you wish so.
Use a break; statement.
This statement exits the loop, so enclose the try-catch statement in a while(True) loop. If an error is not raised, then the break; statement exits the loop.
Scanner tries to parse an input until it is successful. In your code it always tries to parse the first non-integer input again and again. In order to fix this you can read the user input without trying to parse it to an int. You could change your catch-block as follows:
catch(InputMismatchException e){
final String nonInteger = inp.next();
System.out.println("The number must be integer. You typed: " + nonInteger);
}
The output is supposed to be the conversion of binary to decimal. When I run this program and input (for example) 101, it will print the answers 3 times because 101 is 3 digits. How do I fix this? I only need one answer. please help
import java.util.Scanner;
public class Bin2Dec {
public static void main (String[] args){
//Convert the input string to their decimal equivalent.
//Open scanner for input.
Scanner input = new Scanner(System.in);
//Declare variable s.
String s;
//Prompt user to enter binary string of 0s and 1s.
System.out.print("Enter a binary string of 0's and 1's: ");
//Save input to s variable.
s = input.nextLine();
//Create a loop using the length of user input as the maximum number.
for (int i=0;i< s.length();i++){
try {
System.out.println("The decimal value of the binary number "+ s +" is "+error(s));
} catch (BinaryFormatException e) {
System.out.println("There is an error in the entered binary string:"+e.getMessage());
}
}
}
public static int error(String parameter) throws BinaryFormatException {
int tot = 0;
for (int i = parameter.length(); i > 0; i--) {
char c = parameter.charAt(i - 1);
if (c == '1') tot += Math.pow(2, parameter.length() - i);
else if (c != '0') throw new BinaryFormatException("'"+c+"' is not a binary digit");
}
return tot;
}
}
You are invoking the method in a for loop:
for (int i=0;i< s.length();i++){
try {
System.out.println("The decimal value of the binary number "+ s +" is "+error(s));
} catch (BinaryFormatException e) {
System.out.println("There is an error in the entered binary string:"+e.getMessage());
}
}
so of course it will execute as many times as the number of characters in the input. Move the call to error(s) out of the for loop.
You shouldn't try and reinvent something that has already been done. Simply using Integer#parseInt(String s, int radix) should be enough:
public class Bin2Dec {
public static void main (String[] args){
System.out.print("Enter a binary string of 0's and 1's: ");
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
int decoded = Integer.parseInt(input, 2);
System.out.println(decoded);
}
}
Just remove the 'for' loop as shown:
//Create a loop using the length of user input as the maximum number.
//for (int i=0;i< s.length();i++){
try {
System.out.println("The decimal value of the binary number "+ s +" is "+error(s));
} catch (Exception e) {
System.out.println("There is an error in the entered binary
string:"+e.getMessage());
}
}
//}
I have the following code:
import java.io.*;
public class ExamPrep2
{
public static int getPositiveInt()
{
BufferedReader stdin = new BufferedReader(
new InputStreamReader(System.in));
int positiveInt = 0;
try
{
positiveInt = stdin.read();
if (positiveInt < 0) {
System.out.print("A negative int! -1");
return -1;
}
else {
System.out.print("Yay! " + positiveInt);
return positiveInt;
}
}
catch (IOException e) {
System.out.print("Positive int is NaN! -2");
return -2;
}
}
public static void main(String[] args)
{
System.out.print("Enter a positive integer:");
getPositiveInt();
}
}
But when I enter in values, I am not getting the same value back that I have entered.
eg:
Enter a positive integer:1
Yay! 49
Enter a positive integer:-2
Yay! 45
Enter a positive integer:x
Yay! 120
What obvious thing am I overlooking?
The method stdin.read(); is not right method to get int value. Use stdin.readLine(),
positiveInt = Integer.parseInt(stdin.readLine());
This line of code is reading a single character from the stream so it is reading "-" and interrupting it as an integer which is going to be > 0.
positiveInt = stdin.read();
You will need to read the full line of text to get both the - and the 1 characters from the stream.
You can look at an ASCII table and see that 1 = ASCII 49, - is ASCII 45, etc...
http://www.asciitable.com/
You are reading everything in as a char:
positiveInt = stdin.read();
This will return a char. When you enter 1 it will return the ASCII value of this character. Which is 49.
Instead you should use a Scanner.
Scanner scan = new Scanner(System.in);
int input = scan.nextInt();
See the following sample:
public static void main(String[] args) {
char input = '1';
System.out.println((int) input);
}
Output:
49
Read it using Scanner class. Scanner scanner = new Scanner(System.in); and then scanner.nextInt(). BufferedReader is giving you the ASCII value.
I am currently working on a program that calculates the power of certain numbers. The number limit is 1 to 9. My code is posted below. I have the following issues:
Every time I run the program it doesn't print the correct answer.
I want to modify the code so the application calculates X to power of Y, where X and Y are allowed to be integers in the range 1 to 9 (including 9). If the user enters an invalid value the program should ask the user for input again. When a user is done with entering the values for base and exponents, the program will print the result.
Conditions of this task is that I must use loops to calculate the result by doing
several multiplications; I am not allowed to use any available method or API
that calculates the result for me. Please help me come up with the solution.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package exponent;
//import java.util.Scanner;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int b,e;
System.out.println("Enter the base");
b = Integer.parseInt(br.readLine());
System.out.println("Enter the power");
e = Integer.parseInt(br.readLine());
int t = 1;
for(int i = 1;i <= e; i++);
{
t=t*b;
}
System.out.println(t);
}
// TODO code application logic here
}
For a start, there should be no semi colon after the for loop:
for(int i=1;i<=e; i++ )
{
t=t*b;
}
A simple input test could be something along the lines of:
public boolean testInput(int e)
{
if(e>9||e<1)//where e is the inputted number
{
return false
}
else
{
return true;
}
}
Then use it like this:
boolean valid = false;
while(valid!=true)
{
e = Integer.parseInt(br.readLine());
if(testInput(e)==false)
{
System.out.println("Please enter a number between 1 and 9")
continue;
}
else
{
valid = true;
}
}
Remove semi colon from for-loop
From
for(int i=1;i<=e; i++ );
to
for(int i=1;i<=e; i++ )
For the first part, its is a easy fix. You just added a semicolon where there shouldn't be in the for loop.
for(int i = 1;i <= e; i++); {
for(int i = 1;i <= e; i++){ //There should be no semicolon here
For the second part, you can do it with two very easy do-while loops.
//Replace this
System.out.println("Enter the base");
b = Integer.parseInt(br.readLine());
System.out.println("Enter the power");
e = Integer.parseInt(br.readLine());
//with
do{
System.out.println("Enter the base");
b = Integer.parseInt(br.readLine());
}while(b > 9 || b < 1);
do{
System.out.println("Enter the power");
e = Integer.parseInt(br.readLine());
}while(e > 9 || e < 1);
So the do-while loops, will first ask for the base or the power (Depending where in the code the program is running), then it will set the int to the value. If the value is greater than 9, ie: 10 or above, the program will reask for the base or power (Like I said, depended which loo is running), and then it will set the int again. It will do this, until the value is under 10. Like you want.
Here is an example of the output:
Enter the base
56
Enter the base
-4
Enter the base
4
Enter the power
67
Enter the power
10
Enter the power
-8
Enter the power
7
4 to the 7th power is 16384
If the code snippets are confusing, here is the entire compilable, working class:
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class StackOverflowAnswers{
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int b,e;
do{ //Asks for the base
System.out.println("Enter the base");
b = Integer.parseInt(br.readLine());
}while(b > 9 || b < 1); //If the base is not valid, it goes back to the "do" statement, which asks for the base, again.
do{ //Asks for the power
System.out.println("Enter the power");
e = Integer.parseInt(br.readLine());
}while(e > 9 || e < 1); //If the power is not valid, it goes back to the "do" statement, which asks for the power, again.
int t = 1;
for(int i = 1;i <= e; i++){ //No semicolon here
t=t*b;
}
System.out.println(b + " to the " + e + "th power is " + t); //Just added some words and the base and the power for easier debugging and understanding.
}
}
Hope this helps.
For the first part, it is just happening because you placed a semicolon after loop's declaration, which java just loops to that semicolon and nothing more. By removing semicolon the loop should work. However, for the second part, you can just add inputcheck method, as shown in my code below.
import java.io.*;
public class abc {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int b, e;
System.out.println("Enter the base");
b = check(Integer.parseInt(br.readLine()));
System.out.println("Enter the power");
e = check(Integer.parseInt(br.readLine()));
int t = 1;
for (int i = 1; i <= e; i++); {
t = t * b;
}
System.out.println(t);
}
private static int check(int x) {
while (x < 1 || x > 10)
x = Integer.parseInt(br.readLine());
return x;
}