Certain phrases with numbers dont multiply by 2 - java

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

Related

If condition is met -> scan input into one variable. If not -> scan input into another variable

Scanner input = new Scanner(System.in)
System.out.print("Enter either a string or a number");
String str = input.nextLine();
int x = input.nextInt();
The program here expects 2 values, a string and an integer. YET there is only one.
I want str to register the value if it is a string, BUT if it is an integer, I want the value to be registered by x
In other words, I only want one of the variables to be active
if the value of entered is an integer, then you can simply use regex where
if(str.matches("\\d+") || str.matches("-\\d+"))
checks if the entered number is a number of 1 or more digits or the entered number is a negative number with one or more digits
and if that is the case, then you can x = Integer.parseInt(str); to convert that entered string into integer and make str = ""; otherwise , the entered string is stored in str and never parsed to int
and this is the edited code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter either a string or a number\n");
String str = input.nextLine();
int x = 0;
if(str.matches("\\d+") || str.matches("-\\d+"))
{
x = Integer.parseInt(str);
str = "";
}
else
{
// nothing to do
}
System.out.println("x = " + x);
System.out.println("str = " + str);
}
}
and this is some example output:
Enter either a string or a number
10
x = 10
str =
Enter either a string or a number
test
x = 0
str = test
Enter either a string or a number
-30
x = -30
str =
Enter either a string or a number
test10
x = 0
str = test10
The answer provided by abdo and the comment by Jesse are both valid and very good answers.
However it is also possible to achieve your goal with the Scanner methods. In this case hasNextInt() is your friend.
f
But note, that nextLine() will consume the line break, while nextInt() will not. IMHO it will be more clear to code both options alike and use next() instead.
The most simple approach:
if (input.hasNextInt()) {
x = input.nextInt();
}
else {
str = input.next();
}
input.nextLine(); // consume the line break, too
Here still one issue remains: By default Scanner uses whitespace as delimiter, not line breaks. With the input "4 2\n" nextInt() will return 4 and nextLine() will discard the rest. However the user's intention (number versus string) is not obvious in this case either, therefor I'd tend to create the string "4 2" instead. This can easily be achieved by using line breaks as delimiter instead:
Scanner input = new Scanner(System.in).useDelimiter(System.lineSeparator());
A full demo example:
import java.util.Scanner;
public class ScannerExample {
public static void main(String[] args) {
Scanner input = new Scanner(System.in).useDelimiter(System.lineSeparator());
System.out.println("Enter either a string or a number");
String str = null;
while (!"end".equals(str)) {
int x = 0;
str = null;
if (input.hasNextInt()) {
x = input.nextInt();
}
else {
str = input.next();
}
input.nextLine();
if (str != null) {
System.out.printf("we have a string! str=%s%n", str);
}
else {
System.out.printf("we have a number! x=%d%n", x);
}
}
System.out.println("goodbye!");
}
}

Multiply single character by given number in String

I have one goal:
1) Multiply character in String n-times (character, String, n [int] - from user input)
Example:
User input1 (String) : future
User input2 (char) : u
User input3 (int) : 2
Output: fuutuure
First i tried with char[] array but IndexOutOfBoundsException brought me back to reality. Second try-StringBuilder but its not working aswell-empty result window. Should I use StringBuilder (and if answer is yes-how?) ? Or there is other, better solution.
Thank you for help.
package Basics.Strings;
import java.util.Scanner;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class Ex4 {
static String giveAWord() {
Scanner scanWord = new Scanner(System.in);
System.out.println("Give a word");
String word = scanWord.nextLine();
return word;
}
static char giveALetter() {
Scanner scanALetter = new Scanner(System.in);
System.out.println("Give a letter");
char let = scanALetter.next().charAt(0);
return let;
}
static int giveANumber() {
Scanner scanNumber = new Scanner(System.in);
System.out.println("Give a number");
int numb = scanNumber.nextInt();
return numb;
}
static String multiplyLetter(String word, char letter, int number) {
StringBuilder sb= new StringBuilder();
for (int i = 0; i < sb.length(); i++) {
if (sb.charAt(i)==letter) {
sb.append(i*number);
}
}
return sb.toString();
}
public static void main(String[] args) {
String word = giveAWord();
char letter = giveALetter();
int number = giveANumber();
System.out.println(multiplyLetter(word, letter, number));
}
}
There are several things in your multiplyLetter method that would make it not work.
First, you have to initialise the StringBuilder using the word so:
StringBuilder sb = new StringBuilder(word) ;
Else, your StringBuilder will be empty.
Second, you should use the insert(int pos, char c) method, so you can specify where you want tthe character inserted.
And last, you can't just multiply a char and an int and get away with it. If you want to repeatedly insert a character, I think you should use a loop.
So, in summary, try:
StringBuilder sb= new StringBuilder(word);
for (int i = 0; i < sb.length(); i++) {
if (sb.charAt(i)==letter) {
for ( int j = 0 ; j < number ; j++ ) {
sb.insert(i, letter);
i++ ;
}
}
}
Notice I added i++ inside the loop, as sb.length() will increase with each character inserted.
Also, maybe someone more experienced can provide with a more efficient way than just using a loop.
If you are using at least Java 11 (eleven) then the following will work:
String word = "future";
String letter = "u";
int count = 2;
String replacement = letter.repeat(count);
String result = word.replace(letter, replacement);
Note that only method repeat(int) was added in Java 11.
Method replace(CharSequence, CharSequence) was added in Java 5
Java 8 functional way:
String alterString(String input, Character charMatch, int times) {
return input.chars()
.mapToObj(c -> (Character) c) // converting int to char
.flatMap(c -> {
if (c == charMatch) {
Character[] ca = new Character[times];
Arrays.fill(ca, c);
return Arrays.stream(ca); // stream of char c repeated 'times' times
}
return Stream.of(c);
})
.collect(
// following is the string collecting using StringBuilder form stream of characters
Collector.of(
StringBuilder::new,
StringBuilder::append,
StringBuilder::append,
StringBuilder::toString,
);
);
}
A simple way to solve this problem is by using the following functions:
String#join
Collections#nCopies
String#replace
Demo:
import java.util.Collections;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.print("Enter the string: ");
String str = kb.nextLine();
System.out.print("Enter the character: ");
String ch = kb.nextLine();
System.out.print("How many times to repeat?: ");
int n = kb.nextInt();
String result = str.replace(ch, String.join("", Collections.nCopies(n, ch)));
System.out.println("Result: " + result);
}
}
A sample run:
Enter the string: future
Enter the character: u
How many times to repeat?: 2
Result: fuutuure

string methods - replace(oldChar,newChar)

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

How to make equals read a character

So what I need help on is that I have this code and I do not know how the if statements can read ",", ".", and "$". I think the String X should be Char instead of String but I do not know how I could change my String X = in.next(); with char[] arr = new char[] and this statement need to be as an input statement! Thank you for helping me and after answering could you write what kinds of things I could do to make my questions better?
So what this code is supposed to do is that for example input is say &&&&&& and 456 then the output is supposed to be*** 456 so meaning &&&&&& = ** and as many numbers there are meaning length the 's go away so * -> ***456
and if input contains "," for example input is &&&,&&&&&(anywhere is fine for ",") and 10000 then output is 10,000 and so on with "." that puts decimal point where it is placed and round up to that point and "$" just puts a dollar sign in front of the numbers
import java.util.Scanner;
public class printFormatting
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Enter the &'s and ,'s");
String X = in.next();
System.out.println("Enter the numbers");
String Y = in.next();
int lengthX = X.length();
int lengthY = Y.length();
if (X.equals(",") && X.equals("."))
{
System.out.println("Works , && .");
//This is to see if , and . both are being able to be seen by the code
}
else if (X.equals(","))
{
System.out.println("Works ,");
//This is to see if , can be seen
}
else if (X.equals("."))
{
System.out.println("Works ,");
//same
}
if (X.equals("$"))
{
System.out.println("Works $");
}
for (int z = lengthX-lengthY; z > 0;)
{
System.out.print("*");
z--;
}
System.out.println(Y);
}
}

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