Last entered char to lower case or upper case - java

I have a code. Input character, program stops when I input full stop (.).
So, i want to change my last entered char to lower case if user input upper case, or upper case if user input lower case. So my problem is how to change upper case to lower or lower to upper. I dont know how to find last index.
Example:[g j g k . K] or [k j f G . g]
Scanner input = new Scanner(System.in);
String character = input.nextLine();
while (true) {
String character1 = input.nextLine();
if (character1.equals(".")) {
break;
So, i just made that my progaram stop when user input full stop, and i dont know how to change last entered char to lower or upper case!

String character ="C".toLowerCase();
if you mean String and not char...

Probably you try change input but it is not possible. You have to print every character on output.
You can try something like this:
Scanner input = new Scanner(System.in);
Char lastChar = '';
while (true) {
String character1 = input.nextLine();
if (character1.equals(".")) {
if(isBig(lastChar)) {
print(lowerCase(lastChar));
} else {
print(upperCase(lastChar));
}
break;
}
print(lastChar);
lastChar = character1;
}

Build around the following.
The first two check if the character is upper case or lower case. Next two convert two upper case and lower case respectively.
https://docs.oracle.com/javase/7/docs/api/java/lang/Character.html#isUpperCase(char)
https://docs.oracle.com/javase/7/docs/api/java/lang/Character.html#isLowerCase(char)
https://docs.oracle.com/javase/7/docs/api/java/lang/Character.html#toUpperCase(char)
https://docs.oracle.com/javase/7/docs/api/java/lang/Character.html#toLowerCase(char)
So, it would go something like this. It only converts the last character if it is a letter. If you need the last letter and not the last character, you can easily modify it.
Scanner scanner = new Scanner(System.in);
scanner.useDelimiter("");
List<Character> characters = new ArrayList<>();
while(true){
String token = scanner.next();
if( token.equals(".") ){
break;
}
characters.add(token.charAt(0));
}
for( int i = 0 ; i < characters.size() - 1 ; i++){
System.out.print(characters.get(i));
}
Character lastCharacter = characters.get( characters.size() - 1 );
if( Character.isUpperCase( lastCharacter ) ) {
lastCharacter = Character.toLowerCase(lastCharacter);
}else if( Character.isLowerCase( lastCharacter )) {
lastCharacter = Character.toUpperCase(lastCharacter);
}
System.out.println( lastCharacter );

Related

Hangman: How to compare and replace a dash with a letter found

I am learning Java, I know it exists several solutions on stackoverflow but I am stuck. I am trying to create a basic Hangman.
I would like to know how Could I replace a dash with a letter found?
Here is a demonstration:
The word to search is:no
I enter the letter n
You have 5 attempts.
--
Enter your letter: n
I enter the letter o
You have 4 attempts.
--
Enter your letter: o
Idem.
You have 3 attempts.
--
Enter your letter:
Here is my code:
Scanner input = new Scanner(System.in);
char letter = 0; // declares and initialises letter
String[] words = {"yes", "no"}; // declares and initialises an array of words to guess
String word = words[(int) (Math.random() * words.length)]; // chooses random word
boolean[] found = new boolean[word .length()];
int attempts = 5;
while(attempts > 0){
System.out.println("You have " + attempts + " attempts.");
for(int i=0; i<word.length(); i++) {
if ( found[i] ) {
System.out.print(word.charAt(i));
}
else {
System.out.print('-');
}
}
System.out.println("");
System.out.print("Enter your letter : ");
letter = input.next().charAt(0);
attempts--;
}
I have to add a loop perhaps?
I share you my code here => https://repl.it/repls/PeriodicLegitimateMatrix
You can use the indexOf(char) method in the String class to check whether the character was in the word.
It should look like this:
while (attemps > 0) {
//...
System.out.println("");
System.out.print("Enter your letter : ");
letter = input.next().charAt(0);
int characterPosition = word.indexOf(letter);//use a loop because the character could appear in more than one position in the word
while (characterPosition != -1) {//if indexOf(char) returns -1 it means the char was not found
found[characterPosition] = true;
characterPosition = word.indexOf(letter, characterPosition);//this time search the character starting from the last position to find the next one
}
attempts--;
}

How can I replace certain characters within a String in Java?

I have a program that reads an input (a String) and prints that String reversed. Now, I need to read through the reversed String and replace all of the "A"s with "T"s, the "T"s with "A"s, the "G"s with "C"s and the "C"s to "G"s. So basically, the "complement". I tried to use multiple lines with a replace function but once the "A"s are turned into "T"s, it will replace all of those into "A"s so there are no "T"s at all. How can I replace the characters so that they do not override each other?
Here is my code if it helps! I don't have any functions to get the "complement" yet, but here is what I'm working with.
import java.util.*;
public class DNA {
public static void main(String[] args)
{
System.out.println("Please input a DNA sequence: ");
Scanner read;
read = new Scanner(System.in);
String input = read.next();
String reverse="";
for(int i = input.length() - 1; i >= 0; i--) {
reverse = reverse + input.charAt(i);
}
System.out.println("Here is the reversed sequence: ");
System.out.println(reverse);
}
}
You can convert your reverse string to a char array like this:
char[] charArr = reverse.toCharArray();
Then you can iterate through it and change the characters that you want:
for(int i = 0; i < charArr.length; i++){
if(charArr[i] == 'A'){
charArr[i] = 't';
}
}
At the end you can convert the char array back to a string like this:
String str = new String(charArr);
Here is a code sample that you can try:
import java.util.Scanner;
class DNA {
public static void main(String[] args)
{
System.out.println("Please input a DNA sequence: ");
Scanner read = new Scanner(System.in);
String input = read.next();
String reverse="";
StringBuilder sb = new StringBuilder();
for(int i = input.length() - 1; i >= 0; i--) {
reverse = reverse + input.charAt(i);
}
for (char c: input.toCharArray()) { // user 'reverse' to operate on reversed string
switch (c) {
case 'A' : sb.append('T'); break;
case 'T' : sb.append('A'); break;
case 'G' : sb.append('C'); break;
case 'C' : sb.append('G'); break;
default : sb.append(""); break; // handle you're exceptions here
}
}
System.out.println("x: " + sb);
System.out.println("Here is the reversed sequence: ");
System.out.println(reverse);
read.close();
}}
Well, switch-case is a kind of mapping technique which will map your case (as key) with it's values. In this case:
I am replacing 'A' with 'T' where the string contains 'A' by appending into the StringBuilder (to create a new string) and then break; which is a mandatory statement for single time execution only.
And the default keyword is for default case, which means if all of the cases are unsatisfied to be executed then the default case is called, you can do whatever you want to do by default if no case, condition matched.
Well, for your last question, You can make it generic if the problem states some pattern; if not you, unfortunately have to do it manually.
Use the replace method, but change your values to a "temporary" character. https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replace(char,%20char)
Replace T -> x
Replace A -> T
Replace x -> A
Repeat for all your pairs.

Creating a for loop to detect if there are 2 of the same characters next to eachother

I am trying to figure out how to make a for loop that will detect if there are 2 of the same letters g in this case next to each-other, there will be more than one instance of "g" in the string.
Here's what I have,
Scanner keyboard = new Scanner(System.in);
String a;
a = keyboard.next();
if (a.charAt(a.indexOf(g) + 1 ) == "g"){
for ( ?? ; ?? ; ?? ){
System.out.println("True");
System.out.println("False");
}
}
else System.out.println("False");`
I am not sure of some of the values or concepts I am meant to be using, I am only familiar with most of the basics.
Scanner keyboard = new Scanner(System.in);
String a;
a = keyboard.next();
char[] chararray = a.toCharArray();
char temp = '\0';
boolean repeat = false;
for (char s : chararray) {
if(s==temp)
{
System.out.println("repeat");
repeat = true;
break;
}
temp = s;
}
System.out.println(repeat);
You can try this, without any loop at all:
Scanner keyboard = new Scanner(System.in);
String a;
a = keyboard.next();
if (a.indexOf("gg") != -1)
System.out.println("True");
else
System.out.println("False");
keyboard.close();
I've used indexOf cause if you wanted be able to do something with the position of the occurrence.
And if you're not interested in the position of "gg" in your string (if it occurs) you can just replace a.indexOf("gg") != -1 with a.contains("gg") as Vikiiii said.
Use regular expression to find if there are two of the same characters next to each other.
Just check: https://stackoverflow.com/a/4725079/2182503

Switching letters in a string and recieving an index out of range error in Java

I'm trying to write a program that will input a sentence, and then two letters, and then switch all instances of those letters and then print out the switched sentence. For instance, they could input
I like to eat bananas
and then ā€œeā€ and ā€œa,ā€ and my program would print
I lika to aet benenes
Here is my code, but at the end it prints out String Index out of line.
Any ideas how to fix this?
System.out.println("Write something awesome.");
String input1 = Keyboard.readString();
System.out.println("Pick a letter from that awesome sentence.");
char letter1 = Keyboard.readChar();
System.out.println("Pick another letter from that awesome sentence.");
char letter2 = Keyboard.readChar();
double let1 = (input1.length());
int let1Next = (int) let1;
double let2 = (input1.length());
int let2Next = (int) let2;
String newUserImput = input1.replace(input1.charAt(let1Next),
input1.charAt(let2Next));
System.out.println(newUserImput);
Without a stack trace, I have to guess the exception is on this line.
String newUserImput = input1.replace(input1.charAt(let1Next),
input1.charAt(let2Next));
What does input1.charAt(let1Next) resolve to?
double let1 = (input1.length());
int let1Next = (int) let1;
double let2 = (input1.length());
int let2Next = (int) let2;
This can't really be what you mean.
let1Next will represent the end of the array + 1 as will let2Next.
Therefore, there are 2 major bugs here:
You are replacing all occurrences of a given character with itself.
The letter you are picking is beyond the end of the string. Remember, string indexes (such as the input to String.charAt) are 0-based, so the they range from 0 through (length - 1). By specifying input1.length, you are asking for the character after the last character of the string, hence the StringIndexOutOfBoundsException.
You can iterate over array that contains all characters of user sentence (you can get such array using toCharArray method invoked on input1) and if you find letter1 replace it with letter2 and vice-versa.
After that you can create new string based on updated array with new String(arrayOfCharacters).
The method replace will replace all chars in the string
So what you want is
String new1 = input1.replace (letter1, letter2);
String new2 = input1.replace (letter2, letter1);
Then iterate over the original string to see what is different in new1 and new2.
Try using char array-
char letter1 = 'a';
char letter2 = 'e';
String s = "I like to eat bananas";
char[] chrs = s.toCharArray();
int n = chrs.length;
for (int i = 0; i < n; i++) {
if (chrs[i] == letter1) {//if array contains letter1 at intdex i
chrs[i] = letter2; //replace with letter 2
} else if (chrs[i] == letter2) { //if array contains letter2 at intdex i
chrs[i] = letter1;//replace with letter 1
}
}
String swapedString = new String(chrs);
System.out.println(swapedString );
try with this.
char[] cs = input1.toCharArray();
for (int i = 0; i < cs.length; i++) {
char c = cs[i];
if (letter1 == c) {
cs[i] = letter2;
} else if (letter2 == c) {
cs[i] = letter1;
}
}
String newUserImput = new String(cs);
You are getting String index out of line because you tried to access characters outside of the string (valid range is from 0 to length-1). And even if you used length-1, your code will not do what you want. What you really need is to have two dummy placeholders (I assume your string will never contain '#' or '$') replacing 'a' and 'e' and then swap 'a' and 'e' with the dummy placeholders. The code follows:
System.out.println("Write something awesome.");
String input1 = "I like to eat bananas";//Keyboard.readString();
System.out.println("Pick a letter from that awesome sentence.");
char letter1 = 'e';
System.out.println("Pick another letter from that awesome sentence.");
char letter2 = 'a';
// dummy placeholders
char letter3 = '#';
char letter4 = '$';
String newUserImput = input1.replace (letter1, letter3);
newUserImput = newUserImput.replace (letter2, letter4);
newUserImput = newUserImput.replace (letter3, letter2);
newUserImput = newUserImput.replace (letter4, letter1);
System.out.println(newUserImput);

Java: console skipping input

I'm trying to parse a char from console input using in.nextLine() and from there take charAt(0). My problem is after asking the user to enter a string to perform the in.nextLine() on, it skips the input and yields an error due to trying to get the first character of a null string.
System.out.print("Select an operator (+, -, *, /), 'c' or 'C' to clear, or 'q' to quit: ");
String temp = in.nextLine();
char tempOperator = temp.charAt(0);
the error is
java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(Unknown Source)
full program is available here
General comments and suggestions always welcome.
Thanks in advance.
When you do cValue = in.nextDouble();, it reads the next token(full value) and parses it to double. If the return key was pressed at this time, \n is the next token in the buffer to read.
When you do: String temp = in.nextLine();, it reads the \n from the buffer of the previous enter and charAt(0) fails as it has read only empty("") string.
To overcome the issue, either skip the previous buffer by adding an addition in.nextLine(), add \n \r as skip pattern as below (this is the pattern defined in Scanner.class as LINE_SEPARATOR_PATTERN):
in.skip("\r\n|[\n\r\u2028\u2029\u0085]");
or put a small while loop as below:
String temp = "";
while((temp.length() < 0){
temp = in.nextLine();
}
One thing you might consider is instead of doing this:
String temp = in.nextLine();
Do this:
String temp = in.next();
That of course is assuming that you only want a single character from the user input, which it looks like that is all you are asking the user for. This will get rid of the exception you are receiving. However, you may want to read the whole line first to see what the length is, if you would like to throw an error when the user types more than one character.
Well, the problem is in the line in.nextDouble().
Scanner#nextDouble reads the next token from the user as double. So, when you pass a value 4.5 as input, then the nextDouble just reads the token 4.5 and skips the linefeed after that input that user have entered. Now this linefeed(Since this is a new line), will be regarded as input for the next Scanner.nextLine. And hence your in.nextLine after in.nextDouble is reading the newline left over by the previous in.nextDouble.
So, the workaround is the same that #tjg184 has pointed out in his answer. Add an empty in.nextLine after in.nextDouble that will read that newline left over. So, that your coming in.nextLine reads the input actually passed.
cValue = in.nextDouble();
in.nextLine(); // Add this before your `while` which will read your `newline`
while (true) {
//continue;
}
Whereas, Scanner.nextLine reads the complete input till the newline. So, it will not leave any newline to be read by the next read by user.
Although this answer was not needed, as the #tjg184's answer does the same. I just added it to give a better explanation of what exactly is happening.
Looking at your program, it's because of String temp = in.nextLine();. When the user hits the "Enter" key, it essentially is skipping this statement since the user typed hit "Enter". Try the following. Note, I only added the following line String enter = in.nextLine();
import java.util.Scanner;
public class Calculator
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
char operator = 'z'; //initialize operator
double cValue; //current value
double rhValue; //right hand value
boolean cont = true;
System.out.print("Enter starting value: ");
cValue = in.nextDouble();
// disregard the "Enter" key
String enter = in.nextLine();
while(true)
{
System.out.print("Select an operator (+, -, *, /), 'c' or 'C' to clear, or 'q' to quit: ");
String temp = in.nextLine();
char tempOperator = temp.charAt(0);
if (tempOperator == 'c' || tempOperator == 'C')
{
cValue = 0.0;
System.out.println("Current value is: " + cValue);
System.out.println();
}
else if(tempOperator == 'q')
{
System.out.println("Final result: " + cValue);
System.exit(1);
}
else if(tempOperator == '+' || tempOperator == '-' || tempOperator == '*' || tempOperator == '/')
{
operator = tempOperator;
break;
}
else
throw new IllegalArgumentException("operator not valid");
}
System.out.println("Enter a right hand value (type double): ");
rhValue = in.nextDouble();
System.out.println("Math expression: answer " + operator + "= " + rhValue);
switch(operator)
{
case '+': cValue =+ rhValue;
break;
case '-': cValue =- rhValue;
break;
case '*': cValue = cValue * rhValue;
break;
case '/': cValue = cValue / rhValue;
break;
}
System.out.println("Current value is: " + cValue);
}
}

Categories

Resources