I don’t understand why this doesn’t run. I am trying to make a program that displays the text the user inputs as a triangle.
Each new line adds a letter which forms the triangle pattern.
For example, if the user enters the word computers, the output would be:
s
sr
sre
sret
sretu
sretup
sretupm
sretupmo
sretupmoc
import java.util.Scanner;
public class BackwordsTri
{
public static void main(String[] arg)
{
Scanner keyboard = new Scanner(System.in);
String word = keyboard.nextLine();
String newWord="";
char ch;
int wl = word.length();
for (int i=0; i < word.length(); i++)
{
int q = (wl - i);
ch= word.charAt(q);
newWord= ch + newWord;
System.out.println(newWord);
}
}
}
We might need a little more information to help you out on this one. It sounds like you want to be able to print the reversed version of the user input, incrementing by 1 additional letter per line starting from the last letter of the word.
Would you be able to add in the error that you are getting or what the output is from your program? along with a formatted version of the expected output if the issue is in fact formatting?
Related
I'm trying to create a program that parses through an input and determines whether or not it is a palindrome. Pasted below is my code so far:
import java.util.Scanner;
//Gets a message and shift amount and caesar shifts the message by the desired amount. Displays the enciphered message.
public class RobustPalChecker{
public static void main(String[] args){
//declare variables
char current, currentReverse;
int msgInt;
String msg, msgReverse;
StringBuffer sbMsg, newMsg;
Scanner sc = new Scanner(System.in);
//get message
System.out.println("Please enter an integer: ");
msg = sc.nextLine().toUpperCase();
//msgReverse = new StringBuffer(msg).reverse().toString();
System.out.println(msg);
//System.out.println("= " + msgReverse);
//get first and last index of string to check if it's a palindrome
for(int i = 0; i < msg.length(); i++) {
current = msg.charAt(i);
if(Character.isLetter(current) == false){
sbMsg = new StringBuffer(msg);
newMsg = sbMsg.deleteCharAt(i);
msgReverse = new StringBuffer(newMsg).reverse().toString();
}
}
if(newMsg.equals(msgReverse)) {
System.out.println("It's a palindrome");
}else {
System.out.println("It's not a palindrome");
}
}
}
Ignore comments as some of them don't apply and I have not cleaned it up yet. The line of code that I'm pretty sure is causing the error is the isLetter line. The goal of that loop is to find any character that is not a letter and just delete it, and that includes whitespace. That last if statement is the one that actually compares the reversed string and regular string. Now the output that the last if statement is giving me when I try to compile is "variable newMsg might not have been initialized" and the same for msgReverse, but that's not my main question.
My main question is: Is my logic here correct or incorrect?
Also, if you need me to rephrase the question, I can do that as I understand this might be hard to follow, I'm just panicking a little.
Your logic seems fine, but since code is not at all upto the mark its difficult to verify. I have written code in english commented format, if you are able to fill in the blanks all will fall in place.
Let's breakdown the problem in two sections :
Remove unwanted characters from string
Check if string returned from step1 is a pallindrome.
Create two functions :
String cleanUp(String arg){
//create a stringbuffer from arg
//start for loop
//delete unwanted chars from stringbuffer
//end loop
//make string from stringbuffer and return
}
boolean pallindrome(String arg){
//create a new string from arg reverse
//return true if reversed string and arg are same
}
Now call these functions from your main method.
I'm working on a project for my Programming Applications course with WGU. I've decided to adapt a python-based pig latin converter from the previous course. I've almost got it done, but when I run the program, I get an extra word. For example, if I enter Latin, it prints atinLay, then on the next line, prints inLatay.
I'm not sure which part of the code is causing this. I know it should be a simple fix but I just can't find it. Here is my code:
import java.util.Scanner;
public class PigConverter
{
public static void main(String[] args)
{
Scanner anscay = new Scanner(System.in);
System.out.print("Enter a word:");
String word = anscay.nextLine();
System.out.println("This word, in pig latin, would be:");
String pigConvert;
for (int i=0; i < word.length(); i++)
{
if(word.charAt(i)=='a' || word.charAt(i)=='e' || word.charAt(i)=='i' ||
word.charAt(i)=='o' || word.charAt(i)=='u')
{
String second = word.substring(0,i);
String first = word.substring(i,word.length());
System.out.println(first+second+"ay");
}
}
}
}
I think that your loop is finding BOTH vowels in the word, so it/s doing the output twice. I think that your loop should break once you find the first vowel.
I am creating a java program that uses a cipher to encode any message the user types in. It works flawlessly with single words like "hello" and "testing", but begins to fall apart when you add spaces, like the message "hello world." Here is the code:
import java.util.Scanner;
import java.util.ArrayList;
public class Code {
public static void main(String[] args) {
Scanner shiftValue = new Scanner(System.in);
System.out.print("Please enter shift value: ");
int shift = shiftValue.nextInt();
String alphabet = "abcdefghijklmnopqrstuvwxyz";
Scanner input = new Scanner(System.in);
String codeInput = "anything";
int index = 0;
while(!codeInput.equals("end")) {
System.out.println();
System.out.println("Please enter message: ");
codeInput = input.next();
for(int i = 0; i < codeInput.length(); i++){
if(Character.isWhitespace(codeInput.charAt(i))){
System.out.print(" ");
}
else {
while(alphabet.charAt(index) != codeInput.charAt(i)){
index++;
}
if(index > 25 - shift){
index = index - (26 - shift);
System.out.print(alphabet.charAt(index));
}
else {
System.out.print(alphabet.charAt(index + shift));
}
}
index = 0;
}
}
} //method
} //class
When I type start the program, it asks for a shift value, which decides how many letters to shift the cipher. After that, it goes into a while loop, forever asking the user for input, then outputting an encoded version of the input, until the word "end" is typed. In the eclipse console, it looks like this:
Please enter shift value: 3
Please enter message:
hello
khoor
Please enter message:
testing
whvwlqj
Please enter message:
However, when I type multiple words with spaces between them, it looks like this:
Please enter shift value: 3
Please enter message:
hello world
khoor
Please enter message:
zruog
Please enter message:
For some reason, instead of displaying both words in the same sentence format as the input, it encodes the first word, then goes through the entire while loop again before encoding the second word.
I have no idea why this happens, so I would appreciate any help or advice you guys could give me.
Thank you for reading my post, and have a wonderful day.
The Scanner splits the input for you already and by default by whitespaces.
JavaDoc:
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
So I am doing some problems on the UVa online problem judge, but on a relativity easy problem, I keep on getting a ArrayIndexOutOfBoundsException. To understand the code, here is the problem.
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int t = scan.nextInt();
int sum = 0;
for (int i = 0; i <= t; i++){
String d = scan.nextLine();
if (d.equals("report")) {
System.out.println(sum);
} else {
String[] parts = d.split(" ");
int z = Integer.parseInt(parts[1]);
sum+=z;
}
}
}
}
The error message is:
reportException in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at Main.main(Main.java:16)
And I am using the sample input given.
Edit:
I have already tried added println statements in the code and figured out that the number is not being read. I am trying to understand why.
OK, after some messing around on my machine I think I found what might be at least part of the problem. The issue is that I'm not sure what the precise input is, so I'm going off of what I could get working on my machine.
So you start up your program, and it waits for a prompt at this line:
int t = scan.nextInt();
You enter your integer, and the program moves on as expected:
Input: 100 // Then press enter to continue
The input is parsed, and now t is set to 100.
Then when your program enters your for loop, it comes across this line:
String d = scan.nextLine();
Yet for some reason the program doesn't wait for input! (Or at least it didn't on my machine)
I believe the issue lies here:
Input: 100 // Then press enter to continue
^^^^^^^^^^^
What I think is happening is that your input is really
Input: 100\n
^^
That character (\r\n on Windows) is what's input when you hit enter. It's a newline character that tells the console to go to the next line.
So as a result, what I think happens is this:
Input: 100\n
Scanner parses 100, leaving the \n in the input stream
Then at the nextLine() call, the scanner sees \n on the input stream, which denotes end of line, so it thinks you already input the entire line! Because what it thought was your input was only the newline character, it returns an empty string, because your "input" was an empty string and the newline character. Your program then goes to split the newline character by spaces, rightly returns an array with a single element, and then your program promptly crashes when accessing an out-of-bounds index.
What might work better is reading an entire line first and parsing the integer so your scanner doesn't get ahead of itself, like this:
int t = Integer.parseInt(scan.nextLine());
Just as a warning: This is what I've been able to come up with based on using OP's code as-is on my machine. I was unable to get a situation where the only element in parts was "donate". I will update further as I get more info.
The error message means the array parts's length less than 2, sometimes.
It means the variable d does not always contain the string BLANK SPACE, " ", what you split by.
try this code:
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int t = scan.nextInt();
int sum = 0;
for (int i = 0; i <= t; i++){
String d = scan.nextLine();
if (d.equals("report")) {
System.out.println(sum);
} else {
String[] parts = d.split(" ");
/*
* Add IF statement,
*/
if (parts.length() > 1) {
int z = Integer.parseInt(parts[1]);
sum+=z;
}
}
}
}
}
I'll go ahead and let you know that yes, this is homework. I have hit a brick wall in completing it however and desperately need help. I'm also pretty new to Java and am still learning the language.
Okay, I am trying to write a program that asks the user to enter a sentence with no spaces but have them capitalize the first letter of each word. The program should then add spaces between the words and have only the first word capitalized, the rest should start with a lowercase. I can get the space inserted between the words, but I cannot get the first letter of each word lower-cased. I have tried several different ways, and the latest one is giving me this error message:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String ind
ex out of range: 72
at java.lang.AbstractStringBuilder.setCharAt(Unknown Source)
at java.lang.StringBuilder.setCharAt(Unknown Source)
at renfroKristinCh9PC14.main(renfroKristinCh9PC14.java:45)
I'm posting up my code and any and all help you can give me will be very much appreciated.
Thanks.
/*
This program will ask the user to enter a sentence without whitespaces, but
with the first letter of each word capitilized. It will then separate the words
and have only the first word of the sentence capitalized.
*/
import java.util.*;
public class renfroKristinCh9PC14
{
public static void main(String[] args)
{
//a string variable to hold the user's input and a variable to hold the modified sentence
String input = "";
//variable to hold a character
char index;
//create an instance of the scanner class for input
Scanner keyboard = new Scanner(System.in);
//welcome the user and explain the program
userWelcome();
//get the sentence from the user
System.out.println("\n Please enter a sentence without spaces but with the\n");
System.out.println(" first letter of each word capitalized.\n");
System.out.print(" Example: BatmanIsTheBestSuperheroEver! ");
input = keyboard.nextLine();
//create an instance of the StringBuilder class
StringBuilder sentence = new StringBuilder(input);
//add spaces between the words
for(int i=0; i < sentence.length(); i++)
{
index = sentence.charAt(i);
if(i != 0 && Character.isUpperCase(index))
{
sentence.setCharAt(index, Character.toLowerCase(index));
sentence.append(' ');
}
sentence.append(index);
}
//show the new sentence to the user
System.out.println("\n\n Your sentence is now: "+sentence);
}
/*********************************************************************************** *************************
************************************************************************************ *************************
This function welcomes the user and exlains the program
*/
public static void userWelcome()
{
System.out.println("\n\n **************** ****************************************************\n");
System.out.println(" * Welcome to the Word Seperator Program *");
System.out.println(" * This application will ask you to enter a sentence without *");
System.out.println(" * spaces but with each word capitalized, and will then alter the *");
System.out.println(" * sentence so that there arespaces between each word and *");
System.out.println(" * only the first word of the sentence is capitalized *");
System.out.println("\n ********************************************************************\n");
}
}
You are appending to the same string that you are iterating through. Instead, just make your sentence an empty StringBuilder. Then you can append to that while iterating through input. For example:
StringBuilder sentence = new StringBuilder();
//add spaces between the words
for(int i=0; i < input.length(); i++)
{
char letter = input.charAt(i);
if(i != 0 && Character.isUpperCase(letter))
{
sentence.append(' ');
sentence.append(Character.toLowerCase(letter));
}
else
{
sentence.append(letter);
}
}
(Note that I've changed the variable name from index to letter, which is a lot less confusing.)
You have a few different problems here. The main one is that when you call
sentence.setCharAt(index, Character.toLowerCase(index));
you're passing in the actual character in as the first argument, instead of the position. You see, you've just done
index = sentence.charAt(i);
so index is the character itself. Java implicitly converts this character to an integer - but it's not the integer that you want it to be. You probably should have written
sentence.setCharAt(i, Character.toLowerCase(index));
instead.
Also, your sentence.append(' '); will append the space to the end of the StringBuilder, rather than inserting it where you want it to.
And your final sentence.append(index); will duplicate the character. I really don't think you want to do this.