I can't add a string to itself - java

I'm new to java and trying to add a string to itself (plus other strings also) and it runs but doesn't do anything at all, as in it just outputs "test", which is what it is before
everything else seems to work
package chucknorris;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Input string:");
String input = scanner.nextLine();
int length = input.length();
String output = "test";
for (int current = 0;current <= length;current++) {
String letter = input.substring(current, current);
output = output + letter + " ";
if (current == length) {
System.out.println(output);
}
}
}
}

Try this Solution, but you should use StringBuilder if you want to edit a String for a multiple times
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Input string:");
String input = scanner.nextLine();
int length = input.length();
String output = "test";
for (int current = 0;current <= length;current++) {
if (current >= length) {
break;
}
String letter = input.substring(current, current + 1);
output = output + letter;
}
System.out.println(output);
}
}

use concat for the string concatenation.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Input string:");
String input = scanner.nextLine();
int length = input.length();
String output = "test";
output = output.concat(output).concat(input).concat("");
System.out.println(output);
}

Related

to check whether a string is palindrome or not using java

import java.util.Scanner;
public class palindrome{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
String rev;
for(int i=str.length()-1,k=0;i>=0 && k<str.length();i--,k++)
{
rev.charAt(k) = str.charAt(i);
}
if(rev==str)
System.out.println("string is palidrome");
else
System.out.println("string is not palindrome");
}
}
what is wrong with this code?
note: error is showing at the following line of code
rev.charAt(k)=str.charAt(i);
.charAt(k) doesn't return a location, it only tells you what character is there.
Sample code for palindrome program
import java.util.*;
class PalindromeExample2
{
public static void main(String args[])
{
String original, reverse = ""; // Objects of String class
Scanner in = new Scanner(System.in);
System.out.println("Enter a string/number to check if it is a palindrome");
original = in.nextLine();
int length = original.length();
for ( int i = length - 1; i >= 0; i-- )
reverse = reverse + original.charAt(i);
if (original.equals(reverse))
System.out.println("Entered string/number is a palindrome.");
else
System.out.println("Entered string/number isn't a palindrome.");
}
}

Why character in StringBuild does not change?

The character must be entered from the console to change to lowercase letters on this line. But it displays the same word and the symbol does not change.
public class Task {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder(requestString());
char symbol = requestSymbol().charAt(0);
int count = 0;
for (int i = 0; i < sb.length(); i++) {
if (sb.charAt(i) == symbol) {
sb.setCharAt(i, sb.charAt(Character.toUpperCase(i)));
count++;
}
}
System.out.println("Number of entries: " + count);
System.out.println("Converted string: " + sb);
}
static String requestString() {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter string:");
return scanner.nextLine();
}
static String requestSymbol() {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the symbol:");
return scanner.next();
}
}
It seems to be a problem with the line:
sb.setCharAt(i, sb.charAt(Character.toUpperCase(i)));
It should be:
sb.setCharAt(i, Character.toUpperCase(symbol));

It only gives one string as the output

If I enter 3 objects
aakash
12323
aakshit
24r352
rahul
12323
If i give this as a input and enter search string as 'aa' then it gives only first string that matches the search ouput will be
aakash
12323
why not aakshit also
import java.util.Scanner;
import java.io.*;
public class DA_2_searching {
String name,phone_number;
Scanner s = new Scanner(System.in);
DA_2_searching()
{
System.out.print("Enter the Details");
name=s.nextLine();
phone_number= s.nextLine();
}
void search()
{
String search;
search=s.nextLine();
if(name.startsWith(search))
{
System.out.println(name);
System.out.println(phone_number);
}
}
public static void main(String args[])
{
int n;
Scanner s = new Scanner(System.in);
n= s.nextInt();
DA_2_searching obj[]= new DA_2_searching[n];
for(int i=0;i<n;i++)
{
obj[i]= new DA_2_searching();
}
for(int i=0;i<n;i++)
{
obj[i].search();
}
}
}
The reason for your problem is, that you only search for one object at a time. Your for loop that calls the search() function only compares one object to a search input at a time.
In the for loop, you are only calling the search function for one DA_2_searching object (the one with index i - obj[i]). But you want to search in every DA_2_searching object you created, that means you have to rework the search() function so that it gets all DA_2_searching objects and compares them to the search-String.
Here's my solution:
import java.util.Scanner;
public class DA_2_searching {
private String name, phone_number;
private static DA_2_searching[] allPersons;
private static Scanner s = new Scanner(System.in);
public DA_2_searching() {
System.out.println("Enter the Details: ");
System.out.print("Name: ");
this.name = s.next();
System.out.print("Phone-Number: ");
this.phone_number = s.next();
System.out.println("\nNext: ");
}
public static void search() {
System.out.println("Type a word to search for: ");
String toSearch = s.next();
for(DA_2_searching person : allPersons) {
if(person.name.contains(toSearch)) { //contains is better for searching.
System.out.println("Result: " + person.name + " | " + person.phone_number);
}
}
System.out.println("\n");
if(!toSearch.equals("exit")) {
search();
}
}
public static void main(String args[]) {
System.out.print("Amount of Entries: ");
int n = s.nextInt();
System.out.println("");
allPersons = new DA_2_searching[n];
//Creating Persons
for(int i = 0; i < n; i++) {
allPersons[i] = new DA_2_searching();
}
//initializing search
search();
}
}
In your current code you search for a String in every iteration. You read in a String and check if this String equals Array[0] then you print it. Then you read in a String again and check if it is equal to Array[1]... and so on. What you want is a search in the whole Array.
A simple solution would be to read in the String before the 2nd loop and pass the
string into search();
void search(String search) {
if (name.startsWith(search)) {
System.out.println(name);
System.out.println(phone_number);
}
}
public static void main(String args[]) {
int n;
Scanner s = new Scanner(System.in);
n = s.nextInt();
DA_2_searching obj[] = new DA_2_searching[n];
for (int i = 0; i < n; i++) {
obj[i] = new DA_2_searching();
}
String search = new String();
search = s.nextLine();
for (int i = 0; i < n; i++) {
obj[i].search(search);
}
}

How to read input from user with unknown length?

I want to enter a string of numbers, delimited by ",". I don't know how long it will be. The input will be passed to the program and will end with the letter "x".
JAVA!
import java.util.Scanner;
public class fromUserSum {
/// input : 1,2,4x from user
/// output : 7
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int num;
int sumTotal=0;
while(scan.nextByte() != 'x') {
num = scan.nextInt();
sumTotal += num;
}
System.out.println(sumTotal);
scan.close();
}
}
PLEASE help! :)
//////////////
public class fromUserSum {
/// input : 1,2,4x from user
/// output : 7
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String userInput;
do {
System.out.println("Please enter a list of numbers in following format: 1,2,3,4x");
userInput = scan.next();
} while (!userInput.matches("(?:\\d+(?:,\\d+)*)x") || !userInput.matches("\\d+( \\d+)*x"));
scan.close();
String[] numberStrings;
if (userInput.contains(",")) {
numberStrings = userInput.replace("x", "").split(","); // 4x is now 4 and split by ','
} else {
numberStrings = userInput.replace("x", "").split(" ");
}
int sum = 0;
for (String i : numberStrings) {
sum += Integer.valueOf(i);
}
System.out.println("The sum of all numbers in the list is: " + sum);
}
}
Try this
public static void main(String[] args) {
int result = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the value");
String string = sc.nextLine();
string = string.replace("x", "");
String[] strArray = string.split(",");
for (String str : strArray) {
result += Integer.valueOf(str);
}
System.out.println("Result is " + result);
}
Input is 1,2,3,4x
Output is Result is 10
import java.io.Console;
import java.util.Scanner;
class MainClass{
public static void main(String args[]) {
int sum=0;
Console c=System.console();
Scanner scan = new Scanner(c.readLine());
scan.useDelimiter("[,x]");
while(scan.hasNextInt())
sum+=scan.nextInt();
scan.close();
System.out.print(sum);
}
}
This does the job as well. Additionally it tells the user what input is expected and if the entered list does not match the format.
public static void main(final String[] args) {
final Scanner userInputScanner = new Scanner(System.in);
String userInput;
do {
System.out.println("Please enter a list of numbers in following format: 1,2,3,4x or 1 2 3 4x");
userInput = userInputScanner.nextLine();
} while (!(userInput.matches("\\d+(,\\d+)*x") || userInput.matches("\\d+( \\d+)*x")));
userInputScanner.close();
final String[] numberStrings = userInput.replace("x", "").split("[, ]");
int sum = 0;
for (final String numberString : numberStrings) {
sum += Integer.valueOf(numberString);
}
System.out.println("The sum of all numbers in the list is: " + sum);
}

Method is undefined for class TestChatBot?

import java.util.*;
public class TestChatBot
{
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
String x = input.nextLine();
TestChatBot e = new TestChatBot();
{
String prompt = "What would you like to talk about?";
System.out.println(prompt);
String userInput = input.nextLine();
while(!userInput.equals("Goodbye"))
{
System.out.println(e.getResponse());
userInput = input.nextLine();
}
}
}
public class ChatBot
{
public String getResponse(String input)
{
Scanner userInput = new Scanner(input);
input = userInput.nextLine();
longestWord(input);
String keyword = "you";
int you = input.indexOf(keyword);
if (you >= 0)
return "I'm not important. Let's talk about you.";
if (input.length() <= 3)
return "Maybe we should move on. Is there anything else you would like to
talk about?";
if (input.length() == 4)
return "Tell me more about " + input;
if(input.length() == 5)
return "Why do you think " + input + "is important?";
else
return "Now we're getting somewhere. How does " + input + "affect you the
most?";
}
private String longestWord(String x)
{
Scanner input = new Scanner(x);
String longest = "";
String temp = input.next();
while (input.hasNext())
{
if (temp.length() > longest.length())
longest = temp;
}
return longest;
}
}
}
In my ChatBotTest class it says that my getResponse() method is undefined for the class TestChatBot... I don't really understand why it says this and it's preventing my code from running. I'm pretty new to Java so I'm sorry for poor/sloppy coding. Any help is greatly appreciated, thank you!
TestChatBot e = new TestChatBot();
Should be
ChatBot e = new ChatBot();
TestChatBox has no getResponse()
Also, your getResponse takes a String argmument. I think you want to pass userInput to it
System.out.println(e.getResponse(userInput));

Categories

Resources