How do I write a simple program that converts numbers into word-numbers, using loops and arrays?
like this: input: 1532
output: One Five Three Two
Here's what I tried:
class tallTilOrd
{
public static void main (String [] args)
{
Scanner input = new Scanner (System.in);
String [] tall = {"null", "en" , "to", "tre", "fire" ,
"fem", "seks", "syv", "åtte", "ni", "ti");
System.out.println("Tast inn et ønsket tall");
int nummer = input.nextInt();
for (int i = 0; i<tall.length; i++)
{
if(nummer == i)
{
System.out.println(tall[i]);
}
}
}
}
Scanner input = new Scanner (System.in);
String in = Integer.toString(input.nextInt());
String [] tall = {"null", "en" , "to", "tre", "fire" , "fem", "seks", "syv", "åtte", "ni", "ti"};
for(char c : in.toCharArray()){
int i = (int) (c-'0');
for (int j = 0; j<tall.length; j++) {
if(i == j){
System.out.print (tall[j] + " ");
}
}
}
I give you a hint:
You could convert your Integer input into a String and then process each Character of that string. Check out the javadoc for String to figure out how to do it ;-)
Now I'm not sure this is the perfect way to do it, but it would be a possible one.
Instead of iterating over the length of your tall array, you need to iterate over the digits of nummer (to do this, check out the methods String.valueOf(int), String.charAt(int) and String.length()). Then use those digits as indices for tall to get their string representation.
A few notes:
In the code you provided, you need to use == instead of =. == is for comparison, = is for assignment.
Instead of looping through the predefined array, loop through the input. Instead of treating the number entered as an int, treat it as a string and then convert each character in the string into a number, which you can use as an index to fetch the corresponding string from your array.
Also, note that println prints a newline each time.
Related
Sorry for the uninformative title, but I'm new to Java and am quite confused about how I should separate a user input (a string) into two different strings.
Essentially, what I want to do is take a user input with two of the same numbers or letters separated by a space, and remove the corresponding numbers or letters from an ArrayList of strings.
Note: the user input can be a single number or letter, and the method for this part must identify that the user input is not a single letter or number.
For example, if I have the (java) code:
Scanner scan = new Scanner(System.in);
String str = scan.nextLine();
the user then input:5 5 (5 space 5)
and if I have an ArrayList:
Arraylist<String> arrList = new ArrayList<String>;
arrList.add("1");
arrList.add("5");
arrList.add("5");
arrList.add("3");
How do I remove the two 5's from arrList?
My first approach was to separate the user input string into two different strings so that I could remove the two strings from the ArrayList of strings. Since both numbers or letters should be identical to each other, I would only need to scan the first integer or letter. However, I'm not quite sure how to write a method that would scan the first integer or letter in a string that consist of two numbers/integers with a space between them.
I would be much appreciated for any help! Thanks!
Simply use Collection::removeIf method:
String number = "5"; // or an user input
arrList.removeIf(item -> number.equals(item)); // number::equals
You can use .split() to split the inputs by space
String str = scan.nextLine();
String[] list = str.split(" ");
Then you can remove inputs using .remove() from ArrayList
for (int i = 0; i < list.length; i++) {
arrList.remove(list[i]);
}
You have at least two options:
Use split():
String[] numbers = str.split(" ");
Use next() instead of nextLine():
String str1 = scan.next();
String str2 = scan.next();
If you take the latter approach, you might add a hasNext() call to handle the case where there's only one string.
According to your explained example, it looks like you only want to remove the first instance of a string item from the ArrayList otherwise you wouldn't want to supply 5 5, something like this:
String ls = System.lineSeparator();
ArrayList<String> arrList = new ArrayList<>();
arrList.add("1");
arrList.add("5");
arrList.add("5");
arrList.add("3");
Scanner scan = new Scanner(System.in);
String str = "";
while (str.equals("")) {
System.out.print("Enter the numerical strings to delete from ArrayList seperated by a whitespace: " + ls
+ "Your Entry: --> ");
str = scan.nextLine();
if (!str.replaceAll("\\s+", "").matches("\\d+")) {
System.out.println("Invalid Entry! Entries must be numerical integer type! (" + str + ")" + ls);
str = "";
}
}
String[] numbers = str.split("\\s+");
// Iterate through all the User Supplied numbers...
for (int i = 0; i < numbers.length; i++) {
// Remove the first instance (only) of the
// current User the supplied number.
for (int j = 0; j < arrList.size(); j++) {
if (arrList.get(j).equals(numbers[i])) {
arrList.remove(j);
break;
}
}
}
// Display the ArrayList when all is done...
System.out.print(String.join(ls, arrList));
If you supply only one 5 then only the first 5 encountered within the ArrayList is removed.
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(" ");
I'm writing a simple tic tac toe game and need to accept user input during their turn. The player should simply provide a set of coordinates for where to place their token (1,1) to (3,3). I am supposed to be able to accept input as either "2 1" or "2,1" or "2, 1". So I need to be able to take their String input and pull out each of the two numbers, regardless of delimiter and use them to assign their token to the specified cell in the 3x3 array.
The major catch is only being able to utilize stuff we've been taught already (this is the first quarter of Java). This is the first seven chapters of Building Java Programs which consists of Scanner, conditionals/logic, loops and arrays. No patterns, matchers, lists, etc.
Is there a way to accomplish this using only the String class, scanner, or arrays?
Just using the String class, you can use String.split() to get an array of strings which can then be parsed to Integers
public class Example{
public static void main(String []args){
String str = "2 1";
// first split the original string on a comma
String[] str_arr = str.split(",");
// if the length is one then there were no commas in the input, so split again on white space
if (str_arr.length == 1){
str_arr = str.split(" ");
}
int[] int_arr = new int[str_arr.length];
// assign the string array to an int array
for (int i = 0; i < str_arr.length; i++){
int_arr[i] = Integer.parseInt(str_arr[i]);
}
// output to console
for (int j : int_arr){
System.out.println(j);
}
}
}
Updated
Forgot to add "" to convert char to String.
Scanner input = new Scanner(System.in);
String userInput;
String[] coordinates = new String[2];
char character;
int length;
userInput = input.nextLine();
length = userInput.length();
if(length > 2){
coordinates[0] = "" + userInput.charAt(0);
character = userInput.charAt(2);
if(character != ',' && character != ' '){
coordinates[1] = "" + character;
}
else{
coordinates[1] = "" + userInput.charAt(3);
}
}
Explained:
We use an Array to store the two positons you need.
We use a Character to store read in input positions.
We get the length of the read input. This is to validate if it is correct. Since the correct input should be at least more than 2 characters.
We know that the first position is valid so we assign it immediately.We also know that the second position cannot be valid so we skip it (charAt(2) and not charAt(1)) Then we check if the third position is valid if not we assign the fourth position.
Goodluck!
So I'm new to programming. I'm using java. Right now I have an assignment I can't solve on a website that teaches java.
This is the assignment
Write a program that returns number of occurrences of a string in another string.
E.g
Input:
First String: the
Second String: The children are playing with their toys because they love it.
Output:
3
Note: You should only use nested loops. Don’t use methods like indexOf or substring.
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
String a = input.nextLine();
String b = input.nextLine();
String z[] = b.split(" ");
int number=0;
for (int i =0; i<z.length; i++){
if (z[i].contains(a))number++;
}
System.out.println(number);
I won't give you too much code, but here are the main talking points:
You need a way to read the input in. This can be accomplished with a Scanner - it's either from STDIN or a file.
You need a way to break up each word in the sentence. String#split will help you with that.
You need a way to ignore the casing of each sentence - toLowerCase() works well here.
You need to loop over each word in one sentence, as well as each occurrence in the other sentence. Consider that String.split produces a String[], and you can iterate over that with any standard for loop.
You need a way to see is a string is contained in another string. String#contains will help - although you want to be very careful on which side you're asking contains a string. For example:
// This will print true
System.out.println("The world".toLowerCase().contains("the"));
// This will print false
System.out.println("the".contains("The world".toLowerCase()));
Try this :
import java.util.Scanner;
public class Occurence {
/**
* #param args
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str1 = input.nextLine();
String str2 = input.nextLine();
int count = 0;
String word[] = str1.split(" ");
for (int i = 0; i < word.length; i++) {
if (word[i].toLowerCase().contains(str2.toLowerCase())) {
count++;
}
}
System.out.println("Occurence = " + count);
}
}
We are asked to do the following:
Receive the first names of your family members (between 3 to 6 members of your family), create an array of String.
Write a static method called generateNewName() as following:
It receives the array of String as a parameter.
It creates a new first name by using the 2nd character of each String from the array
Example: If you enter as first names Rocky, Ashley, Ocarina, Baron, Ernest, the resulting name should be oscar.
Display the names that were entered and newly generated name
This is what I have:
import java.util.Arrays;
import java.util.Scanner;
public class Foothill {
static Scanner input;
public static void main(String[] args) {
input = new Scanner (System.in);
String[] getNames = new String[5];
char Output;
Output = generateNewName(getNames);
System.out.println(Output);
for(int x = 0; x < 5; x++){
System.out.println("Enter 5 names: ");
getNames[x] = input.nextLine();
}
}
public static char generateNewName(String[] getNames)
{
String newS = Arrays.toString(getNames);
char result = '\0';
for(int j = 0; j < getNames.length; j++){
result = (char) (result + newS.charAt(1));
}
return result;
}
}
It is properly taking the input, however it seems to not be executing the generatNewName method. Am I doing something wrong with the types of methods i'm using? Should generateNewName return a string-type? If so, how do I get the second letter of all input strings and concatenate them? Thanks,
Your generateNewName() method should be returning a String, not a char.
Then you would have to change that
char result = '\0';
with
String result = "";
and then you start appending (using +) the letters to the String.
You can also read about StringBuilder, which would make the code more efficient.
Also, String newS = Arrays.toString(getNames); that line doesn't make much sense. You want to be looping through the names you have, not through all the letters of your name.
I would rewrite that loop to something like:
for (int i = 0 ; i < names.length ; i++) {
result += names[i].charAt(1);
}
or, using a for-each loop
for (String name : names) {
result += name.charAt(1);
}
"Enter 5 names:" is misleading. Consider "Enter name " + (x + 1) + " (of " + 5 + "):" or something similar.
But to answer your question: You are running generateNewName before you get any names! It's being executed for an array of only null elements!
Change this:
Output = generateNewName(getNames);
System.out.println(Output);
for(int x = 0; x < 5; x++){
System.out.println("Enter 5 names: ");
getNames[x] = input.nextLine();
}
to this
for(int x = 0; x < 5; x++){
System.out.println("Enter 5 names: ");
getNames[x] = input.nextLine();
}
Output = generateNewName(getNames);
System.out.println(Output);
:)
Also consider renaming your variables to (a) follow naming conventions such as variable names should be lowercase, and (b) to be more indicative of what they hold and what they are (string, char, array, etc.). Such as names or nameArray instead of getNames and newName or outputName instead of Output.
Finally, and as stated by others, you're using and returning a char in the generateNewName, and obviously a name is a string, not a char.
generateNewName should return a String, not a char. A char is a single character, like the letter A.
You can't generate the new name before asking for the old names, right? Within a method, unless you say otherwise (e.g. with a loop), code runs from top to bottom, like a list of instructions.