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()){
...
...
...
}
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);
}
I'm trying to make a short program that converts any string into T H I S F O N T.
For example: "This is a test sentence" turns into "T H I S I S A T E S T S E N T N C E"
I have a StringBuilder inside a while loop, but using finale.insert(i, '\t'); doesn't work.
import java.util.Scanner;
public class Executable {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String x;
int i = 0;
System.out.print("Input text here: ");
x = input.nextLine();
StringBuilder finale = new StringBuilder(x.toUpperCase());
while(i > finale.length()) {
if(finale.substring(i, i) == " ") {
i += 2;
finale.insert(i, '\t');
}
}
System.out.println(finale);
}
}
Any help?
You have a few issues with your code. Before I present an implementation that works, let's look at those other issues.
Your while loop checks if i > finale.length(). Since i = 0 the while loop never has a chance to begin.
You are comparing strings using == and this is not correct. == is used to confirm two objects are equal, not the value of two strings. You would need to use string.equals() instead.
You're doing too much in your loop anyway. Using a simple for loop can accomplish the goal quite simply.
Here is a new loop you can use instead of what you have:
for (int i = 1; i < finale.length(); i++) {
finale.insert(i++, " ");
}
The output: T H I S F O N T
For those unfamiliar with for loops, here's a very simple breakdown of how the above is structured.
The for loop is defined in three parts:
for (variable_to_increment; repeat_until_this_condition_is_met; modify_variable_on_each_iteration) {
// Code to be executed during each pass of the loop
}
First, we define a variable that we can track on each loop: int i = 1. By setting i = 1, we are going to skip the first character in the string.
The next statement, i < finale.length() means that we want to keep repeating this loop until we reach the length of our string. For example, if the string is 5 characters long and we've run the loop 4 times, i now equals 5 and is no longer less than the string's length, so the loop ends.
The last part is i++. This tells Java what we want to do with i after each loop. In this case, we want to increment the value by 1 each time the loop repeats.
Everything inside the brackets is, obviously, the code we want to execute on each loop.
You're saying while i>finale.length() but i is initialized as 0. You never enter the while loop.
Some issues with your code (see inline comments):
import java.util.Scanner;
public class Executable {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String x;
int i = 0;
System.out.print("Input text here: ");
x = input.nextLine();
StringBuilder finale = new StringBuilder(x.toUpperCase());
while(i > finale.length()) { // this condition is incorrect. Initially
// this condition will always be false
// if you input some sentence. It should be
// i < finale.length()
if(finale.substring(i, i) == " ") { // here preferably you should use
// equals method to compare strings
i += 2;
// you are only incrementing the i if the ith
// substring equals " ". Firstly, substring(i,i)
// will return empty string because the second argument
// is exclusive
finale.insert(i, '\t');
}
}
System.out.println(finale);
}
}
If you want to have an alternate method (not very optimal) for doing what you want to do, you can try the following approach:
import java.util.Scanner;
public class Executable {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String x;
int i = 0;
System.out.print("Input text here: ");
x = input.nextLine();
String finale = x.toUpperCase().replaceAll(" ","").replaceAll("", " ");
System.out.println(finale);
}
}
First, convert the string to uppercase --> then remove all spaces between the words --> then insert spaces between all letters. The code line which does this is,
String finale = x.toUpperCase().replaceAll(" ","").replaceAll("", " ");
Here is a sample run:
Input text here: This is a sentence
T H I S I S A S E N T E N C E
The correct way with your method would be, just increment until you have twice the size of the initial String
while (i < x.length() * 2) {
finale.insert(i, '\t');
i += 2;
}
An easier way would be with a classic for-loop:
StringBuilder finale = new StringBuilder();
for (char c : x.toUpperCase().toCharArray()) {
finale.append(c).append('\t');
}
Use a for loop since you know the number of iterations:
Scanner input = new Scanner(System.in);
String x;
System.out.print("Input text here: ");
x = input.nextLine();
StringBuilder finale = new StringBuilder(x.toUpperCase());
int len = finale.length();
for (int i = 1; i < 2 * len; i+=2 ) {
finale.insert(i, '\t');
}
System.out.println(finale);
You are comparing strings with ==. Never do that; use equals instead.
For future readers: this job can be done elegantly using Java 8 Streams:
String result = str.chars()
.filter(i -> i != ' ')
.mapToObj(t -> (char) t)
.map(Character::toUpperCase)
.map(Character::valueOf)
.collect(Collectors.joining(" ");
This is my second question here and still a beginner so please bear with me.
I have this code of a very basic hangman type game.I have changed the characters to "-",I am able to get the indices of the input but I am not able to convert back the "-" to the characters entered.
Its an incomplete code.
String input;
String encrypt = line.replaceAll("[^ ]","-");
System.out.println(encrypt);
for (int j=0;j<10;j++){ //Asks 10 times for user input
input = inpscanner.nextLine();
int check = line.indexOf(input);
while (check>=0){
//System.out.println(check);
System.out.println(encrypt.replaceAll("-",input).charAt(check));
check = line.indexOf(input,check+1);
}
Here is how it looks like:
You have 10 chances to guess the movie
------
o
o
o
L
L
u //no repeat because u isn't in the movie.While 'o' is 2 times.
I would like to have it like loo---(looper).
How can I do like this "[^ ]","-" in case of a variable?
This might help.
public static void main(String[] args) {
String line = "xyzwrdxyrs";
String input;
String encrypt = line.replaceAll("[^ ]","-");
System.out.println(encrypt);
System.out.println(line);
Scanner scanner = new Scanner(System.in);
for (int j=0;j<10;j++) { //Asks 10 times for user input
input = scanner.nextLine();
//int check = line.indexOf(input);
int pos = -1;
int startIndex = 0;
//loop until you all positions of 'input' in 'line'
while ((pos = line.indexOf(input,startIndex)) != -1) {
//System.out.println(check);
// you need to construct a new string using substring and replacing character at position
encrypt = encrypt.substring(0, pos) + input + encrypt.substring(pos + 1);
//check = line.indexOf(input, check + 1);
startIndex = pos+1;//increment the startIndex,so we will start searching from next character
}
System.out.println(encrypt);
}
}
I need to write for loop to iterate through a String object (nested within a String[] array) to operate on each character within this string with the following criteria.
first, add a hyphen to the string
if the character is not a vowel, add this character to the end of the string, and then remove it from the beginning of the string.
if the character is a vowel, then add "v" to the end of the string.
Every time I have attempted this with various loops and various strategies/implementations, I have somehow ended up with the StringIndexOutOfBoundsException error.
Any ideas?
Update: Here is all of the code. I did not need help with the rest of the program, simply this part. However, I understand that you have to see the system at work.
import java.util.Scanner;
import java.io.IOException;
import java.io.File;
public class plT
{
public static void main(String[] args) throws IOException
{
String file = "";
String line = "";
String[] tempString;
String transWord = ""; // final String for output
int wordTranslatedCount = 0;
int sentenceTranslatedCount = 0;
Scanner stdin = new Scanner(System.in);
System.out.println("Welcome to the Pig-Latin translator!");
System.out.println("Please enter the file name with the sentences you wish to translate");
file = stdin.nextLine();
Scanner fileScanner = new Scanner(new File(file));
fileScanner.nextLine();
while (fileScanner.hasNextLine())
{
line = fileScanner.nextLine();
tempString = line.split(" ");
for (String words : tempString)
{
if(isVowel(words.charAt(0)) || Character.isDigit(words.charAt(0)))
{
transWord += words + "-way ";
transWord.trim();
wordTranslatedCount++;
}
else
{
transWord += "-";
// for(int i = 0; i < words.length(); i++)
transWord += words.substring(1, words.length()) + "-" + words.charAt(0) + "ay ";
transWord.trim();
wordTranslatedCount++;
}
}
System.out.println("\'" + line + "\' in Pig-Latin is");
System.out.println("\t" + transWord);
transWord = "";
System.out.println();
sentenceTranslatedCount++;
}
System.out.println("Total number of sentences translated: " + sentenceTranslatedCount);
System.out.println("Total number of words translated: " + wordTranslatedCount);
fileScanner.close();
stdin.close();
}
public static boolean isVowel (char c)
{
return "AEIOUYaeiouy".indexOf(c) != -1;
}
}
Also, here is the example file from which text is being pulled (we are skipping the first line):
2
How are you today
This example has numbers 1234
Assuming that the issue is StringIndexOutOfBoundsException, then the only way this is going to occur, is when one of the words is an empty String. Knowing this also provides the solution: do something different (if \ else) when words is of length zero to handle the special case differently. This is one way to do this:
if (!"".equals(words)) {
// your logic goes here
}
another way, is to simply do this inside the loop (when you have a loop):
if ("".equals(words)) continue;
// Then rest of your logic goes here
If that is not the case or the issue, then the clue is in the parts of the code you are not showing us (you didn't give us the relevant code after all in that case). Better provide a complete subset of the code that can be used to replicate the problem (testcase), and the complete exception (so we don't even have to try it out ourselves.
I'm trying to write my own Java word count program. I know there may already be a method for this, but I'd like to get it work. I'm getting an out of bounds error at line 14. I'm trying to use an input word to count how many times it appears in an input string. So I'm looping up to stringlength - wordlength, but that's where the problem is.
Here is the code:
import java.util.Scanner;
public class wordcount {
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.print( "Enter word : " );
String word = s.nextLine();
Scanner t = new Scanner(System.in);
System.out.print("Enter string: ");
String string = t.nextLine();
int count = 0;
for (int i = 0; i < string.length()-word.length(); i = i+1){
String substring = string.substring(i,i+word.length());
if (match(substring, word)==true){
count += 1;
}
}
System.out.println("There are "+count+ " repetitions of the word "+word);
}
public static boolean match(String string1, String string2){
for (int i=0; i<string1.length(); i+=1){
if (string1.charAt(i)!=string2.charAt(i)){
return false;
}
}
return true;
}
}
First of all, two Scanners are not necessary, you can do many inputs with the same Scanner object.
Also, this if condition
if (match(substring, word) == true)
can be rewritten like
if (math(substring, word))
I would also recommend you to use i++ to increase the loop variable. Is not strictly necessary but is "almost" a convention. You can read more about that here.
Now, about theIndexOutOfBoundsException, I've tested the code and I don't find any input samples to get it.
Besides, there is an issue, you are missing one iteration in the for:
for (int i = 0; i < string.length() - word.length() + 1; i++) { // Add '+ 1'
String substring = string.substring(i, i + word.length());
// System.out.println(substring);
if (match(substring, word)) {
count++;
}
}
You can test it by putting a print statement inside the loop, to print each substring.
I'm not getting an out of bounds error, can you tell me what values you were using for word and string?
I have identified a bug with your program. If word is equal to string, it still returns count 0. I suggest adding one more iteration and using regionMatches instead. RegionMatches makes your match method obsolete and will return false if word.length() + i is equal or greater than string.length(), avoiding out of bounds issues.
As you can see I also moved the calculations to a seperate method, this will make your code more readable and testable.
And as Christian pointed out; you indeed do only need one Scanner object. I've adapted the code below to reflect it.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter word : ");
String word = sc.nextLine();
System.out.print("Enter string: ");
String string = sc.nextLine();
int count = calculateWordCount(word, string);
System.out.println("There are " + count + " repetitions of the word " + word);
}
private static int calculateWordCount(String word, String string) {
int count = 0;
for (int i = 0; i < string.length() - word.length() + 1; i++) {
if (word.regionMatches(0, string, i, word.length())) {
count++;
}
}
return count;
}