How to make equals read a character - java

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

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

frequency of a letter in a string using arrays

In this program I have been having trouble to get the terminal window I suspect it might be a runtime error .I am using blue J btw. Also I dont understand why the code used this
f[ch-'A']++;
Please help out with a tracing for this program.
This is the code:
import java.util.*;
public class frequency
{
public static void main(String args[])
{
Scanner sc= new Scanner(System.in);
int f[]= new int[26];
System.out.println("enter a string");
String input = sc.nextLine();
input= input.toUpperCase();
for(int i=0; i<input.length();i++)
{
char ch=input.charAt(i);
if (Character.isLetter(ch))
f[ch-'A']++;
}
System.out.println("Characters Frequency");
for(int i=0;i<26;i++)
{
if( f[i]!=0)
{
System.out.println((char) (i+'A') + "\t\t" + f[i]);
}
}
}
}
Because it is converting the text to uppercase
input= input.toUpperCase();
each char can have the ascii value of A subtracted (see https://www.asciitable.com/) to obtain an index into the array.
'B' - 'A' == 1 etc
test
enter a string
stupid sod
Characters Frequency
D 2
I 1
O 1
P 1
S 2
T 1
U 1

How do I print a letter based on the index of the string?

I want to print a letter instead of the index position using the indexOf(); method.
The requirement is that: Inputs a second string from the user. Outputs the character after the first instance of the string in the phrase. If the string is not in the phrase, outputs a statement to that effect. For example, the input is 3, upside down, d. The output should be "e", I got part of it working where it inputs an integer rather than a string of that particular position. How would I output a string?
else if (option == 3){
int first = 0;
String letter = keyboard.next();
first = phrase.indexOf(letter,1);
if (first == -1){
System.out.print("'"+letter+"' is not in '"+phrase+"'");
}
else {
System.out.print(first + 1);
}
}
String.charAt(index)
You can access a single character, or a letter, by caling método charAt() from String class
Example
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String phrase = keyboard.nextLine();
char firstLetter = phrase.charAt(0);
System.out.println("First Letter : " + firstLetter);
}
So, running this code, assuming the input is StackOverFlow, the output will be S
In your code I think doing the follow will work:
Your Code
String letter = keyboard.next();
first = letter.charAt(0);
That might help!
Based on those comments
So, what you want is print the first letter based on a letter the user
has input? For example, for the word Keyboard, and user inputs letter
'a' the first letter might be 'R'. Is that it? – Guerino Rodella
Yes, I have to combine both the indexOf(): method and the charAt():
method – Hussain123
The idea is get next letter based on user input letter.
I'm not sure I wunderstood it, but this is my shot
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String phrase = "keyboard";
String userInput = keyboard.nextLine();
boolean notContainsInputValue = !phrase.contains(userInput);
if (notContainsInputValue) {
System.out.println("The input value doesn't exists");
return;
}
char firstLetter = userInput.charAt(0);
int desiredIndex = 0;
for (int i = 0; i < phrase.length(); i++) {
if (phrase.charAt(i) == firstLetter) {
desiredIndex = i;
break;
}
}
System.out.println("The index for your input letter is: " + desiredIndex);
System.out.println("Next letter based on input value is: " + phrase.charAt(desiredIndex + 1));
}
The Output
The index for your input letter is: 5
Next letter based on input value is: r
Hope that helps you.

Changing single chars to upper or lower case depending on user input in Java

I have tried to find guidance on this, but I keep getting solutions on an entire string, or a single character. I am in my 4th week of Java, and have hit a roadblock.
I have to ask a user to input three letters ("Enter three letters: abc"). Depending on which case they type, I have to write a program that swaps upper with lower and visa versa. For example, if the user types "aBc", my output will be "AbC".
This is what I have so far. If my code is horrible, I'm sorry. I'm learning as I go.
import java.util.Scanner;
public class LowerUpper {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter three letters: ");
String letters = input.nextLine();
for (int i = 0; i < letters.length(); i++) {
char letter1 = letters.charAt(0);
char letter2 = letters.charAt(1);
char letter3 = letters.charAt(2);
if (Character.isUpperCase(letters.charAt(0)) == true)
System.out.println(Character.toLowerCase(letter1));
else {
System.out.println(Character.toUpperCase(letter1));
}
if (Character.isUpperCase(letters.charAt(1)) == true)
System.out.println(Character.toLowerCase(letter2));
else {
System.out.println(Character.toUpperCase(letter2));
}
if (Character.isUpperCase(letters.charAt(2)) == true)
System.out.println(Character.toLowerCase(letter3));
else {
System.out.println(Character.toUpperCase(letter3));
}
}
}
}
When I typed "abc" for the input, the output was:
A
B
C
A
B
C
A
B
C
The format of the output is supposed to be "Result: ABC". I can work on that later. I'm just trying to figure out how to get this to execute correctly. My hunch is that I'm definitely going wrong on my if/else statements. I do not know how to print the changed chars all in a row (abc, AbC, ABC, etc). I thought I did it correctly at the beginning with the indexing of the string (0,1,2).
By the way, it's not showing my output correctly this forum. It is supposed to be one letter per line, not "ABCABCABC", if I made sense with that.
The reasoning for this is because it's inside of a for loop, which is essentially worthless, because you are never using the integer 'i'. If you remove the for loop, it should only execute once, thus for outputting "ABC", instead of "A B C A B C A B C". To print the chars in a row, you can simply append each character to a string, and then output that.
The biggest issue I see is that you've got a loop going over the length of the string but you're not using the loop index i to reference the individual characters. In short, you're trying too hard and overlooking the obvious.
Wouldn't this do the trick?
for (int i = 0; i < letters.length(); i++) {
char letter1 = letters.charAt(0);
if (Character.isUpperCase(letter1)) {
System.out.println(Character.toLowerCase(letter1));
} else {
System.out.println(Character.toUpperCase(letter1));
}
}
The reason why you get a redundant printing 'coz you loop the three variables which already contain all characters.
To solve your problem. just remove the for loop. 'coz you already
store each character to the three variables.
You code will look like this now:
import java.util.Scanner;
public class LowerUpper {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter three letters: ");
String letters = input.nextLine();
char letter1 = letters.charAt(0);
char letter2 = letters.charAt(1);
char letter3 = letters.charAt(2);
if (Character.isUpperCase(letters.charAt(0)) == true)
System.out.println(Character.toLowerCase(letter1));
else {
System.out.println(Character.toUpperCase(letter1));
}
if (Character.isUpperCase(letters.charAt(1)) == true)
System.out.println(Character.toLowerCase(letter2));
else {
System.out.println(Character.toUpperCase(letter2));
}
if (Character.isUpperCase(letters.charAt(2)) == true)
System.out.println(Character.toLowerCase(letter3));
else {
System.out.println(Character.toUpperCase(letter3));
}
}
}
Ok, here is my new code. It compiled with no errors and the output was just as it was supposed to be:
import java.util.Scanner;
public class LowerUpper {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter three letters: ");
String letters = input.nextLine();
char letter1 = letters.charAt(0);
char letter2 = letters.charAt(1);
char letter3 = letters.charAt(2);
if (Character.isUpperCase(letters.charAt(0)) == true)
System.out.print("Result: " + Character.toLowerCase(letter1));
else {
System.out.print("Result: " + Character.toUpperCase(letter1));
}
if (Character.isUpperCase(letters.charAt(1)) == true)
System.out.print(Character.toLowerCase(letter2));
else {
System.out.print(Character.toUpperCase(letter2));
}
if (Character.isUpperCase(letters.charAt(2)) == true)
System.out.print(Character.toLowerCase(letter3));
else {
System.out.print(Character.toUpperCase(letter3));
}
}
}
The problem is that you have a loop then do each letter individually. So get rid of the loop. It would look better if you re-wrote it with a loop but only had one if/else statement inside the loop based on i not 0,1&2.
Replace your for loop with:
System.out.println(letters.toUpperCase());

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

Categories