This is the code I am working on. The problem is when I enter a non hexadecimal value such as "rr" or "z", it prints a negative value. How can I stop it from doing this? Also, how can I solve this question? When the program starts it asks the user to enter a hexadecimal number of lengths 2 (e.g., 1F). The smallest number the user should enter is 90 (decimal equivalent 144) and the largest is FF (decimal equivalent 255).
import java.util.Scanner;
public class HexaConverter {
public static int hex2decimal(String s)
{
String digits = "0123456789ABCDEF";
s = s.toUpperCase();
int val = 0;
for (int i = 0; i < s.length(); i++)
{
char c = s.charAt(i);
int d = digits.indexOf(c);
val = 16*val + d;
}
return val;
}
//Start of conversion method
public static void main(String args[])
{
String hexadec_num;
int dec_num, i=1, j;
int bin_num[] = new int[100];
Scanner scan = new Scanner(System.in);
System.out.print("Please enter a Hexadecimal Number: ");
hexadec_num = scan.nextLine();
final int MAX_LENGTH = 2;
if(String.valueOf(hexadec_num).length() <= MAX_LENGTH) {
/* first convert the hexadecimal to decimal */
dec_num = hex2decimal(hexadec_num);
System.out.print("Equivalent Dec Number is : "+ dec_num);
System.out.println();
/* now convert the decimal to binary */
while(dec_num != 0)
{
bin_num[i++] = dec_num%2;
dec_num = dec_num/2;
}
System.out.print("Equivalent Binary Number is : ");
System.out.print("\n");
for(j=i-1; j>0; j--)
{
System.out.print(bin_num[j]);
}
}
else
{
System.out.println("ERROR: Input number was too long");
main(args); // calling to return to the main method
}
}
}
int d = digits.indexOf(c); will return -1 if the character doesn't exist in the digits string, if you add in a check for this:
int d = digits.indexOf(c);
if (d == -1) return 0; // CHECK HERE
val = 16*val + d;
Then you can handle the error as you like, in this example I just returned 0
As for the second part of the question, you can just check the value of the returned result is within the range 144 and 255
if (144 <= dec_num && dec_num <= 255) return "SUCCESS";
return "FAIL";
Related
I'm new to java, got an assignment about converting binary to decimal.
here's my code
public static void main(String[] args) {
int num, decimal = 0, i=0;
Scanner in = new Scanner(System.in);
System.out.println("Enter a Binary Number");
String binary = in.nextLine();
num = Integer.parseInt(binary);
while(num != 0){
decimal += (num%10)*Math.pow(2, i);
num = num /10;
i++;
}
System.out.println("Decimal Number : "+ decimal);
}
It's already done but the teacher request "Use scanner class inside a while loop for users to enter the binary number one by one. A “-1” would stop the loop."
Does anyone know how to change my code?
Use another while loop and keep iterating until the user inputs -1.If user inputs -1 use break to come out of while loop
public static void main(String[] args) {
int num, decimal = 0, i=0;
Scanner in = new Scanner(System.in);
while(true) {
System.out.println("Enter a Binary Number");
String binary = in.nextLine();
num = Integer.parseInt(binary);
if(num ==-1){
break;
}
while(num != 0){
decimal += (num%10)*Math.pow(2, i);
num = num /10;
i++;
}
System.out.println("Decimal Number : "+ decimal);
}
}
Your task consists of two parts: iterated input-check-process cycle and the process itself.
The former is simply solved with a loop:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (true) {
// input
System.out.println("Enter a Binary Number");
String inputStr = in.nextLine();
// check
if (inputStr.equals("-1")) {
break;
}
// process
// TODO
}
}
This repeats asking for input data, reading it, testing for a special 'terminate' value and exits eventually if one is found.
The second part can be solved as follows: scan input digits one by one; each new digit found becomes a new least-significant bit of a number being constructed, while all preceding digits become one position more significant than they were.
That means, whenever you find a new digit, the number gets doubled and the value of a new digit gets added:
// process
int result = 0;
int position;
for (position = 0; position < inputStr.length(); ++position) {
char digit = inputStr.charAt(position);
int val = Character.digit(digit, 2);
result = 2*result + val;
}
System.out.println("Decimal Number : "+ result);
Together they make:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (true) {
// input
System.out.println("Enter a Binary Number");
String inputStr = in.nextLine();
// check
if (inputStr.equals("-1")) {
break;
}
// process
int result = 0;
int position;
for (position = 0; position < inputStr.length(); ++position) {
char digit = inputStr.charAt(position);
int val = Character.digit(digit, 2);
result = 2*result + val;
}
System.out.println("Decimal Number : "+ result);
}
}
Of course, for a real-life program we should also validate input, ie. test if it consists of digits 0 and 1 only, whether it's not empty or not too long (so that the result of conversion fits the values range of type int).
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();
}
I've got to find a solution to find the next largest number, based on a sequence of 0,1,2,3,4,5,6,7,8,9 input by the user.
For example is the user inputs
5647382901
then my function has to change it to
5647382910
My below code replace my last 2 x digits with the temporary char K, but I need it to replace just the last digit. Please let me know what I'm doing wrong?
import java.util.*;
public class NextLargest {
int a = 100;
public static void nextLargest(String a){
long newNumber = Long.valueOf(a);
int last = (int)(newNumber%10);
int lastByOne = (int)(newNumber/10)%10;
if(last > lastByOne){
char k = a.charAt(a.length()-2); // 0
a = a.replace(a.charAt(a.length()-2),a.charAt(a.length() -1) ); // 5647382911
System.out.println(b); // 5647382911
a = a.replace(a.charAt(a.length()-1),k);
System.out.println(a);
}
System.out.println(a);
System.out.println(last);
System.out.println(lastByOne);
}
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the number");
String number = scan.next();
nextLargest(number);
}
}
the problem with replace method is that it changes all the occurences of your old char with your new char and thats why you can't switch the last 2 digits you can try it using this solution :
long newNumber = Long.valueOf(a);
int last = (int)(newNumber%10);
int lastByOne = (int)(newNumber/10)%10;
if(last > lastByOne){
newNumber= newNumber - lastByOne*9 + last*9 ;
}
System.out.println("!!!!!!!!!!!!!!!! my final number :"+newNumber);
a = String.valueOf(newNumber);
System.out.println("!!!!!!!!!!!!!!!! my final number :"+a);
}
I am supposed to do this :
For an input number print frequency of each number in the order of its occurrence.For eg :
Input:56464
Output:
Number-Frequency
5 -1
6 -2
4 -2
I cannot use any other libraries except java.lang and Scanner to input
So I tried this :
package practice2;
import java.util.Scanner;
public class DigitFrequency2
{
private static Scanner sc;
public static void main(String[] args)
{
sc = new Scanner(System.in);
System.out.println("Enter an integer number");
String sb = sc.nextLine();
System.out.println("Number\tFrequency");
int i,x,c = 0;
for(i=0;i<sb.length();i++)
{
c = 0;
for(x = i+1;x<sb.length();x++)
{
if(sb.charAt(i) == sb.charAt(x) && sb.charAt(i) != '*' && sb.charAt(x) != '*')
{
c++;
sb.replace(sb.charAt(x),'*');
}
}
if(c>0)
{
System.out.println(sb.charAt(i)+" \t"+c);
}
}
}
}
Number Frequency
6 1
4 1
Where am I going wrong please help.
Simple way is this. Won't bother commenting as it is clear whats going on.
Scanner in = new Scanner(System.in);
while (true) {
System.out.print("Input String: ");
String line = in.nextLine();
while (!line.isEmpty()) {
char c = line.charAt(0);
int length = line.length();
line = line.replace(String.valueOf(c), "");
System.out.println(c + " " + (length - line.length()));
}
}
There are few problems with sb.replace(sb.charAt(x),'*');:
replace replaces all characters, not just first one which is why your c can't be grater than 1.
Strings are immutable so since replace can't edit original string, it returns new one with replaced characters which you can store back in sb reference.
Anyway if you would be able to use other Java resources beside java.lang.* or java.util.Scanner simple approach would be using Map which will map character with number of its occurrences. Very helpful here is merge method added in Java 8 allows us to pass key initialValue combination of old and new value
So your code can look like:
String sb = ...
Map<Character, Integer> map = new TreeMap<>();
for (char ch : sb.toCharArray()) {
map.merge(ch, 1, Integer::sum);
}
map.forEach((k, v) -> System.out.println(k + "\t" + v));
Problem is that as mentioned, String is immutable, so String.replace() just returns a new string and it does not (cannot) modify the original. Either you should use StringBuilder, or store the returned value (e.g. sb = sb.replace(sb.charAt(x),'*');).
Going further, since you initialize c with 0, it will stay 0 if there is no other occurrence of the character in question (sb.charAt(i)), so your algorithm won't detect and print digits that occur only once (because later you only print if c > 0).
Counting occurrences (frequency) of characters or digits in a string is a simple operation, it does not require to create new strings and it can be done by looping over the characters only once.
Here is a more efficient solution (one of the fastest). Since digits are in the range '0'..'9', you can create an array in which you count the occurrences, and by looping over the characters only once. No need to replace anything. Order of occurrence is "remembered" in another order char array.
char[] order = new char[10];
int[] counts = new int[10];
for (int i = 0, j = 0; i < sb.length(); i++)
if (counts[sb.charAt(i) - '0']++ == 0)
order[j++] = sb.charAt(i); // First occurrence of the digit
And print in order, until the order array is filled:
System.out.println("Number\tFrequency");
for (int i = 0; order[i] != 0; i++)
System.out.println(order[i] + "\t" + counts[order[i] - '0']);
Example output:
Enter an integer number
56464
Number Frequency
5 1
6 2
4 2
For completeness here's the complete main() method:
public static void main(String[] args) {
System.out.println("Enter an integer number");
String sb = new Scanner(System.in).nextLine();
char[] order = new char[10];
int[] counts = new int[10];
for (int i = 0, j = 0; i < sb.length(); i++)
if (counts[sb.charAt(i) - '0']++ == 0)
order[j++] = sb.charAt(i); // First occurrence of the digit
System.out.println("Number\tFrequency");
for (int i = 0; order[i] != 0; i++)
System.out.println(order[i] + "\t" + counts[order[i] - '0']);
}
Note:
If you would want to make your code safe against invalid inputs (that may contain non-digits), you could use Character.isDigit(). Here is only the for loop which is safe against any input:
for (int i = 0, j = 0; i < sb.length(); i++) {
char ch = sb.charAt(i);
if (Character.isDigit(ch)) {
if (counts[ch - '0']++ == 0)
order[j++] = ch; // First occurrence of ch
}
}
This should be a good code to print frequency using user input:
public static void main(String args[])
{
System.out.println("Please enter numbers ");
String time = in.nextLine(); //USER INPUT
time = time.replace(":", "");
char digit[] = {time.charAt(0), time.charAt(1), time.charAt(2), time.charAt(3)};
int[] count = new int[digit.length];
Arrays.sort(digit);
for (int i = 0; i < digit.length; i++)
{
count[i]++;
if (i + 1 < digit.length)
{
if (digit[i] == digit[i + 1])
{
count[i]++;
i++;
}
}
}
for (int i = 0; i < digit.length; i++)
{
if (count[i] > 0)
{
System.out.println(digit[i] + " appears " + count[i]+" time(s)");
}
}
}
The point of this program is to take a three digit number from the command line and then reversing it. After that it is supposed to subtract the reverse from the original number and add the original to the reversed.
This is supposed to only take numbers that are three digits and the first digit of the number has to be greater than the last so that it is not negative when the numbers are subtracted.
The code compiles correctly but when I put a number in the command line prints out the line "Enter a three digit number, with the first digit larger than the third" only.
What it is supposed to print out like
$ java Rev 351
Reverse and subtract:
351
153 -
---
198
Reverse and add:
198
891 +
---
1089
This is my code:
public class Rev
{
public static void main(String[] args)
{
int num = 0;
for (int i = 0; i < args.length; i++)
{
System.out.println("Enter a three digit number, with the first digit larger than the third");
num = Integer.parseInt(args[i]);
reverseNum(num);
subtractNum(num);
addNum(num);
}
}
static boolean checkDigits(int number) // checks if numbers are correct
{
int reverse = reverseNum(number);
if(number > reverse)
{
throw new Error("Reverse number needs to be less than the original number!");
}
else
{
return true;
}
}
static int reverseNum(int number) //reverses number
{
int reverse = 0;
int r = 0;
while (number != 0)
{
if(number < 1000 || number > 99)
{
r = number % 10;
reverse = (reverse*10) + r;
number = number/10;
}
}
return reverse;
}
static void subtractNum(int number) // subtracts
{
int reverse = reverseNum(number);
int total = number - reverse;
System.out.println("Reverse and subtract: ");
System.out.println(number);
System.out.println(reverse + " - ");
System.out.println("---");
System.out.println(total);
System.out.println();
number = total;
}
static void addNum(int number) // adds
{
int reverse = reverseNum(number);
int total = number + reverse;
System.out.println("Reverse and add: ");
System.out.println(number);
System.out.println(reverse + " + ");
System.out.println("---");
System.out.println(total);
number = total;
}
}
public static void main(String[] args)
{
int num = 0;
for (int i = 0; i < args.length; i++)
{
System.out.println("Enter a three digit number, with the first digit larger than the third");
num = Integer.parseInt(args[i]);
reverseNum(num);
subtractNum(num);
addNum(num);
}
}
So the args variable is the command line argument. So if you're compiling via command line, you would call something like java Rev.class 321 where 321 is your 3 digit number. If you want to use the Java console to take inputs, use a Scanner.
To take inputs, use something like this:
Scanner sc = new Scanner(System.in);
num = sc.nextInt();
You're never actually getting a number from the input. You need to do this in your main():
public static void main(String[] args)
{
int num = 0;
for (int i = 0; i < args.length; i++)
{
System.out.println("Enter a three digit number, with the first digit larger than the third");
try (Scanner s = new Scanner(System.in)){
num = s.nextInt();
}
reverseNum(num);
subtractNum(num);
addNum(num);
}
}
The Scanner reads the main input stream (from the keyboard). Otherwise, when you pass in the argument on the command line, it hasn't yet asked you for the input, and prints out the request for input.
Your other problem is that you don't call checkDigits() after getting your number, so you should probably do a while loop using it until you get a number you'll accept, like this:
public static void main(String[] args)
{
int num = -1;
while (num < 0 || !checkDigits(num)){
System.out.println("Enter a three digit number, with the first digit larger than the third");
try (Scanner s = new Scanner(System.in)){
num = s.nextInt();
}
}
reverseNum(num);
subtractNum(num);
addNum(num);
}
Also, your other methods are incorrect in that they are acting on an input parameter (which is possible for objects but not primitives, and is bad practice in any case).
Instead write them as functions which take in values and return them, then modify your main again to look like this:
public static void main(String[] args)
{
int num = Integer.parseInt(args[0]);
if (checkDigits(num)){
num = subtractNum(num);
addNum(num);
} else {
System.out.println("Enter only a three digit number, with the first digit larger than the third");
}
}