// I'm looking for any errors or mistakes I made in the code or another way to do it with if-then statements or usage of array. (very new to java)
import java.util.Scanner;
public class Palindrome {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a string");
String letter = input.nextLine();
int n = letter.length();
int numberOfLetters = 0;
for (int i = 0; i < letter.length(); i++) {
numberOfLetters++;
}
if(letter.charAt(0) != letter.charAt(n-1)){
String letter2 = letter.toLowerCase();
if (letter2.charAt(0) == letter2.charAt(n - 1)) {
System.out.println("This is a palindrome " + letter);
}
else {
System.out.println("This is not a palindrome " + letter);
}
}
}
}
This is the problem I'm trying to solve:
My code is the following:
import java.util.Scanner;
public class LineByLine {
public static void main(String[] args) {
while (true) {
Scanner scanner = new Scanner(System.in);
String sentence = String.valueOf(scanner.nextLine());
String[] pieces = sentence.split(" ");
for (int i = 0; i < pieces.length; i++) {
System.out.println(pieces[i]);
}
if (sentence.equals("")) {
break;
}
}
}
}
My code is showing as wrong and I'm unsure why. Any explanations?
You should arrange your code like:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
String sentence = String.valueOf(scanner.nextLine());
String[] pieces = sentence.split(" ");
for (int i = 0; i < pieces.length; i++) {
System.out.println(pieces[i]);
}
if (sentence.equals("")) {
break;
}
}
scanner.close();
}
Also you could use hasNext method instead of while(true) part:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
String sentence = scanner.nextLine();
String[] pieces = sentence.split(" ");
for (int i = 0; i < pieces.length; i++) {
System.out.println(pieces[i]);
}
}
scanner.close();
}
You'll need to place:
Scanner scanner = new Scanner(System.in);
outside of the while loop.
The reason:
You only need to create a single Scanner object. This has to be done before you enter the loop since the instantiation will consume the standard input - this means that after the first iteration of the loop, there will be no standard input left to instantiate the object once again.
You can also think about it more mechanically than that:
If you had a loop that was meant to iterate through numbers, you wouldn't want to be resetting your loop counter each time, right? Its quite a similar thing in this case.
What I am trying to do is very elementary. The user should enter a name and the program prints only the initials of the name except for the last word.
Eg:
input - "Mansha Mannan UL Haque"
output - "M.M.U.Haque"
The program is as follows but it does not compile.
class joke
{
public static void main(String str)
{
String alter=" "+str;
int n=alter.length();
for(int i=0;i<=n;i++)
{
char f=alter.charAt(i);
if (f.compareTo(" ")>0)
{
System.out.println(alter.charAt(i+1));
}
}
}
}
The error showed is char cannot be dereferenced.
Split your input string into string array then access each word and print its first char, for last word print it whole.
class joke
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String alter=sc.nextLine(); //take input from user
String arr[] = alter.split(" ");
int n=arr.length(); //total words in user string
for(int i=0;i<n;i++)
{
if(i==n-1){ //if last word
System.out.print(arr[i]);
}
else{
System.out.print(arr[i].charAt(0)+". ");
}
}
}
}
This should do the trick
in this case namewould be your input
String name = "Mansha Mannan UL Haque";
String[] nameArray = name.split(" ");
String newName = "";
for(int i = 0; i < nameArray.length; i++)
{
if(i != nameArray.length -1)
{
newName += nameArray[i].substring(0, 1) + ".";
}
else
{
newName += nameArray[i];
}
}
and you should also make your class joke public and change String str to String[] args
This is what I have so far. I want the program to print out the words the user inputs as a sentence. But
I don't know how I get that to happen with the code I have written so far.
ex: if you entered
Hello
World
done
The program should say: "Hello World"
import java.util.Scanner;
public class Chapter3ProblemsSet {
public static void main(String [] args) {
String word = "";
final String SENTINEL = "done";
double count = 0;
String userInput = "";
Scanner in = new Scanner (System.in);
System.out.println("Please enter words: ");
System.out.println("Enter done to finish.");
word = in.next();
do {
word = in.next();
count++;
System.out.print(" "+word);
}
while (!word.equals(SENTINEL));
System.out.println(" "+word);
}
}
What you need it to store it in a variable which is declared outside the loop.
StringBuilder sentence=new StringBuilder();
do {
word = in.nextLine();
count++;
System.out.print(" "+word);
sentence.append(" "+word);
}
while (!word.equals(SENTINEL));
Then for printing use
System.out.println(sentence.toString());
You will need to create an additional string to "collect" all of the words that the user enters. The problem with your original is that you replace 'word' with the word entered. This should do the trick:
import java.util.Scanner;
public class Chapter3ProblemsSet {
public static void main(String [] args) {
String word = "";
String sentence = "";
final String SENTINEL = "done";
double count = 0;
String userInput = "";
Scanner in = new Scanner (System.in);
System.out.println("Please enter words: ");
System.out.println("Enter done to finish.");
word = in.next();
do {
word = in.next();
count++;
sentence += " " + word;
System.out.print(" "+word);
}
while (!word.equals(SENTINEL));
System.out.println(" "+sentence);
}
}
You can read it by pieces and put them together using a StringBuffer - http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuffer.html
StringBuffer sb = new StringBuffer();
do {
sb.append( in.next() );
count++;
}
while (!word.equals(SENTINEL));
So I'm trying to find all the uppercase letters in a string put in by the user but I keep getting this runtime error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: 4
at java.lang.String.charAt(String.java:686)
at P43.main(P43.java:13)
I feel foolish but I just can't figure this out and oracle even talks about charAt on the page about java.lang.StringIndexOutOfBoundsException
Here is my code for finding the uppercase letters and printing them:
import java.io.*;
import java.util.*;
public class P43{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
//Uppercase
String isUp = "";
System.out.print("Please give a string: ");
String x = in.next();
int z = x.length();
for(int y = 0; y <= z; y++){
if(Character.isUpperCase(x.charAt(y))){
char w = x.charAt(y);
isUp = isUp + w + " ";
}
}
System.out.println("The uppercase characters are " + isUp);
//Uppercase
}
}
I'd really appreciate any input and or help.
for(int y = 0; y <= z; y++){
should be
for(int y = 0; y < z; y++){
Remember array index starts from ZERO.
String length returns
the number of 16-bit Unicode characters in the string
Because loop started from ZERO, loop should terminate at length-1.
The array index out of bounds is due to the for loop not terminating on length - 1, it is terminating on length
Most iterating for loops should be in the form:
for (int i = 0; i < array.length; i++) {
// access array[i];
}
It's the same with a string.
Perhaps a cleaner way would be:
String inputString; // get user input
String outputString = "";
for (int i = 0; i < inputString.length; i++) {
c = inputString.charAt(i);
outputString += Character.isUpperCase(c) ? c + " " : "";
}
System.out.println(outputString);
Edit: Forgot String Doesn't implement Iterable<Character>, silly Java.
With Java 8 you can also use lambdas. Convert the String into a IntStream, use a filter to get the uppercase characters only and create a new String by appending the filtered characters to a StringBuilder:
Scanner in = new Scanner(System.in);
System.out.print("Please give a string: ");
//Uppercase
String isUp = in.next()
.chars()
.filter(Character::isUpperCase)
.collect(StringBuilder::new, // supplier
StringBuilder::appendCodePoint, // accumulator
StringBuilder::append) // combiner
.toString();
System.out.println("The uppercase characters are " + isUp);
//Uppercase
Inspired by:
Adam Bien - Streaming A String
Simplest way to print anIntStream as a String
Try this...
Method:
public int findUpperChar(String valitateStr) {
for (int i = valitateStr.length() - 1; i >= 0; i--) {
if (Character.isUpperCase(valitateStr.charAt(i))) {
return i;
}
}
return -1;
}
Usage:
String passwordStr = password.getText().toString();
.......
int len = findUpperChar(passwordStr);
if ( len != -1) {
capitals exist.
} else {
no capitals exist.
}
Hi one of the easy step to find uppercase char in a given string...
Program
import java.io.*;
public class testUpper
{
public static void main(String args[]) throws IOException
{
String data,answer="";
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter any String : ");
data=br.readLine();
char[] findupper=data.toCharArray();
for(int i=0;i<findupper.length;i++)
{
if(findupper[i]>=65&&findupper[i]<=91) //ascii value in between 65 and 91 is A to Z
{
answer+=findupper[i]; //adding only uppercase
}
}
System.out.println("Answer : "+answer);
}
}
Output
Enter any String :
Welcome to THe String WoRlD
Answer : WTHSWRD
You can increase the readability of your code and benefit from some other features of modern Java here. Please use the Stream approach for solving this problem. Also, I suggest importing the least number of libraries into your class. Please avoid using .* while importing.
import java.util.Scanner;
public class P43 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Please give a string: ");
String x = in.next();
x.chars().filter(c -> Character.isUpperCase(c))
.forEach(c -> System.out.print((char) c + " "));
}
}
Sample input:
saveChangesInTheEditor
Sample output:
C I T E
import java.util.Scanner;
class Demo
{
public static void main(String[] args)
{
StringBuilder s=new StringBuilder();
Scanner input = new Scanner(System.in);
System.out.println("Enter your String");
String str= input.nextLine();
for(int i=0; i<str.length(); i++)
{
if(Character.isUpperCase(str.charAt(i)))
{
System.out.print(str.charAt(i)+" ");
}
}
}
}
The simplest way I know is to use regex replacement.
isUp = x.replaceAll("[^A-Z]", "");
In simple terms, this uses a regular expression which matches any character which is not in the A-Z range, and replaces it with an empty string.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the number");
String str= input.nextLine();
int ascii;
for(int i=0; i<str.length(); i++) {
ascii = str.charAt(i);
System.out.println(ascii);
if (ascii >= 65 && ascii <= 90) {
System.out.println("captal letter found ::: "+ascii);
}
}
}
public class Cama {
public static void main(String[] args) {
String camal = "getStudentByName";
String temp = "";
for (int i = 0; i < camal.length(); i++) {
if (Character.isUpperCase(camal.charAt(i))) {
System.out.print(" " + Character.toLowerCase(camal.charAt(i)));
} else if (i == 0) {
System.out.print(Character.toUpperCase(camal.charAt(i)));
}else{
System.out.print(camal.charAt(i));
}
}
}
}