I'm trying to take a string from a user input using a scanner, and evaluate each character and add 2 to its ASCII value, if I put input of abc, I would like it to output cde. I tried the code below, and got a cannot convert char to int error.
String inputString;
System.out.println("Input: ");
Scanner sc = new Scanner(System.in);
inputString = sc.nextLine();
sc.close();
int len=inputString.length();
char[] c = inputString.toCharArray();
for(int i = 0; i < len; i++)
{
c[i] +=2;
c = inputString.toCharArray();
}
System.out.println(c);
}
You cannot just write += 2 with an array (of any kind) and have Java change the whole array. You will have to do something like
for (int i = 0; i < len; i++) {
name[i] += 2;
}
Additionally, you are initializing every character in name to the first character of the input string, so it will just be {'a', 'a', 'a'}. You should either change the initialization to be name[i] = inputString.charAt(i), or just make name = inputString.toCharArray() to do it all in one go.
Finally, you cannot print arrays in Java like you're trying to do. You'll need to write something like System.out.println(String.valueOf(name)).
Related
ı am new in java.here is my code. I determined my String array size with nextint metod using Scanner. Then ı have added Strings with nextline metod. it seems correct for me but ı cant see my first value of array. what is the problem in this code.
public class App {
public static void main(String[] args) {
String[] arr;
Scanner sc = new Scanner(System.in);
System.out.println("write a number ");
int n = sc.nextInt();
arr = new String[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextLine();
}
System.out.println(arr[0]);
}
}
You can see the first entry, it just happens to be a blank String.
The reason this happens is that when you call int n = sc.nextInt(); and user presses Enter, the Scanner reads the integer, but leaves the end-of-line character in the buffer.
When you read the first string with sc.next() the end-of-line "leftover" gets scanned right away, and gets presented to your program as the first String which is blank.
The fix to this problem is simple: call sc.next() after sc.nextInt(), and ignore the result.
Instead of
for (int i = 0; i < n; i++) { arr[i] = sc.nextLine(); } System.out.println(arr[0]);
Do
arr[0] = sc.nextLine();
for (int i = 0; i < n; i++) { arr[i] = sc.nextLine(); } System.out.println(arr[0]);
This is a bug that occurs when using nexLine() after nextInt() because nextInt() doesn't pull the \n from the input stream buffer, so when you invoke nextLine() it consumes just the \n character (nextLine() is implemented to consume characters until it meets a \n)
I have been working on this problem for two days now and have no idea where I'm going wrong.
Essentially I need to ask a user for a string of words.
I need to set up an int array of 26 elements that holds the count of lower case letters and one for upper case letters.
I can't get the program to compare with the array elements properly. This is my code so far:
public class Lab17Array {
public static void main(String[] args)
{
Scanner kb = new Scanner (System.in);
int lLetter = 0;
int uLetter = 0;
// int[] alph = new int [26];
int alph [] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
int Alph [] = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
System.out.println("Enter a phrase");
String user = kb.nextLine();
// to print out length of word
System.out.println("Total number of letters is " + user.length());
for(int i = 0; i < user.length(); i++)
{
}
System.out.println("Upper case letters are:" + uLetter);
System.out.println("Lower case letters are:" + lLetter);
int otherL = user.length() - (uLetter + lLetter);
// to print out other chars that aren't letters
System.out.println("Number of all other letters is " + otherL );
}
}
Inside my for loop is where I've been trying different if conditions. I have no idea what I'm missing?
Using an Array
You could use String.toCharArray() and a for-each loop to iterate your userInput (you seem to have changed the variable name between your post, and your comment). Regardless, something like
for (char ch : user.toCharArray()) {
if (Character.isLowerCase(ch)) {
lLetter++;
} else if (Character.isUpperCase(ch)) {
uLetter++;
}
}
Using Regular Expression(s)
You could reduce your code by using a regular expression to remove all non-lowercase characters from the input and another to remove all non-uppercase characters from the input like
int lLetter = user.replaceAll("[^a-z]", "").length(); // <-- removes everything not a-z
int uLetter = user.replaceAll("[^A-Z]", "").length(); // <-- removes everything not A-Z
Try this
int upperCount = 0;
int lowerCount = 0;
Scanner sc = new Scanner(System.in);
String w = sc.nextLine();
for(int i = 0; i < w.length(); i++){
if(Character.isUpperCase(w.charAt(i))){
upperCount++;
}else{
lowerCount++;
}
}
System.out.println("Upper Counts are "+upperCount+" lower counts are "+lowerCount);
Try this.
for(int i = 0; i < user.length(); i++)
{
int ch = user.charAt(i);
if (Arrays.binarySearch(alph, ch) >= 0)
++lLetter;
if (Arrays.binarySearch(Alph, ch) >= 0)
++uLetter;
}
I need to load in a given String which will be type in as an input String:
20 6
....................
..XXXXX..XXX.XXX..X.
..X.X.X..X.XXX.X..X.
..XXXXX..XX.X..X....
..XX......XXXXXX..X.
....................
something like that. It contains 2 integers and a String with "." and "X"
Now I just want to ask 2 questions:
1)I need to load the 2 integers first,but how can get the first two integers by BufferedReader?(the 2 int is divide by space between each other and the rest)
2)Then after loading the two integers,how can I load the following rest string char by char?(Like everytime I need to just load one char,then I go to some function,then come back and load the next char;and between there is no blank space)
Here is part of my code:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str=br.readLine();
number1 = Integer.parseInt();
number2 = Integer.parseInt();
And now I don't know how to continue...Anyone can help me to load it?
For 1) you just need to do a split
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str=br.readLine();
String ints[] = str.split(" ");
number1 = Integer.parseInt( ints[0] );
number2 = Integer.parseInt( ints[1] );
Then for 2) once you have a String you can have it length and so get them char by char ;)
String lol = "......XXX..XX...";
for( int i = 0; i < lol.length(); i++ )
System.out.println(lol.charAt(i));
With this you will get all your string char by char
It is much better if you use Scanner then you can read int and the String easier.
I suppose you input two integers as col and row.
Example like this:
Scanner scan = new Scanner(System.in);
int col = scan.nextInt();
int row = scan.nextInt(); //input two int first
scan.nextLine();
for(int i = 0; i < row; i++) {
String s = scan.nextLine();
for(int j = 0; j < col; j++) {
char c = s.charAt(j);
//your code here
}
}
We are asked to do the following:
Receive the first names of your family members (between 3 to 6 members of your family), create an array of String.
Write a static method called generateNewName() as following:
It receives the array of String as a parameter.
It creates a new first name by using the 2nd character of each String from the array
Example: If you enter as first names Rocky, Ashley, Ocarina, Baron, Ernest, the resulting name should be oscar.
Display the names that were entered and newly generated name
This is what I have:
import java.util.Arrays;
import java.util.Scanner;
public class Foothill {
static Scanner input;
public static void main(String[] args) {
input = new Scanner (System.in);
String[] getNames = new String[5];
char Output;
Output = generateNewName(getNames);
System.out.println(Output);
for(int x = 0; x < 5; x++){
System.out.println("Enter 5 names: ");
getNames[x] = input.nextLine();
}
}
public static char generateNewName(String[] getNames)
{
String newS = Arrays.toString(getNames);
char result = '\0';
for(int j = 0; j < getNames.length; j++){
result = (char) (result + newS.charAt(1));
}
return result;
}
}
It is properly taking the input, however it seems to not be executing the generatNewName method. Am I doing something wrong with the types of methods i'm using? Should generateNewName return a string-type? If so, how do I get the second letter of all input strings and concatenate them? Thanks,
Your generateNewName() method should be returning a String, not a char.
Then you would have to change that
char result = '\0';
with
String result = "";
and then you start appending (using +) the letters to the String.
You can also read about StringBuilder, which would make the code more efficient.
Also, String newS = Arrays.toString(getNames); that line doesn't make much sense. You want to be looping through the names you have, not through all the letters of your name.
I would rewrite that loop to something like:
for (int i = 0 ; i < names.length ; i++) {
result += names[i].charAt(1);
}
or, using a for-each loop
for (String name : names) {
result += name.charAt(1);
}
"Enter 5 names:" is misleading. Consider "Enter name " + (x + 1) + " (of " + 5 + "):" or something similar.
But to answer your question: You are running generateNewName before you get any names! It's being executed for an array of only null elements!
Change this:
Output = generateNewName(getNames);
System.out.println(Output);
for(int x = 0; x < 5; x++){
System.out.println("Enter 5 names: ");
getNames[x] = input.nextLine();
}
to this
for(int x = 0; x < 5; x++){
System.out.println("Enter 5 names: ");
getNames[x] = input.nextLine();
}
Output = generateNewName(getNames);
System.out.println(Output);
:)
Also consider renaming your variables to (a) follow naming conventions such as variable names should be lowercase, and (b) to be more indicative of what they hold and what they are (string, char, array, etc.). Such as names or nameArray instead of getNames and newName or outputName instead of Output.
Finally, and as stated by others, you're using and returning a char in the generateNewName, and obviously a name is a string, not a char.
generateNewName should return a String, not a char. A char is a single character, like the letter A.
You can't generate the new name before asking for the old names, right? Within a method, unless you say otherwise (e.g. with a loop), code runs from top to bottom, like a list of instructions.
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);