Subtract Characters One at a Time - java

I am trying to get the following code to delete the last character one at a time until the last...
Output:
Will
Wil
Wi
W
* #author Will
*/
import java.util.Scanner;
public class DecreaseLetters {
public static void main(String args[]){
Scanner s=new Scanner(System.in);
System.out.println("Anota una Frase: ");
String input=s.nextLine();
return str.substring(0,str.length()-1);
System.out.println(input);
}
}

Maybe this?
import java.util.Scanner;
public class DecreaseLetters {
public static void main(String args[]){
Scanner s=new Scanner(System.in);
System.out.println("Anota una Frase: ");
String str=s.nextLine();
while(str.length()>1) {
str = str.substring(0,str.length()-1);
System.out.println(str.substring(0,str.length()-1));
}
}
}
Reverse:
Scanner s=new Scanner(System.in);
System.out.println("Anota una Frase: ");
String str=s.nextLine();
int i = 0;
while(i<=str.length()) {
String str2 = str.substring(0,i);
System.out.println(str2);
i++;
}

Java String is immutable. You could use a StringBuilder like,
Scanner s = new Scanner(System.in);
System.out.println("Anota una Frase: ");
String input = s.nextLine();
StringBuilder sb = new StringBuilder(input);
while (sb.length() > 0) {
System.out.print(sb);
System.out.print(" ");
sb.setLength(sb.length() - 1);
}
System.out.println();
or, you could produce substrings in a loop like
for (int i = 0; i < input.length(); i++) {
System.out.print(input.substring(0, input.length() - i));
System.out.print(" ");
}
System.out.println();

One way is to use a for loop and the substring() function of the String class:
public static void main (String[] args) throws java.lang.Exception
{
System.out.println("Anota una Frase: ");
String text = new Scanner(System.in).nextLine();
for (int i = 0; i < text.length(); i++)
System.out.println(text.substring(0, text.length()-i));
}

Related

How to read and use the String array using scanner class or other in java

How to read and use the String array using scanner class or other in java
i could read the String into array like that below
arr[0]="apple";
arr[1]="mango";
arr[2]="banana";
.
.
.
and soon
but in by using scanner class how it possible pls tell me
and any help full "for each" in java String arrays...
To read into string array and then read the populated array you could use:
public static void main(String [] args){
// to populate string array`enter code here`
Scanner sc = new Scanner(System.in);
int length = 10, pos = -1;
String arr[] = new String[length];
while(++pos < length){
System.out.print("Enter string : ");
arr[pos] = sc.nextLine();
}
// to read the already populated string array1
for(String s: arr){
System.out.println(s);
}
}
Program to read specific number of elements from the console and write them on the console.
public class Test {
public static void main(String args[]) {
System.out.println("Enter string array size");
Scanner in = new Scanner(System.in);
int i = in.nextInt();
String[] arr = new String[i];
for (int j = 0; j < i; j++) {
System.out.println("Enter next element");
arr[j] = in.next();
}
for (String s : arr) {
System.out.println("Next element[" + s+"]");
}
}
}
import java.util.Scanner;
public class StringRWrite {
public static void main(String[] args) {
Scanner sc1=new Scanner(System.in);
System.out.println("enter the length of String array");
int n=sc1.nextInt();
String[] larray=new String[n];
for(int i=0;i<n;i++){
System.out.println("enter the "+(i+1)+" String :");
larray[i]=sc1.next();
}
System.out.println("Strings Entered by user:");
for(String s:larray){
System.out.println(s);
}
}
}
import java.util.Scanner;
public class StringReadAndWrite {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("enter the length of String array");
int n=sc.nextInt();
String[] sarray=new String[n];
for(int i=0;i<n;i++){
System.out.println("enter the "+(i+1)+" String :");
sarray[i]=sc.next();
}
System.out.println("Strings Entered by user:");
for(String s:sarray){
System.out.println(s);
}
}
}
import java.util.Scanner;
public class BasketballPlayers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("enter the number of basketball players");
int numberOfPlayers = input.nextInt();
String[] playersArray =new String[numberOfPlayers];
for(int i=0;i< numberOfPlayers;i++){
System.out.println("enter the "+(i+1)+" String :");
playersArray[i]= input.next();
}
System.out.println("BasketBall Player names:");
for(String s:playersArray){
System.out.println(s);
}
}
}

ArrayList not adding String

I'm trying to get a word count of a string entered by a user but I keep getting "0" back as a result. I can't figure out what to do.
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner reader=new Scanner(System.in);
ArrayList<String> A=new ArrayList<String>();
System.out.print("Enter a sentence: ");
String a=reader.next();
int charCount=a.length();
int space;
int period;
int wordCount=0;
//word count\
for (int i=0; i<1; i++){
space=a.indexOf(" ");
if (a.charAt(0)!=' '){
if (space!=-1){
A.add(i, a.substring(0, space-1));
a=a.substring(a.indexOf(" ")+1, charCount-1);
}
if (space==-1&&a.charAt(charCount-1)=='.'){
period=a.indexOf(".");
A.add(i, a.substring(0, period));
}
charCount=a.length();
}
wordCount=A.size();
}
System.out.print("Word Count: "+A.size());
}
Why don't you try like this-
public static void main (String[] args) {
Scanner reader=new Scanner(System.in);
System.out.println("Enter a sentence: ");
String str1 = reader.nextLine();
String[] wordArray = str1.trim().split("\\s+");
int wordCount = wordArray.length;
System.out.println("Word count is = " + wordCount);
}

ask the user for input (a sentence) and print out the longest word of that sentence

How do I have this program ask the user for input (a sentence) and print out the longest word of that sentence.
package projectOne;
import java.util.Scanner;
public class LongestWord {
//Scanner keyboard = new Scanner(System.in);
//System.out.println("In 1 sentence tell me what is on your mind today.");
//String actualstring = keyboard.nextLine();
static String actualstring = keyboard.nextLine();
static String[] splitstring = actualstring.split(" ");
public static void main(String [] args){
Scanner keyboard = new Scanner(System.in);
System.out.println("In 1 sentence tell me what is on your mind today.");
//String actualstring = keyboard.nextLine();
//String[] splitstring = actualstring.split(" ");
LongWord();
}
public static void LongWord() {
String longword = "";
for (int i=0; i<=splitstring.length-1; i++){
if (longword.length()<splitstring[i].length())
longword = splitstring[i];
}
System.out.println(longword);
int replyLength = longword.length();
System.out.println(replyLength);
if (replyLength == 3)
System.out.println("Hmmm tell me more about "+longword+" please");
else if (replyLength == 4)
System.out.println("Why do you feel "+longword+" is important?");
else if (replyLength == 5)
System.out.println("How does "+longword+" affect you?");
else if (replyLength > 5)
System.out.println("We seem to be making great progress with "+longword);
else
System.out.println("Is there something else you would like to discuss?");
}
}
I don't think you quite understand how methods work. In your main you should prompt the user for the line they'd like to enter and then you should read the entire line intro a String using the Scanner.nextLine() method and then you should pass said String into your longWord method for processing.
public static void main(String [] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("In 1 sentence tell me what is on your mind today.");
String sentence = keyboard.nextLine();
longWord(sentence);
}
public static void longWord(String sentence) {
//Process and print the longest word using the passed in String param
//Splitting, looping, comparisons, output
}
Try:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
String maxword = null;
str = str + ' ';
int l = str.length();
String word = "";
int maxlength = 0;
for (int i = 0; i < l; i++) {
word = word + str.charAt(i);
if (str.charAt(i + 1) == ' ') {
if (word.length() > maxlength) {
maxword = new String(word);
maxlength = word.length();
}
word = "";
i++;
}
}
System.out.println("Longest Word: " + maxword);
}

Program to remove a word from a sentence

How can I modify the program without using word number option?
Please give me a simplified program.
What must I do to make this program work without word number?
import java.io.*;
class Sentence
{
public static void main(String ar[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the sentence");
StringBuffer sentence=new StringBuffer(br.readLine()+" ");
System.out.println("Enter the word to be deleted");
String word=br.readLine();
int n=0;
int wordno;
System.out.println("Enter the word number");
wordno=Integer.parseInt(br.readLine());
int count=0;
for(int i=0;i<sentence.length();i++)
{
char ch=sentence.charAt(i);
if(ch==' ')
{
String str=sentence.substring(n,i);
count=count+1;
if(str.equals(word)&&count==wordno)
{
sentence.delete(n,i);
}
n=i+1;
}
}
System.out.println("The new sentence is : "+sentence);
}
}
Here is the working program
package com.nikhil.string;
import java.io.IOException;
import java.util.Scanner;
public class demo1 {
public static void main(String[] args) throws IOException {
String[] s;
String sentence, word;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the sentence");
sentence = sc.nextLine();
System.out.println("Enter the word to be deleted");
word = sc.nextLine();
String finalSentence = "";
s = sentence.split(" ");
for (int i = 0; i < s.length; i++) {
if (word.equals(s[i])) {
continue;
} else {
finalSentence += s[i] + " ";
}
}
System.out.println("final sentence is :: " + finalSentence);
sc.close();
}
}
As far as I can see you want to remove given word from a sentence. My suggestion as follows
Read sentence (say String str="hi, How are you")
Take the word you want to remove from the sentence.
(say String strToRemove="are")
Then you can try something as follows.
String str = "hi, How are you?. are you there?";
String strToRemove = "are";
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(str);
boolean status=true;
while (status){
int index=stringBuilder.indexOf(strToRemove);
if(index!=-1) {
stringBuilder.delete(index, index + strToRemove.length()+1);
// +1 will remove a space
}else {
status=false;
}
}
System.out.println(stringBuilder.toString());
public static void main(String ar[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the sentence");
StringBuffer sentence = new StringBuffer(br.readLine() + " ");
System.out.println("Enter the word to be deleted");
String word = br.readLine();
String result = sentence.toString().replace(word, "");
System.out.println("The new sentence is : " + result);
}

Reading data from keyboard to store in string array

String s[];
System.out.println("Enter loop value");
int t = s.nextInt();
for(int i=0;i<t;i++)
{
str[i]=s.nextLine();
}
while it reading it gives null pointer exception
What you need is something like this:
Scanner s = new Scanner(System.in);
System.out.println("Enter loop value");
int t = s.nextInt(); // read number of element
s.nextLine(); // consume new line
String str[] = new String[t];
for(int i=0;i<t;i++)
{
str[i]=s.nextLine();
}
System.out.println(Arrays.toString(str));
Hope this helps.
I changed the typos and missing declarations in your code:
package snippet;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;
public class Snippet {
public static void main(String[] args) throws IOException {
Scanner s = new Scanner(System.in);
String str[] = new String[10];
System.out.println("Enter loop value (maximum 9)");
int t = s.nextInt();
for (int i = 0; i <= t; i++) {
str[i] = s.nextLine();
}
System.out.println("your entered lines:");
System.out.println(Arrays.toString(str));
}
}
However, I would recommend to store the values in a List instead of an Array. I also prefer using a BufferedReader to using a Scanner.
Try something like this:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter loop value");
String a[] = new String[Integer.parseInt(br.readLine())];
for (int i = 0; i < a.length; i++) {
a[i] = br.readLine();
}
//After modifying my code works well
import java.io.*;
import java.util.Scanner;
class Sample
{
public static void main(String[] args) throws Exception
{
bufferedReader();
scanner();
}
static void bufferedReader()throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter Number of Strings");
int len = Integer.parseInt(br.readLine());
String a[] = new String[len];
for(int i=0; i<len; i++){
System.out.println("Enter String"+ (i+1));
a[i] = br.readLine();
}
for(String str : a)
System.out.println(str);
}
static void scanner(){
Scanner s = new Scanner(System.in);
System.out.println("Enter Number of Strings");
int len = Integer.parseInt(s.nextLine());
String a[] = new String[len];
for(int i=0; i<len; i++){
System.out.println("Enter String"+ (i+1));
a[i] = s.nextLine();
}
for(String str : a)
System.out.println(str);
}
}
But when using Scanner nextLine() skips the data when read
if any one knows please post description with example

Categories