Why is my program not running? Please check - java

The following program prompts the user to enter a word; reverse the word and print it. I believe my program contains no error but it does not seem to run in eclipse. Please somebody check my code. Thanks!
import java.util.Scanner;
public class reverseWord
{
public static String reverse(String m)
{
String reverse = "";
int Length = m.length();
for(int i = Length-1; i>=0; i=i-1)
{
reverse = reverse + m.charAt(i);
}
return reverse;
}
public static void main(String args[])
{
Scanner keyIn = new Scanner(System.in);
String store = keyIn.nextLine();
reverseWord rw = new reverseWord();
rw.reverse(store);
}
}

Your problem is that you are only returning the reversed String but no printing it out to the console. You should also changed the method to be a non-static method or accessing it using the class name instead of an instance. And class names in java always start with a uppercase letter :) Try something like this:
import java.util.Scanner;
public class ReverseWord {
public String reverse(String m) {
String reverse = "";
int Length = m.length();
for (int i = Length - 1; i >= 0; i = i - 1) {
reverse = reverse + m.charAt(i);
}
return reverse;
}
public static void main(String args[]) {
Scanner keyIn = new Scanner(System.in);
String store = keyIn.nextLine();
ReverseWord rw = new ReverseWord();
String reversedWord = rw.reverse(store);
System.out.println(reversedWord);
}
}

Related

Problem with Java code that will print TRUE when a word has no vowels in an IF statement

I am trying to write a code the will print TRUE when i enter a word with no vowels and will print FALSE if I enter a word with vowels. I am having trouble when it comes to writing the string. I give one of the strings the value that holds all the values.
String A = "aeiou";
The other 2 strings hold the rest of the alphabet.
When I type in a word that has vocals it prints FALSE however when I type in a word with no vowels it prints FALSE.
I wanna know if there is a way to make the program read the values of the string as separate entities and not as a whole line.
package lab3;
import java.util.Scanner;
public class Lab3 {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
String input = reader.next();
/* A and B, but not C */
String A = "bcdfghjklm";
String B = "npqrstvwxyz";
String C = "aeiou";
if (input.contains(A) && input.contains(B) || input.contains(C)) {
System.out.println("TRUE");
} else {
System.out.println("FALSE");
}
}
}
You can do it with a short function
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
String input = reader.next();
System.out.println(chk(input));
}
static public boolean chk(String s) {
for (int i = 0; i < s.length(); i++) {
if ("aeiou".indexOf(s.charAt(i)) != -1) {
return false;
}
}
return true;
}
}
This is a working correct for your purpose:
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
String input = reader.next();
String C = "aeiou";
for (int i = 0; i < input.length(); i++) {
char inputA = input.charAt(i);
for (int j = 0; j < C.length(); j++) {
char c = C.charAt(j);
if (inputA == c) {
System.out.println("TRUE");
return;
}
}
}
System.out.println("FALSE");
}
The key point is to use the method charAt(int index); so you can check each char in the string.
You can choose to use any of the below two methods, containsVowel and containsVowel1 as both of them do the same thing:
import java.util.Arrays;
import java.util.Scanner;
public class Test {
public static void main(String args[]) {
Scanner reader = new Scanner(System.in);
System.out.println("Enter a text: ");
String input = reader.nextLine();
String[] vowels = { "a", "e", "i", "o", "u" };
System.out.println(!containsVowel(input, vowels));
System.out.println(!containsVowel1(input, vowels));
}
public static boolean containsVowel(String input, String[] vowels) {
return Arrays.stream(vowels).parallel().anyMatch(input::contains);
}
public static boolean containsVowel1(String input, String[] vowels) {
for (int i = 0; i < vowels.length; i++) {
if (input.contains(vowels[i])) {
return true;
}
}
return false;
}
}

Replace one by one values of an array list and store the values of another array using for loop

How to replace one by one values of an array list and store the values of another array using for loop?
As I want the user to write any line, then I want the code to eliminate all the numbers as well as symbol from the user input and convert the remaining user input into uppercase and then if I get something BDJH from the program I want the program to shift the value of alphabet by one therefore the answer should be or the output should be CEKI as (earlier it was BDJH shifted by one in alphabetical order).
But my program is not running, I don't know the error.
import java.util.ArrayList;
import java.util.Scanner;
public class nanana {
public static void main(String[] args){
System.out.println("ENTER THE NUMBER YOU WANT ENCRYPTED");
Scanner input1=new Scanner(System.in);
String name =input1.nextLine();
encryption(name);
name=name.toUpperCase();
ArrayList<Character> nilkil =new ArrayList<Character>();
for(int i=0;i<=name.length()-1;i++){
nilkil.add(name.charAt(i));
}
char[] deep={'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'};
for(int j=0;j<=nilkil.size()-1;j++) {
for (int p = 0; p <=deep.length-1; p++) {
if(nilkil.get(j)==deep[p]){
nilkil.add(j,deep[p+1]);
}
}
}
System.out.println(nilkil.toString());
}
public static String encryption(String name){
name=name.replaceAll("[^a-zA-Z]" ,"");
name=name.toUpperCase();
System.out.println(name);
return name;
}
}
You can do this by converting the input string to character array then increment each ASCII character by 1 as you required. One thing keep your class name meaningful and starts with Caps.
public class CharacterConversion{
public static void main(String[] args){
System.out.println("ENTER THE NUMBER YOU WANT ENCRYPTED");
Scanner input1=new Scanner(System.in);
String name =input1.nextLine();
encryption(name);
name=name.toUpperCase();
char[] namesArray = name.toCharArray();
for(int i=0;i<namesArray.length;i++){
namesArray[i] = (char) (namesArray[i]+1);
}
System.out.println(new String(namesArray));
}
public static String encryption(String name){
name=name.replaceAll("[^a-zA-Z]" ,"");
name=name.toUpperCase();
System.out.println(name);
return name;
}
}
Please find correct answer for your problem.
import java.util.*;
public class nanana {
public static void main(String[] args){
System.out.println("ENTER THE NUMBER YOU WANT ENCRYPTED");
Scanner input1=new Scanner(System.in);
String name =input1.nextLine();
name=encryption(name);
ArrayList<Character> nilkil =new ArrayList<Character>();
for(int i=0;i<=name.length()-1;i++){
nilkil.add(name.charAt(i));
}
String answer="";
char[] deep={'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'};
for(int j=0;j<=nilkil.size()-1;j++) {
if(nilkil.get(j)=='Z') //Replacing Z with A
answer=answer+'A';
else{
for (int p = 0; p <deep.length-1; p++) {
if (nilkil.get(j) == deep[p]) {
answer = answer + deep[p + 1];
break;
}
}
}
}
System.out.println(answer);
}
public static String encryption(String name){
name=name.replaceAll("[^a-zA-Z]" ,"");
name=name.toUpperCase();
return name;
}
}

How can I detect all the capital letters in a string given by the user?

So I'm trying to write a method where it detects all the capital letters given by the user. How is this possible? Is it possible to do it using ASCII values? Is it possible in another way? Please give me suggestions and about the best way to come up with this algorithm
NOTE: problem is as stated at bottom of the source CODE
SOURCE CODE
Scanner sc = new Scanner(System.in);
private String userPassword;
private char[] passChar;
private int passwordScore = 0;
public String getPassword(){
userPassword = sc.nextLine();
passChar = userPassword.toCharArray();
return userPassword;
}
// Ingore this comment below, this is just for me
//do for( char i : passChar.length) or actualy if statmen so that if the pass is not 8 charaters long it doesnt qulafiy
public void passRequirments(){
}
public int passLength(){
for(char upperCase: passChar){
passwordScore = passwordScore + 4;
}
return passwordScore;
}
//THIS IS WHERE IM HAVING TROUBLE
public void passUpper(){
for (char c : passChar){
if (Character.isUpperCase(passChar.charAt(c))){
}
}
}
THE PROBLEM
public void passUpper(){
for (char c : passChar){
if (Character.isUpperCase(passChar.charAt(c))){
passwordScore = passwordScore + ((userPassword.length()- passChar.charAt(c)) * 2);
}
}
}
I think something like this could be a feasible solution
import java.io.*;
import java.util.*;
public class Main{
public static int printUpperCaseLetters(String s)
{
char[] ch = new char[s.length()];
ch = s.toCharArray();
int cap_count = 0;
for(int i=0; i<ch.length; i++)
{
int val = (int)ch[i];
if(val>=65 && val<=90)
{
cap_count++;
System.out.println(ch[i]);
}
}
return cap_count;
}
public static void main(String[] args) throws IOException {
Scanner input = new Scanner(System.in);
String s = input.next();
// So this method returns you the capital letters count inside of the string
int cap_count = printUpperCaseLetters(s);
}
}
Hope this help!
You can fetch the function part and add it to your code.
Just focus on the method printUpperCaseLetters and pass your String to this method.
Just use regex to replace all non capital letters to empty space:
string = string.replaceAll("[^A-Z]", "");
You will end up with string that contains only capital letters from input.

JAVA Reversing a string on multiple lines output

Why in my program am i getting the output on one single line ? like abc123... I want my output to be printed on multiple lines, same as my inputs..
import java.util.Scanner;
class Reverse
{
public static void main(String args[])
{
String original;
String reverse = "";
Scanner kbd = new Scanner(System.in);
while (kbd.hasNextLine()) {
original = kbd.nextLine();
int length = original.length();
for ( int i = length - 1 ; i >= 0 ; i-- ) {
reverse = reverse + original.charAt(i);
}
}
System.out.println(reverse);
}
}
It should be for example like this :
input: abc
123
...
output:cba
321
...
Here's one way of doing it:
import java.util.Scanner;
class Reverse {
public static void main(String args[])
{
String original;
String reverse = "";
Scanner kbd = new Scanner(System.in);
StringBuilder output = new StringBuilder();
while (kbd.hasNextLine())
{
original = kbd.nextLine();
StringBuilder sb = new StringBuilder(original);
output.append(sb.reverse().toString()).append("\n");
}
System.out.println(output.toString());
}
}
EDIT I noticed that in your question it seems that you only want to print the output after all input has been provided. I've modified the code from my original answer to do this.
import java.io.*;
import java.util.*;
public class reverseString {
public static void main(String[] args) {
String input="";
System.out.println("Enter the input string");
try
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
input = br.readLine();
char[] try1= input.toCharArray();
for (int i=try1.length-1;i>=0;i--)
System.out.print(try1[i]);
}
catch (IOException e) {
e.printStackTrace();
}
}}
try this:
package stackoverflow;
import java.util.Scanner;
class Reverse
{
public static void main(String args[])
{
String original;
String reverse = "";
Scanner kbd = new Scanner(System.in);
while (kbd.hasNextLine()) {
original = kbd.nextLine();
//befor you add the reversed string add a jump line firs
if(reverse.length()>0)reverse=reverse+"\n";
int length = original.length();
for ( int i = length - 1 ; i >= 0 ; i-- ) {
reverse = reverse + original.charAt(i);
}
}
System.out.println(reverse);
}
}
You should change this part
for ( int i = length - 1 ; i >= 0 ; i-- ) {
reverse = reverse + original.charAt(i);
}
in
for ( int i = length - 1 ; i >= 0 ; i-- ) {
reverse = reverse + original.charAt(i);
}
reverse = reverse + '\n';
This will add new line character.
I have one advice for you - use StringBuilder for new reverse string
Like this:
public static void main(String args[]) {
String original;
StringBuilder sbReverse = new StringBuilder();
Scanner kbd = new Scanner(System.in);
while (kbd.hasNextLine()) {
original = kbd.nextLine();
int length = original.length();
for (int i = length - 1; i >= 0; i--) {
sbReverse.append(original.charAt(i));
}
sbReverse.append('\n');
}
System.out.println(sbReverse.toString());
}
The reason - in Java, strings are immutable.
That mean every time it execute reverse = reverse + original.charAt(i); it will be created a new string in memory.
You're getting the output in a single line because you are using System.out.printf(). Use System.out.println() instead.
PS: an easier way to reverse a string would be to use reverse() from StringBuilder.
reverse = new StringBuilder(original).reverse().toString();

java beginner programming, putting strings in char array to filter input

in this code I've been trying to filter the characters in the array with a for-loop to a second array, but am unable to. Could anyone tell me what is exactly wrong with my code?
public class Deel1 {
public static void main(String[] args) {
String zinInvoer = getInput();
String zinUitvoer = filterZin(zinInvoer);
}
static String getInput() {
Scanner scan = new Scanner(System.in);
String zinInvoer = "";
System.out.println("Voer een zin in: ");
if (scan.hasNextLine()) {
zinInvoer = scan.nextLine().trim();
}
if (zinInvoer.equals("")) {
System.out.println("Geen invoer!");
System.exit(0);
}
return zinInvoer;
}
static String filterZin(String zinInvoer) {
String zinUitvoer = "";
char ongefilterd[] = zinInvoer.toCharArray();
String nogFilteren = new String(ongefilterd);
char a = nogFilteren.charAt(97);
for (a = 97; a <= 122; a++) {
a = a += 32;
char gefilterd[] = //second array to be printed
}
System.out.println("Gefilterd: " + zinUitvoer);
return zinInvoer;
}
}
Sorry if it annoys you but I had to translate your variables into english in order to figure out what their purposes were.
First of all, it will always throw an exception when the string is less than 98 letters long because it looks for the 97th letter.
Second, the for loop in "filterZin" will only filter letter # 98, which I am guessing was not your intention.
Also, geFilterd should probably be created outside of the for loop, and in the for loop you (i guess) would want to do
geFilterd[a]=a+32;
a+=32;
Because I couldn't figure out what your overall goal was for this program, I made a version of it that does what I think you were trying to do, but again, I do not know.
import java.util.Scanner;
public class Deel1 {
public static void main(String[] args) {
String phraseInput = getInput();
filterPhrase(phraseInput);
}
static String getInput() {
Scanner scan = new Scanner(System.in);
String phraseInput = "";
System.out.println("Voer een zin in: ");
if (scan.hasNextLine()) {
phraseInput = scan.nextLine().trim();
}
if (phraseInput.equals("")) {
System.out.println("Geen invoer!");
System.exit(0);
}
return phraseInput;
}
static String filterPhrase(String phraseInput) {
String phraseOutput = "";
char onFiltered[] = phraseInput.toCharArray();
String currentFilter = new String(onFiltered);
// for (a = 97; a <= 122; a++) {
// a = a += 32;
// //char filtered[] = //second array to be printed
// }
char[] filtered = new char[26];
for(int i=97;i<=122;i++){
char a = currentFilter.charAt(i);
filtered[i-97]= (char) (a+32);
}
System.out.println("filtered: " + filtered.toString());
return phraseInput;
}
}

Categories

Resources