Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am trying to make a program that accepts a word then displays the word diagonally. So far I've only gotten it to display vertically.
The scanner accepts "zip", then outputs:
z
i
p
How do i make it go like this:
z
i
p
Here is my code:
import java.util.Scanner;
public class exercise_4
{
public static void main(String [] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Please enter your words");
String word = scan.nextLine();
for (char ch: word.toCharArray())
{
System.out.println(ch);
}
}
}
You can try something like this:-
String s = "ZIP";
String spaces = "";
for (int i = 0; i < s.length(); i++) {
System.out.println(spaces + s.charAt(i));
spaces += " ";
}
You can do
String spaces = ""; // initialize spaces to blank first
for (int i = 0; i < word.length(); i++) { // loop till the length of word
spaces = spaces + " "; //
// increment spaces variable
// for first iteration, spaces = ""
// for second iteration, spaces = " "
// for third iteration, spaces = " "
// for fourth iteration, spaces = " " and so on
System.out.println(spaces + word.charAt(i));
// this will just print the spaces and the character of your word.
}
Try this
Scanner scan = new Scanner(System.in);
System.out.println("Please enter your words");
String word = scan.nextLine();
String i = new String();
for (char ch : word.toCharArray()) {
System.out.println(i+ch);
i=i+" ";
}
I would prefer a StringBuilder for concatenation.
String s = "ZIP";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
System.out.println(sb.toString()+ s.charAt(i));
spaces.append(" ");
}
With StringUtils from commons-lang:
int indent = 0;
for (final char c : "ZIP".toCharArray()) {
System.out.println(StringUtils.repeat(" ", indent) + c);
indent++;
}
Related
The following Java program is supposed to manipulate a string input by the user in such a way that the user will decide which character needs to be replaced with another and just the last character from the string should be replaced. Example if the user enters the string "OYOVESTER" and decides to replace "O" with "L", the program should output the following result: "OYLVESTER" (notice that only the last "O" was replaced with "L")
NOTE: YOU CANNOT USE BREAK COMMAND TO STOP THE LOOP. IT IS PROHIBITED.
import java.util.Scanner;
public class StringFun {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the string to be manipulated");
String inString = keyboard.nextLine();
String outString = "";
//Replace Last
System.out.println("Enter the character to replace");
char oldCharF = keyboard.next().charAt(0);
System.out.println("Enter the new character");
char newCharF = keyboard.next().charAt(0);
int count = 0; // variable that tracks number of letter occurrences
for(int index = inString.length() - 1;index >= 0;index--) {
if(inString.charAt(index) == oldCharF && count < 1){
outString = newCharF + outString;
outString = outString + inString.substring(0,index);
count++;
}
if (count < 1) {
outString = outString + inString.charAt(index);
}
}
System.out.print("The new sentence is: "+outString);
}
}
I keep getting the following output which is incorrect:
Enter the string to be manipulated
OYOVESTER
Enter the character to replace
O
Enter the new character
L
The new sentence is: LRETSEVOY
There are many simpler ways to achieve your requirement but I hope you have to demonstrate this with loops (without breaks)
Then you can use some thing like this :
boolean skip = false;
for (int index = inString.length() - 1; index >= 0; index--) {
if (!skip && inString.charAt(index) == oldCharF) {
outString = newCharF + outString;
skip = true;
}
else {
outString = inString.charAt(index) + outString;
}
}
PS : Using String concatenation inside loops is not recommended since
every String concatenation copies the whole String, usually it is preferable to
replace it with explicit calls to StringBuilder.append() or StringBuffer.append()
No break command seems like a weird condition. You could just a boolean value, and other methods, to break the loop when you need. Why not do something like this?
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the string to be manipulated");
String word = keyboard.nextLine();
//Replace Last
System.out.println("Enter the character to replace");
char oldCharF = keyboard.next().charAt(0);
System.out.println("Enter the new character");
char newCharF = keyboard.next().charAt(0);
int index = word.lastIndexOf(oldCharF);
if(index > 1){
word = word.substring(0,index) + newCharF + word.substring(index+1);
}
System.out.println("The new sentence is: " + word);
}
So my task was to create a program that takes a file as input and counts the occurrences of each alphabetic character in it. Then I shall print the letter, the amount of times it occurs and the frequency of it.
And I get it to work almost as planned. The only problem I have is that when I print, it also prints the number of dots(.) in the file. And I can't stop it from doing that. Help please..
public class CountOccurences {
private static Scanner input;
public static void main(String [] args) throws FileNotFoundException {
DecimalFormat dec = new DecimalFormat("#.000");
input = new Scanner(new File("story.txt"));
int[] ltrCtr = new int[127]; // This array counts the number of occurences for every letter / symbol on the ascii table.
String str = "";
// Puts the textfile as a String
while(input.hasNext()) {
str += input.next();
}
char[] text = str.toCharArray();
char temp; int tempInt;
int ctr = 0;
for(int i = 0; i < text.length; i++) { // Loops through the text
temp = text[i]; // Gets the char at i
tempInt = (int)temp; // Get the ascii value of the char at i
ltrCtr[tempInt]++;
if(Character.isAlphabetic(text[i])) {
ctr++;
}
}
System.out.println("Letter" + " Amount" + " Freq");
for(int i = 0; i < ltrCtr.length; i++) {
if(ltrCtr[i] >= 1 && (int)ltrCtr[i] != 46) {
System.out.println(" " + (char)i + " " +
ltrCtr[i] + " " +
dec.format((double)ltrCtr[i]/ctr) + "%");
}
}
input.close();
}
}
I believe you meant to use isLetter, not isAlphabetic.
Mureinik is right, isLetter solves your problem. Here's a post explaining the differences between isLetter and isAlphabetic to make it clearer: What is the difference between Character.isAlphabetic and Character.isLetter in Java?
I'm working my way through a java learning book and at the moment I'm learning about arrays and vectors. I've been doing ok up until now I've been stuck on this question for ages and have no idea how to tackle it, my head is about to explode!
The questions for this certain program I have to tackle are:
Elementary error checking is introduced, specifically check that the array Tokens has two elements, if there is a problem with the format of the data inform the user but carry on accepting input.
It will accept input of either
quit
put name mark
get name
The quit scenario works as before, the second scenario stores the student and their mark at the next
available array index; whilst get just returns the mark of any student who matched to the name ( there
may be more than one such student, there many be none).
The program reads in the mark as an integer not a String (you can find examples of the structure you
need by searching for Integer.parseInt on Google).
Upon typing quit, the mean mark, and the highest mark are also displayed.
The java code is as follows:
import java.util.Scanner;
public class ArrayInput {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
String b;
String student[] = new String[50];
String mark[] = new String[50];
int i = 0;
while ((b = s.nextLine()) != null) {
if (b.equals("quit")) break;
String Tokens[] = b.split(' ');
// System.out.println(Tokens[0] + ' ' + Tokens[1]);
student[i] = Tokens[0];
mark[i] = Tokens[1];
i++;
}
for (int j = 0; j < i; j++) {
System.out.println(student[j] + ' ' + mark[j]);
}
}
}
It also throws out on error on this line:
String Tokens[] = b.split(' ');
use:
b.split("\\s+");
to split on whitespaces.
This will cause any number of consecutive spaces to split your string into tokens as the split() method in java is constructed to be used with regular expressions anyway
I would've written it like this (tried it on IDEONE):
import java.util.Scanner;
public class ArrayInput {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
String b;
String[] student = new String[50]; // changed here
String[] mark = new String[50]; // Changed here
int i = 0;
b = s.nextLine(); // Get the next line here first
while (b != null) { // Evalaute b as for while loop here
if (b.equals("quit")) break;
String[] Tokens = b.split(" "); // Changed to use " ", not ' '
// System.out.println(Tokens[0] + ' ' + Tokens[1]);
student[i] = Tokens[0];
mark[i] = Tokens[1];
i++;
b = s.nextLine(); // get the next line here before looping again.
}
for (int j = 0; j < i; j++) {
System.out.println(student[j] + ' ' + mark[j]);
}
}
}
The Scannerclass has a method called hasNext() which you can use quite helpfully for the while() loops. If you use that the following snippet is improved:
// b = s.nextLine() not needed anymore
while(s.hasNext()){
...
...
...
}
I need help on my code in Java.
This is the problem :
Example input : AaaaaAa
Output : A appears 7.
The problem is I need it to ignore cases.
Please help me, my code works fine, except that it doesn't ignore cases.
import java.io.*;
public class letter_bmp{
public static BufferedReader input = new BufferedReader( new InputStreamReader(System.in));
public static void main(String[] args) throws Exception
{
String string1;
String pick;
String ans;
do
{
int count=0;
System.out.print("En taro Adun, Executor! Input desired string : ");
string1 = input.readLine();
System.out.print("Now, Executor...which character shall I choose : ");
pick = input.readLine();
for(int counter = 0; counter < string1.length(); counter++)
{
if(pick.charAt(0) == string1.charAt(counter))
count++;
}
System.out.print("Executor...you picked '" + pick + "' it is used " + count + " times in the word "+string1+".");
System.out.println("\nWould you like to try again, Executor? (Yes/No): ");
ans = input.readLine();
}
while(ans.equalsIgnoreCase("Yes"));
}
}
Convert the string to lower case characters using the String.toLowerCase() method.
// ...
string1 = input.readLine().toLowerCase();
// ...
pick = input.readLine().toLowerCase();
// ...
The easiest solution is to make 2 new strings like this:
string1_lower = string1.toLowerCase();
pick_lower = pick.toLowerCase();
And use those two variables during comparison.
I understand that the question is old and the OP might have got his answer. But i am putting this out here just in case if anybody needs it in the future.
public static void main(String[] args) {
String s="rEmember";
for(int i = 0; i <= s.length() - 1; i++){
int count = 0;
for(int j = 0; j <= s.length() - 1; j++){
if(Character.toLowerCase(s.charAt(i)) == Character.toLowerCase(s.charAt(j))){
count++;
}
}
System.out.println(s.charAt(i) + " = " + count + " times");
}
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm trying to count the number of words in a String, find the length of each word in a String and then determine the largest word in the String using only the String class. I can't use arrays. Does anyone know a way to extract each word from the string?
int indexOfSpace = 0;
int nextIndexOfSpace = 0;
String sentence = "This is a sentence";
int lastIndexOfSpace = sentence.lastIndexOf(" ");
while(indexOfSpace != lastIndexOfSpace){
nextIndexOfSpace = sentence.indexOf(" ",indexOfSpace);
String word = sentence.subString(indexOfSpace,nextIndexOfSpace);
System.out.println("Word: " + word + " Length: " + word.length());
indexOfSpace = nextIndexOfSpace;
}
String lastWord = sentence.subString(lastIndexOfSpace);
System.out.println("Word: " + lastWord + " Length: " + lastWord.length());
You need to do something along the above lines. Since your question seems like a homework question, I am not going to put an effort into debugging this. This is as far as I can go into answering what seems like a homework question.
Debug it, use it.
Use StringTokenizer
String sentence = "This is a sentence";
StringTokenizer t = new StringTokenizer(sentence);
String word ="";
while(t.hasMoreTokens())
{
word = t.nextToken();
System.out.println(word);
}
The Output should be
This
is
a
sentence
Scanner s= new Scanner("Put your string here");
while(s.hasNext()){
String word= s.next();
}
Edit using only String:
String myString = "hello world how are you";
for (int i = 0, //start of word
j = 0; //end of word
i < myString.length(); //make sure we're in bounds
i = j + 1) { //Start from where we left off plus one
//to get rid of space we just found
j = myString.indexOf(" ", i); //find the next space
if (j == -1) { //-1 means no more spaces so we're done
break;
}
String word = myString.substring(i, j); //here is your word
}
This can be done using the split(" ")//which splits the string(maybe a sentence) by spaces into words and use array list to store List words = Arrays.asList(sentence.split(" "));
A raw version, probably efficient, could be something like this. This assumes that there are single spaces between the words including in the end which can easily be tweaked make it perfect.
int wordCount = 0;
int maxWordLen = 0;
String longestWord = null;
if(input != null){//given word
int currentWordStart = 0;
for(int i = 0; i < input.length(); i++){
char currentChar = input.charAt(i);
if(' ' == currentChar){
wordCount++;
String currentWord = input.substring(currentWordStart, i);
int currentWordLen = i - currentWordStart;
System.out.println("Word: " + currentWord + ", Length: " + currentWordLen);
currentWordStart = i + 1;
if(maxWordLen < currentWordLen){
maxWordLen = currentWordLen;
longestWord = currentWord;
}
}
}
}
System.out.println("Word count: " + wordCount);
System.out.println("Longest word: " + longestWord + ", Length: " + maxWordLen);