I have a script that is supposed to take a String of both numbers and letters and break them down into their ASCII/Hex values under the appropriate column. It works flawlessly until I put a space anywhere in the String. It will print everything normally up to the space and then break with no errors.
Ex. (works):
kdillon76
Ex. (does NOT work):
kdillon 76
In my For Loop I have an If Statement stating that if the character is a digit then "do this" followed by an Else Statement to cover anything "else". Shouldn't the Else Statement be able to translate the space to the "32" ASCII number?
Any and all help is greatly appreciated!
import java.util.*; // Load all Utility Classes
public class DKUnit3Ch12 { // Begin Class DKUnit3Ch12
public static void main(String[] args) { // Begin Main
Scanner myScan = new Scanner(System.in); // Initialize the Scanner
String myInput; // Define a new Variable
System.out.print("Please enter a string of any length: "); //Print the text
myInput = myScan.next(); // Define a new Variable with the next user input
System.out.printf("%n%-8s%-16s%-16s%s%n", "Initial", "ASCII(char)", "ASCII(int)", "Hex"); // Print the labels with proper tablature
for(int x = 0; x < myInput.length(); x++) { // Begin For Loop
char myChar = myInput.charAt(x); // Define a new Variable based on position in index
if(Character.isDigit(myChar)) { // Begin If Statement (if the character is a digit)
System.out.printf("%-24s%-16d%02X%n", myChar, (int)myChar, (int)myChar); // Print the items with proper tablature including capitalized Hex
} // End If Statement
else { // Begin Else Statement (if the character is NOT a digit)
System.out.printf("%-8s%-32d%02X%n", myChar, (int)myChar, (int)myChar); // Print the items with proper tablature including capitalized Hex
} // End Else Statement
} // End For Loop
System.out.print("\nThank you for playing!"); // Print the text
myScan.close(); // Close the Scanner
} // End Main
} // End Class DKUnit3Ch12
From the documentation:
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
Replace myScan.next() with myScan.nextLine()
Related
My program has a String inputted Eg. hello i am john who are you oh so i see you are also john i am happy
my program then has a keyword inputted Eg. i (the program doesn't like capitals or punctuation yet)
then it reads the initial String and finds all the times it mentions the keyword + the word after the keyword, Eg. i am, i see, i am.
with this is finds the most common occurrence and outputs that second word as the new keyword and repeats. this will produce
i am john/happy (when it comes to an equal occurrence of a second word it stops (it is meant to))
What i want to know is how i find the word after the keyword.
package main;
import java.util.Scanner;
public class DeepWriterMain {
public static void main(String[] args) {
String next;
Scanner scanner = new Scanner(System.in);
System.out.println("text:");
String input = scanner.nextLine();
System.out.println("starting word:");
String start = scanner.nextLine();
input.toLowerCase();
start.toLowerCase();
if (input.contains(start)) {
System.out.println("Loading... (this is where i find the most used word after the 'start' variable)");
next = input.substring(5, 8);
System.out.println(next);
}else {
System.out.println("System has run into a problem");
}
}
}
If you use split to split all your words into an array, you can iterate through the array looking for the keyword, and if it is not the last in the array, you can print the next word
String arr [] = line.split(" ");
for (int i = 0; i < arr.length -1; i++) {
if (arr[i].equalsIgnoreCase(keyword)) {
sop(arr[i] + " " arr[i + 1]);
}
if it is not the last in the array, iterate only to length - 1
The String class includes a method called public int indexOf(String str). You could use this as follows:
int nIndex = input.indexOf(start) + start.length()
You then only need to check if nIndex == -1 in the case that start is not in the input string. Otherwise, it gets you the position of the first character of the word that follows. Using the same indexOf method to find the next space provides the end index.
This would allow you to avoid a linear search through the input, although the indexOf method probably does one anyway.
I'm trying to allow the user to put in multiple inputs from the user that contain a char and integers.
Something like this as input: A 26 16 34 9
and output each int added to an array.
I was thinking I could have the first input as a character and then read the rest as a string which then I separate and put into an array.
I'm not new to coding but new to java. I've been doing c++ so the syntax is a bit different.
This is what I have so far, I haven't set up my array yet for the integers.
import java.util.Scanner;
public class Program0 {
public static void main(String[] args) {
int firstNumber;
Scanner reader = new Scanner(System.in);
System.out.println("'A' to enter a number. 'Q' to quit");
int n = reader.nextInt();
if (n=='A') {
//if array is full System.out.println("The list is full!");
//else
System.out.println("Integer " + " " + "has been added to the list");
}
else if (n=='Q') {
System.out.println("List of integers: ");
System.out.println("Average of all integers in the list: ");
}
else{
System.out.println("Invalid Action");
}
reader.close();
}
}
Could you specify better how should your input be given? From your question, if I understand well, the user simply type "A" followed by a list of numbers separated by a space. So I would simply read the next line, split it in words (separated by a space) and check if the first word is the letter "A". Here it goes:
import java.util.Scanner;
public class Program0 {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("'A' to enter a number. 'Q' to quit");
String line = reader.nextLine();
String[] words = line.split(" ");
if (words.length > 0 && words[0].equals("A")) {
//if array is full System.out.println("The list is full!");
// => I don't understand this part
//else
for(int i = 1; i<words.length; i++){
int integer = Integer.parseInt(words[i]);
System.out.println("Integer " + integer + " has been added to the list");
//do your stuff here
}
}
else if (words.length > 0 && words[0].equals("Q")) {
System.out.println("List of integers: ");
System.out.println("Average of all integers in the list: ");
}
else{
System.out.println("Invalid Action");
}
reader.close();
}
}
Note that in your solution, you read the next int from your scanner and then try to compare it with the character 'A'. This will not work because A is not an int. If you really want to get the first character from your scanner, you could do:
String line = reader.nextLine();
if(line.length() > 0){
char firstChar = line.charAt(0);
//do your stuff here
}
A character is not an int. You cannot read an int to expect something like 'A'. You can read a String and take its first character though. Scanner doesn't offer a convenient method to read the next String and expect it to be only one-character long. You'd need to handle that yourself.
But considering you don't know in advance how many numbers there will be to read, your solution to read the entire line and interpret it entirely, is the better one. That means you can't use nextInt() nor nextDouble() nor next() nor nextWhateverElse().
You need nextLine(), and it will give you the entire line as a String.
Then you can split() the result, and check if the first is one-char-long. Then you can parse all the others as int.
I don't immediately recall how to write this in Java – it's been a bit of a while – but what I'd do is to first separate the string by spaces, then attempt to do ParseInt on each piece.
If the string isn't a valid integer, this method will throw an exception, which you can catch. So:
If you make it to the next statement, an exception didn't happen, so the value is an integer.
If, instead, you find yourself in the exception-handler (having caught [only ...] the expected kind of exception, the value is a string.
Of course, don't "catch" any exception-type other than the NumberFormatException that you're expecting.
By the way, it is perfectly routine to use exceptions in this way. Let Java's runtime engine be the authority as to whether it's an integer or not.
I'm looking for help with a question I have. We just started learning simple java in our course after learning a tonne of C++.
One of our bonus missions for people who know code more than what was taught in class.
The mission is as follows: Write a function by the name lettersSeries which gets letters (one letter at a time, assume all letters are lower case) inputted from the user. The function stops accepting letters from the user once the user has inputted 3 consecutive letters. (Only for loops can be used without while loops)
Example: a -> b -> a -> c -> d -> e (Here is stops)
As far I don't know much and I would be happy if someone would help me with this... I tried some options but I have no idea how to trace the alphabet, and especially how to check if letters are consecutive...
Thanks!
public static void letterSeries() {
//We create a scanner for the input
Scanner letters = new Scanner(System.in);
for(Here I need the for loop to continue the letters input) {
//Here I need to know if to use a String or a Char...
String/Char letter = next.<//Char or String>();
if(Here should be the if statement to check if letters are consecutive) {
/*
Here should be
the rest of the code
I need help with
*/
Obviously, you could change the code, and not make my pattern, I would just be happier with an easier way!
Here's how I would tackle the problem, I'm going to let you fill in the blanks with this though so I don't do all of your homework for you.
private void letterSeries() {
Scanner scanner = new Scanner(System.in);
char prevChar;
char currChar;
int amountOfConsecutives = 0;
final int AMOUNT_OF_CONSECUTIVES = 2;
for(;;) {
// Take in the users input and store it in currChar
// Check if (prev + 1) == currChar
// If true, amountOfConsecutives++
// If false, amountOfConsecutives = 0;
// If amountOfConsecutives == AMOUNT_OF_CONSECUTIVES
// Break out of the loop
}
}
You can use chars' Unicode number to check if letters are consecutive: if a and b are your letters, try to check if b - a == 1. If consequentiality is intended in a case-insensitive way ('B' consecutive to 'a') then check: (b - a == 1 || b - a == 33).
Scanner letters = new Scanner(System.in);
char previousChar = '\0';
int consecutive = 1;
for(; consecutive != 3 ;){
char userInput= letters.findWithinHorizon(".", 0).charAt(0);
if (userInput - previousChar == 1){
consecutive++;
} else {
consecutive = 1;
}
previousChar = userInput;
}
I cheated a little bit with this solution. I used a for loop with only the middle part so it acts like a while loop.
Anyway, here's how it works.
The first three lines create a scanner for user input, a consecutive variable that counts how many consecutive letters the user enters, and a previousChar to store the previous character.
"Why does consecutive start at 1?" you might ask. Well if the user enters one letter, it is going to be consecutive with itself.
In the for loop, as long as consecutive != 3, the code is going to run. The first line in the loop we read a character using findWithinHorizon(".", 0).charAt(0). And then the if statement checks whether it is a consecutive letter with the previous character. If it is, add one to consecutive and if not, reset consecutive to one. Lastly, we set previousChar to userInput to prepare for the next iteration.
private void letterSeries() {
Scanner letters = new Scanner(System.in);
String last = "";
int counter = 0;
for (;counter < 2;){
if ( last.equals (last=letters.next())) counter ++;
else counter = 0
}
}
I'm trying to make a pig latin program that:
1. if the input word starts with a consonant, put that consonant at the end of the word and add ay.
2. if the input word starts with a vowel, add ay to the end.
I'm using a while loop to check whether the input is all letters and to keep asking for input until it is. The program compiles with no errors but when I run it an exception keeps coming at the line after the while loop exits saying my index is out of bounds when I try to get the first letter of the word, it seems basic but I dont know why this exception is coming up
import java.util.Scanner;
public class Rev
{
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
String vow = "aeiou";
String ques = "Enter word";
String reply ="";
int counter = 0;
String newword = "";
boolean isword = false;
String let = "";
while(isword)
{
System.out.println(ques);
reply = input.nextLine();
for (int i =0;i<reply.length();i++)
{
let=reply.substring(i,i+1);
if (let.matches("[a-zA-Z]")) counter++;
}
if (counter==reply.length()) isword=true;
}
String first = reply.substring(0,1);
if (!(vow.contains(first))) newword = reply.substring(1,reply.length())+first+"ay";
else newword = reply+"way";
System.out.print("New word is "+newword);
}
}
Your boolean "isword" is set to false at the start, so it skips the while loop entirely. That means the string "reply" is an empty string with zero characters in it, so you can't call substring(0,1) on it. This would require your string "reply" to have at least one character in it. That's what is causing your index out of bounds error.
Change the boolean "isword" to true and you'll start your loop. Then change the if (counter==reply.length()) to change isword to false instead of true, and you'll break out of your while loop.
You never enter the while(isword) loop, as isword is false.
Since reply is still an empty string, trying to get one character from a string with zero characters is causing your problem.
Just initialise boolean isword to true or use a do-while.
If you're serious about a pig Latin translator as a student project, write it in an appropriate language. You could do this in Korn shell in, like, ten lines of code.
while true
do
print Enter word:
read WORD
if [[ $WORD == "^[aeiou]" ]]
then
print "${WORD}ay"
else
INITCONS=$(echo $WORD | sed 's/^(.).*/\1/')
REMAINDER=$(echo $WORD | sed 's/^.//')
print "${REMAINDER}${INITCONS}ay"
fi
done
Hello I am working on an assignment and I'm running into issues I was hoping for a little direction...
The purpose is to have user input a phrase and create an acronym out of that phrase. Anything over three words will be ignored.
I'm having issues with the acronym part, I am able to get the first character and figured that I would loop through the user input and grab the character after a space, but that is not working. All I am getting is the first character, which is obvious because I grab that first, but I can't figure out how to "save" the other two characters. Any help is greatly appreciated.
*********UPDATE************************
So thanks to an answer below I have made progress with using the StringBuilder. But, now if I enter "Your Three Words" the Output is: YYYYYTYYYYYWYYYY
Which is progress but I can't understand why it's repeating those first characters so many times??
I edited the code too.
*********UPDATE*****************************
public class ThreeLetterAcronym {
public static void main(String[] args) {
String threeWords;
StringBuilder acronym = new StringBuilder();
Scanner scan = new Scanner(System.in);
System.out.println("Enter your three words: ");
threeWords = scan.nextLine();
for(int count = 0; count < threeWords.length(); count++) {
acronym.append(threeWords.charAt(0));
if(threeWords.charAt(count) == ' ') {
++count;
acronym.append(threeWords.charAt(count));
}
}
System.out.println("The acronym of the three words you entered is: " + acronym);
}
}
You can't save the other characters because char is supposed to store only one character.
You can use a StringBuilder in this case
StringBuilder acronym = new StringBuilder();
Then in your loop simply replace it with
String[] threeWordsArray = threeWords.split(" ");
for(String word : threeWordsArray) {
acronym.append( word.substring(0, 1) );
}
**updated
You store the character at the current index in space:
char space = threeWords.charAt(count);
Then you compare the value of space with the integer value 3:
if(space < 3)
This will almost certainly never be true. You are asking for the numeric value of a character. Assuming it is a letter it will be at least 65. I suspect that your intention is to store something different in the variable space.