have to do an exercise called SpanishNumbers. Create a SpanishNumbers application that displays numbers 1 through 10 in Spanish. A method with an int parameter should display the Spanish word for the number passed. A loop structure in the main() method should be used to call the method ten times. The Spanish word equivalents for numbers 1 through 10 are:
1 uno, 2 dos, 3 tres, 4 cuatro, 5 cinco, 6 seis, 7 siete, 8 ocho, 9 nueve, 10 diez.
package chapter7java;
import java.util.Scanner;
/**
*
* #author Eric
*/
public class SpanishNumbers {
public static void spanNum(int num, String word) {
for (int i = 1; i<= num; i++) {
if (num = 1) {
System.out.println("Uno");
}
}
}
public static void main (String [] args) {
for (int i = 1; i<=10; i++) {
System.out.println(i);
}
}
}
So before you freak out, I'm having trouble even starting this thing so maybe give me some tip hows I can do what it asks, not finish the work necessarily. What I posted was just crap so just let me know how I can go about starting this. Thanks in advance! This is beginner java so keep it simple.
The function spanNum needs only an int as a parameter. Remove the String parameter passed to it. Replace
public static void spanNum(int num, String word) {
with
public static void spanNum(int num) {
The spanNum function is supposed to print the Spanish for one number (the one passed in parameter num). So there should be no loop. Also = is an assignment statement, not a comparison operator. The comparison operator is ==. So the statement to test if num is equal to 1 would be if(num == 1).
In the main, you could call spanNum in the loop for all values of i.
You're going to want to create an array to hold your spanish numbers.
String[] numbers = {"uno", "dos", "tres", ......}
Declare that inside your spanNum method; you then just print out the value at index i to convert it into spanish. Just remember that array indices start at 0, so you'll need to shift
your index by one.
First of all, the line if(num = 1) should be if(num == 1) since = assigns and == compares. Second, when you are planning to take one number and do different things based on its value, a switch block may be more useful than multiple if...else if blocks. Third, in your main method, you are simply outputting the loop control variable, i, each time instead of calling spanNum().
Related
I have a 2d array and I'm trying to find the largest string only in the second column of the 2d array, but for some reason it only gives me the first string in the 2nd column even if there is a bigger string. Here's what I have:
class Main{
public static void main(String[] args) {
String[][] data = {
{"Jeep", "Wrangler", "35000"},
{"Honda", "civic", "25000"},
{"Toyota", "Corolla", "22000"}
};
LargestName(data);
}
public static void LargestName(String[][] a){
String largestN = a[0][1];
for(int i = 0; i < a.length; i++){
if(largestN.compareTo(a[i][1])<0){
largestN = a[i][1] + "";
}
}
System.out.println(largestN);
}
}
Again, I'm trying to compare the strings only in the second column of the 2d array but with what I have it only gives me the first string of the 2nd column "Wrangler", even if there is a larger string in the 2nd column. Please help
I cannot see a flaw in the code. So look at the definition of 'largest string': It is possible that the code really returns exactly that value that you chose in the beginning.
This can be easily tested by choosing a different start value.
On top of that you could add more System.out.println, or even better use a debugger to step through your code. This will give you a very good understanding of how the JVM executes your code.
You need to comapre length, compareTo is not good choice, please look what are you trying to do:
System.out.println("Wrangler".compareTo("civic"));
System.out.println("civic".compareTo("Corolla"));
System.out.println("Corolla".compareTo("Wrangler"));
result:
-12 32 -20
This question already exists:
Generating a 4 digit number with an increment of 1 (java) [closed]
Closed 1 year ago.
trying to create a unique code and apart of the code format is generating a 4 digit sequence number. (increment of 1) so it would produce XX0001, XX0002.
was messing around more to do the sequence one but erm i cant seem to do it but this is what i have that doesn't work ;c
i did this but it generated xx0001 for all my items:
int number = 0;
String s = String.format("%04d", ++number);
stringBuilder.append(s);
return stringBuilder.toString();
Make number field static.
Since you are calling function it recreates it several times every time with number equal to zero.
While incrementing the value, you should do it in a loop.
for (int number = 0; number < 9999; number++) {
// not writing the code here intentionally, try to figure it out and you will do it.
// hint: append in the string builder
}
you can replace 9999 with your desired last value of the sequence.
Since you are always initializing number as 0, It will always be 1.
So the number should always be incremented by one, therefore you need to keep track of it when you access it in the function. So static variable is used. Check below the example.
class Main {
public static void main(String[] args) {
System.out.println(BuildCode());
System.out.println(BuildCode());
System.out.println(BuildCode());
}
static int number = 1; // Static variable, to keep track of latest number
public static String BuildCode() {
String code = String.format("%04d", ++number);
return code;
}
}
Note: you can create the function BuildCode and pass an int num argument which indicated the latest number used - This number can be obtained from the database, File, or a static variable - .
The output numbers are displayed from 1 to max, one per line with the following exceptions:
numbers divisible by a are replaced with the word "Flip"
the numbers divisible by b are replaced with the word "Flop"
numbers divisible by both are replaced by "FlipFlop"
I am stuck and need a little direction to where my problem is. I thought maybe a for loop would be perfect to go through and list the numbers and have the if else to check each number with the input numbers picked by the user.
import javax.swing.JOptionPane;
public class FlipFlop {
public static void FlipFlop(Integer a, Integer b, Integer Max) {
for (int i = 1; i < Max; i++) {
if (i % a == 0) {
System.out.println("Flip");
} else if (i % b == 0) {
System.out.println("Flop");
} else if (i % a == 0 && i % b == 0) {
System.out.println("FlipFlop");
} else {
System.out.println(i);
}
System.out.println();
}
}
public static void main(String[] arg) {
Integer a;
Integer b;
Integer max;
String Title = "FlipFlop Assignment";
String data = JOptionPane.showInputDialog(null, "Enter your first number", Title, 1);
a = new Integer(data);
data = JOptionPane.showInputDialog(null, "Enter your second number", Title, 1);
b = new Integer(data);
data = JOptionPane.showInputDialog(null, "Enter the upper bound", Title, 1);
max = new Integer(data);
FlipFlop(a, b, max);
}
}
Integer, not integer. That makes max undefined in the first function. Also look into int.
You never actually assign anything to max
All those println functions, you never defined Flip, Flop and FlipFlop. Presumably they're either missing string constants or just plain string literals. (actually your case is even worse, FlipFlop is your function so you're passing the function reference which I bet confuses Java even more)
The flipflop case should come before the other two. Pen and paper should trivially explain why.
There are a few issues here, but the overall code is very close to what you want.
integer max; is creating a variable using an unreal type, I believe you want to be using the passed in variable Max which has a capital 'M'. Be careful of case sensitivity with variables. Generally non-final variables should start with a lower-case letter to prevent confusion.
If you delete the integer max and change your method's Max to max it solves some of your trouble, because right now you aren't using the passed in Max value at all. Unless you yourself have created a class named "integer" you cannot create variables using it.
You are not checking equality in your if statements, you are trying to assign a value. The '=' is trying to assign a value, you want '==' which checks for value equality.
You should move the if statement checking for both Flip and Flop first, because as it is if both are true, only "Flip" will print.
Last, nothing will print at all right now because you don't have Flip, Flop, or FlipFlop inside quotes. You will get a compiler error because there is no variable or class named Flip, or Flop. System.out.println("Flip"); is what you want.
Very new to Java: Trying to learn it.
I created an Array and would like to access individual components of the array.
The first issue I am having is how to I print the array as a batch or the whole array as indicated below? For example: on the last value MyValue4 I added a line break so that when the values are printed, the output will look like this: There has to be a better way to do this?
MyValue1
MyValue2
MyValue3
MyValue4
MyValue1
MyValue2
MyValue3
MyValue4
The next thing I need to do is, manipulate or replace a value with something else, example: MyValue with MyValx, when the repeat variable is at a certain number or value.
So when the repeat variable reaches 3 change my value to something else and then change back when it reaches 6.
I am familiar with the Replace method, I am just not sure how to put this all together.
I am having trouble with changing just parts of the array with the while and for loop in the mix.
My Code:
public static String[] MyArray() {
String MyValues[] = { "MyValue1", "MyValue2", "MyValue3", "MyValue4\n" };
return MyValues;
}
public static void main(String[] args) {
int repeat = 0;
while (repeat < 7) {
for (String lines : MyArray()) {
System.out.println(lines);
}
repeat = repeat + 1;
if (repeat == 7) {
break;
}
}
}
Maybe to use for cycle to be shorter:
for (int i = 0; i < 7; i++) {
for (String lines : MyArray()) {
// Changes depended by values.
if (i > 3) {
lines = MyValx;
}
System.out.println(lines); // to have `\n` effect
}
System.out.println();
}
And BTW variables will start in lower case and not end withenter (\n). So use:
String myValues[] = {"MyValue1", "MyValue2", "MyValue3", "MyValue4"};
instead of:
String MyValues[] = { "MyValue1", "MyValue2", "MyValue3", "MyValue4\n" };
and add System.out.println(); after eache inside cycle instead of this:
MyValues[n] = "value";
where n is the position in the array.
You may consider using System.out.println() without any argument for printing an empty line instead of inserting new-line characters in your data.
You already know the for-each loop, but consider a count-controlled loop, such as
for (int i = 0; i < lines.length; i++) {
...
}
There you can use i for accessing your array as well as for deciding for further actions.
Replacing array items based on a number in a string might be a bit trickier. A regular expression will definitely do the job, if you are familiar with that. If not, I can recommend learning this, because it will sure be useful in future situations.
A simpler approach might be using
int a = Integer.parseInt("123"); // returns 123 as integer
but that only works on strings, which contain pure numbers (positive and negative). It won't work with abc123. This will throw an exception.
These are some ideas, you might try out and experiment with. Also use the documentation excessively. ;-)
This question already has answers here:
While loop doesn't run a indexOf search
(4 answers)
Closed 8 years ago.
I'm trying to find out how many times one string appears in another. For my testing, I'm using "ea" for wordOne and "Ilikedthebestontheeastbeachleast" for wordTwo. My output is returning 2 for my "appearance" variable, which should store how many times "ea" appears in wordTwo. It should return 3.
I've tried messing with variable initializations, and trying to think of the math differently, but I'm pretty much out of ideas.
Here's the relevant code section:
int wordTwoLength = wordTwo.length();
System.out.println(wordTwoLength);
while (wordTwoLength > 0)
{
positionCount = wordTwo.indexOf(wordOne, positionCount);
appearances++;
wordTwoLength = (wordTwoLength - positionCount);
}
System.out.println(appearances);
Thanks!
Edit: I forgot to add that I tried other test inputs and got crazy outputs. It would return numbers way higher than expected for some, and lower for others.
So now the problem is that .indexOf still returns the true index of "ea" in wordTwo - it doesn't take into account where you start from. Also, setting positionCount equal to where you find the word and then searching from that position again is just going to make you immediately find the same instance of that word, not the next one.
The index of the first instance of "ea" in wordTwo is 18, so wordTwoLength will be set to 32-18, or 14. Then you'll find the same instance of ea in wordTwo, and wordTwoLength will be set to 14-18, or -4. Then you'll exit the while loop, with appearances being 2.
for (int index = 0; (index = wordTwo.indexOf(wordOne, index)) > -1; index ++)
appearances ++;
Try this simpler code:
class Demo{
public static void main(String[] args){
String wordOne = "ea";
String wordTwo = "Ilikedthebestontheeastbeachleast";
String[] arr = wordTwo.split(wordOne);
int cnt = arr.length - 1;
System.out.printf("[%s] has occured for %s time(s) in [%s]", wordOne, cnt, wordTwo);
}
}
You can simplify your above work by "Converting String to Character array".Because it will be more Efficient(I think).I have provided a sample code here,
String wordOne="Ilikedthebestontheeastbeachleast";
String wordTwo="ea";
int count=0;
char[] arrayOne=wordOne.toCharArray();
char [] arrayTwo=wordTwo.toCharArray();
for(int i=0;i<=((arrayOne.length)-1);i++)
{
if(arrayTwo[0]==arrayOne[i]&&arrayTwo[1]==arrayOne[i+1])
count+=1;
}
System.out.println("Pattern found "+count+" times.");
This will suits your need but using For loop.