string methods - replace(oldChar,newChar) - java

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);
}

Related

Java question for scan a binary number using while loops

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).

Function to detect numerical palindromes not working as expected

I'm a beginner in programming. Can you please tell me what's wrong with my code? The code shows not palindrome, although the number is a palindrome.
public static void main(String[] args) {
// TODO code application logic here
Scanner in = new Scanner(System.in);
int a =0;
int n =in.nextInt();
while(n >0){
int temp =n %10;
a = a*10+temp;
n = n/10;
}
System.out.println(a);
if( n ==a){
System.out.println("The number is palindrome");
}else{
System.out.println("The number is not palindrome");
}
}
Output:
16461
16461
The number is not palindrome
Your code works, except for the fact that you are not keeping the original value intact to compare it with the reversed number you compute. This works for your input value by saving a copy of your original input, and using that at the end to compare with what you compute:
public static void main(String[] args) {
// TODO code application logic here
Scanner in = new Scanner(System.in);
int a = 0;
int n = in.nextInt();
int orign = n;
while(n >0){
int temp = n %10;
a = a*10+temp;
n = n/10;
}
System.out.println(a);
if( orign == a){
System.out.println("The number is palindrome");
}else{
System.out.println("The number is not palindrome");
}
}
Sample sessions:
16461
16461
The number is palindrome
12345
54321
The number is not palindrome
3
3
The number is palindrome

Why won't my code take the input from the command line?

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");
}
}

Certain phrases with numbers dont multiply by 2

Hi There so I have a project that basically finds all numbers i have and multiplies them by 2. I have it like 90% done but for the other 10% certain inputs don't work.
So my code finds all the numbers in a user input and multiplies them by 2.
(eg. 123woah becomes 246woah and woah888 becomes woah1776)
Can anyone find my error and explain to me what i need to do?
EDIT: For example a case that doesn't work is like 1abc1. The code doesn't work if the numbers are in different spots.
Thanks
import java.util.Scanner;
public class MultiplyBy2
{
public static void main(String[] args)
{
int EXIT = 0;
while(EXIT == 0)
{
Scanner kbReader = new Scanner(System.in);
System.out.println("input?");
String String1 = kbReader.nextLine();
if(String1.equalsIgnoreCase("exit"))
{
break;
}
else
{
String String2 = String1;
String1 = String1.replaceAll("\\D", "");
int i = Integer.parseInt(String1);
int j = i * 2 ;
String2 = String2.replaceAll("" + i, "" + j);
System.out.println(String2);
}
}
}
}
Here you go:
String String1="1abc1"; // or woah888
Pattern p = Pattern.compile("-?\\d+");
Matcher m = p.matcher(String1);
while (m.find()) {
Integer temp=Integer.parseInt(m.group());
Integer temp2=temp*2;
String1=String1.replaceFirst(temp.toString(),temp2.toString());
}
System.out.println(String1);
Demo
You can try this.
String text = "123.0114cc";
String numOnly = text.replaceAll("\\p{Alpha}","");
double numVal = Double.valueOf(numOnly);
double newVal=numVal*2;
text=text.replaceFirst(String.valueOf(numVal),String.valueOf(newVal));
System.out.println(text);
Out put:
246.0228cc

Scanner only reading first set of input

This is a code I have developed to separate inputs by the block (when a space is reached):
import java.util.Scanner;
public class Single {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.println("Three Numbers:");
String numbers = in.next();
int length = numbers.length();
System.out.println(length);
int sub = length - length;
System.out.println(sub);
System.out.println(getNumber(numbers, length, sub));
System.out.println(getNumber(numbers, length, sub));
System.out.println(getNumber(numbers, length, sub));
}
public static double getNumber(String numbers, int length, int sub){
boolean gotNumber = false;
String currentString = null;
while (gotNumber == false){
if (numbers.substring(sub, sub + 1) == " "){
sub = sub + 1;
gotNumber = true;
} else {
currentString = currentString + numbers.substring(sub, sub);
sub = sub + 1;
}
}
return Double.parseDouble(currentString);
}
}
However, it only reads the first set for the string, and ignores the rest.
How can I fix this?
The problem is here. You should replace this line
String numbers = in.next();
with this line
String numbers = in.nextLine();
because, next() can read the input only till the first space while nextLine() can read input till the newline character. For more info check this link.
If I understand the question correctly, you are only calling in.next() once. If you want to have it process the input over and over again you want a loop until you don't have any more input.
while (in.hasNext()) {
//do number processing in here
}
Hope this helps!

Categories