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.
Related
just doing an assignment and to sum it up:
I need to get a users ID which is an int and make sure the first number is 4.
I have tried to do this by converting the id (int from the object in the main method) into the char array.
I print out the index[0] to console and it says 4, great right?
But i have made an if statement that then says if index[0]of the array is 4 then do something... it doesn't seem to acknowledge index 0 is 4 and proceeds to do whats in the else block.
public boolean checkID()
{
int convert = getId(); //get id is 44444
char[] idArray = String.valueOf(convert).toCharArray();
System.out.println(idArray[0]); // this returns a value of 4 in the console
boolean check = false;
if(idArray[0] == 4)
{
check = true;
System.out.println("Id starts with 4!");
}
else
{
check = false;
throw new IllegalArgumentException("Id does not start with 4");
}
return check;
}
}
Of course in the console i receive the illegal argument exception but also 4 printed out?
Sorry if this is a silly problem i have been looking at it for so long and its abit blurry now haha!
Possibly there is a better way?
Thanks in advance!
You are trying to compare an int with a char.
You have converted your int to an array of char, so the right way to see whether the first element in your array is equal 4 or not, you need to make it a char and put it inside single quotes like this:
if(idArray[0] == '4')
{
check = true;
System.out.println("Id starts with 4!");
}
Thanks!
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
hello i worked on a recursive method to convert from int to string fully manual way, and i wanna know if that recursive method is efficient or not, and if you could help me to improve the code. Im new to algorithms so don't blame me if something looks like ugly... I've search on the internet but never looked for something like that :
public class IntToString {
public static String intToString(int number) {
return intToString(number, "", false);
}
private static String intToString(int number, String answer,
boolean isNegative) {
if (number < 0 && isNegative == false) {
isNegative = true;
number = -number;
}
if (number == 0)
if (isNegative)
return "-" + answer;
else
return answer;
System.out.println(number);
return intToString(number / 10, answer = number % 10 + answer,
isNegative);
}
// test
public static void main(String[] args) {
String ans = intToString(-324234);
System.out.println(ans);
}
}
No, it's not very efficient. Though it could be worse. At least it's still O(N) where N is the number of decimal digits in the given number.
invertInt is not really needed. You are using it because you are appending it to the answer that you pass down the the recursions, which will cause that number to be inverted. But there are at least two other ways to do it so that it won't be inverted.
If you note, there is only a very slight difference between the the way you handle negative numbers and positive numbers. Perhaps you can just run the same procedure for both of them, if you remember that processing a negative number is the same as processing its positive opposite, and tacking the - when you're done.
There is no reason for all the flags for negative and inversion. Both of them are only done at the top level. So you can do those things at the intToString(int number) function and not in your recursive function, and save yourself a lot of condition checking, and of course, the replaceAll() call.
There is no need to pass down the answer. You can base your return value on what the recursive call returned. Remember that for numbers like 1,2,3, you'll get the string '1','2','3'. So if you have 23, and you pass down 2, you can use the 2 you got to build your answer.
Your algorithm does not return the correct answer for 0. It's the correct answer when you think in recursive terms, but not when you call it with 0 from main. There are at least two ways to handle that.
And a bit of style advice:
Always indent your code properly.
You don't need to compare boolean values to true or false. If you have a boolean variable x, you can use if (x) or if (!x) rather than if (x==true) and if (x==false). Name your boolean variables in a way that will make this more intuitive, like isNegative or needsInversion. An if (isNegative) makes sense when you read it.
More detailed information in case you could not find the solution:
How do we avoid the inversion? There are two ways, basically. If you insist on passing down the answer, then instead of:
answer += num % 10;
Use:
answer = ( num % 10 ) + answer;
That is - append it to the left of the answer, not its right.
The approach I prefer is using the answer from the lower level. Suppose you have the number 123. So you pass down 12, and you get back the answer "12". Then you can use
return answer + ( num % 10 );
which will give you "123". This time, it's appended to the right.
Finally, here is the complete solution:
public static String intToString( int n ) {
if ( n == 0 ) {
return "0";
} else if ( n < 0 ) {
return "-" + positiveIntToString( -n );
} else {
return positiveIntToString(n);
}
}
private static String positiveIntToString( int n ) {
if ( n == 0 ) {
return "";
} else {
return positiveIntToString( n / 10 ) + ( n % 10 );
}
}
You have the public function that is what you expose to the world. The recursive function is private, and it is only called for positive numbers. If called with zero, it will return an empty string, which is good for the recursion, but not as a real solution.
So the public function first checks two possible issues. If the number is zero, it shouldn't be passed to the private function because it will not return the correct answer. Instead, just return the string "0", as it is the correct answer.
For a negative number, all we need to do is do the work for its counterpart, -n, which is positive and so will be acceptable to the private function. And then we add the "-" in front.
The recursive function for positive integers then becomes very simple: if it's zero, return empty string. For anything else, call itself with n/10, tack the n%10 to the right side of the result, and return that.
Here is also an alternative solution, without a private method:
public static String intToString( int n ) {
if ( n == 0 ) {
return "0";
} else if ( n < 0 ) {
return "-" + intToString( -n );
} else if ( n < 10 ) {
return "" + (n%10);
} else {
return intToString(n/10) + (n%10);
}
}
I actually consider this to be a slightly less efficient solution, because we do two more checks on each level. The check for negative will only be true once, at the top level. The check for zero will only be true if the function is called with zero in the first place. The check for single digit numbers is the current recursion end (because we can't stop the recursion at zero, otherwise we'll always get an extra "0" at the beginning).
I know how to use substring() but why isn't this working, the user inputs an equation like
"5t + 1" with a space before and after the "+". I want tVariable to hold the integer before it, in this case 5 and constant should hold the constant integer in this case 1, but I get an out of range error.
import java.util.*;
import javax.swing.JOptionPane;
public class project3030 {
public static void main(String[] args) {
String L1x, tVariable, constant;
L1x = JOptionPane.showInputDialog("This is the format (x=5t + 1)");
int endIndex = L1x.indexOf("t");
tVariable = L1x.substring(0, endIndex);
int beginIndex = L1x.lastIndexOf(" ");
int endIndex2 = L1x.indexOf("");
constant = L1x.substring(beginIndex, endIndex2);
System.out.println(tVariable + constant);
}
}
You need to change it to something more like
constant = L1x.substring(L1x.lastIndexOf(" ")).trim();
Then when you add the numbers, you have to Parse them before you add them.
int constantInt = Integer.parseInt(constant);
Or you could use this solution:
String[] input = L1x.split(" ");
// remove the 't'
String tNum = input[0].substring(0, input[0].length() - 1);
int t = Integer.parseInt(tNum);
int constant = Integer.parseInt(input[2]);
String operator = input[1];
if (operator == "-")
constant *= -1;
The reason you are getting this error is because your substring() range is off.
You are passing into substring() an invalid range because the first index is beginIndex which you set equal to lastIndexOf(" ") while endIndex2 you set equal to indexOf("") which will occur at the beginning of the string.
Thus, you have your ranges mixed up. When you make this statement:
constant = L1x.substring(beginIndex, endIndex2);
You're giving it an invaid range
and will cause the specified error.
You could also do it different way. Let's say you create a JFrame and there you could put a textfield for every value, so for every "t" or constants, and then it would be much more simple to get those values. For characters like t or = you could use JLabels, so it would be a mixture of JTextFields and JLabels and I think it wouldn't be that ugly. I used this solution few times.
I'm new to Java so I'm trying to write random programs to figure it out. I'm trying to write something that takes as user-input a quadratic equation like so: x^2 + 3x -1
Maybe this is too advanced (or maybe it isn't) but I'm wondering how to extract the characters one-by-one in a loop. If it was all digits I think I could use .isDigit() and save them to an array, but because they're different data types I'm not sure how to go about doing this. My 'code' so far looks like this
import java.lang.String;
import java.lang.StringBuffer;
import java.util.Scanner;
import java.lang.Character;
public class Lab
{
public static void main(String[] args)
{
Scanner user_input = new Scanner(System.in);
System.out.print("Please input the quadratic equation (ex: 2x^2 + 3x - 2): ");
String request = user_input.nextLine();
int myArr[];
String lettArr[];
for (int i = 0; i <= request.length(); i++)
{
String c = request.charAt(i);
if (request.isDigit(c))
{
myArr[1] += c;
}
if(request.isLowerCase(c))
{
lettArr[1] += c;
}
}
System.out.println(myArr[0]);
}
}
my .isDigit() and .isLowerCase() methods are not working. I think I'm using them in the right sense. This is pretty complex for my level and I'm wondering if this is a dead-end or an acceptable strategy.
Thanks.
I think what your are trying to do is to extract the coefficients from the user input. Your approach might work but there would be many case that you have to consider (+/- signs for example). Instead why don't you try Java's regular expressions
String input = "2x^2 - 4x + 1";
input = input.replaceAll("\\s", ""); //removes all whitespaces
Pattern p = Pattern.compile("(-?\\d+)x\\^2((\\+|-)\\d+)x((\\+|-)\\d+)");
Matcher m = p.matcher(input);
if (!m.matches()) {
System.out.println("Incorrect input");
return;
}
int a, b, c;
a = Integer.parseInt(m.group(1));
b = Integer.parseInt(m.group(2));
c = Integer.parseInt(m.group(4));
System.out.println(String.format("a=%d, b=%d, c=%d", a, b, c));
You can adapt this fragment and use it in your code. I , however, supposed that your coefficients are integer numbers. If you need them, instead, to be double you have to change the format of the given regex and also to change Integer.parseInt to Double.parseDouble. I could write this in more details if you are interested.
There are a few things wrong with your code:
public class Lab
{
public static void main(String[] args)
{
Scanner user_input = new Scanner(System.in);
System.out.print("Please input the quadratic equation (ex: 2x^2 + 3x - 2): ");
String request = user_input.nextLine();
int myArr[]; //not initialized
String lettArr[]; //should be a character type & not initialized
for (int i = 0; i <= request.length(); i++)
{
String c = request.charAt(i); // returns a char
if (request.isDigit(c))
{
myArr[1] += c; // not right, myArr is ints and c is a char
}
if(request.isLowerCase(c))
{
lettArr[1] += c; // not right
}
}
System.out.println(myArr[0]); //only prints one char (you might want this
}
}
1.
You are extracting a character from the input string and trying to add it to the second entry in an uninitialized array. You're line in code is:
myArr[1] += c;
myArr is an integer array and c is a character. You can't do that in java. What's more, you are trying to add a char to an int, which was not initialized in the first place!! The type of everything in an array must be the same. This gets more complicated when it comes to inheritance and such, but for now just know that you can't do that. If you wanted the Integer value of a character you can use:
Integer.parseInt(c)
I'm not sure what you are trying to do with your statement, but I'm 90% sure that it's not trying to do what you want it to. For reference:
myCharArr[i] = c;
assigns the i-th element (starting from 0) to the value of c. So if i=1 and myCharArr was initialized to 3 elements long, it would look like this:
[ ? | c | ?]
where ? is just a garbage value.
2.
In java you need to initialize your arrays, or use a more dynamic List object. The thing with primitive arrays is that their size cannot change, i.e. when an primitive array is initialized:
int arr[] = new int[5];
it stays the same size (in this case 5). If you use something like an ArrayList, you can add as many things as you want. The way you would initialize ArrayLists would be like:
ArrayList<Integer> intArr = new ArrayList<Integer>();
ArrayList<Character> charArr = new ArrayList<Character();
and with those initialized you can do:
intArr.add(someInt);
charArr.add(someChar);
You can use primitive arrays for this problem but it will save you a bit of trouble if you use Lists.
Read up on arrays.
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().