Cannot find symbol while loop - java

Hello I am creating an algorithm to take int x and convert it to the desired base being int y.
example 7 base 3 = 21.
void printXBaseY(int x, int y) {
boolean active = true;
while(x >= y) {
int a = x % y;
int b = x / y;
String first = "" + a;
String second = "" + b;
String answer = "" + first + second;
}
String answer = "" + first + second;
println(x + " base " + y + " is " + answer);
}
}
at String answer it has error cannot find symbol - variable first, can anyone explain why it cannot find it? and provide a solution.
thank you in advance

Those variable's are out of scope.
In java the scope is restricted to {}.
Just move them to top, so that they're available further.
void printXBaseY(int x, int y) {
boolean active = true;
String first=""; // or null
String second=""; // or null
while(x >= y) {
int a = x % y;
int b = x / y;
first = "" + a;
second = "" + b;
String answer = "" + first + second;
}
String answer = "" + first + second;
System.out.println(x + " base " + y + " is " + answer);
}
You might be a beginner :Read more about block and statements

It is out of scope. You declared it within the while loop. it is gone afterwards.
To solve this, declare first and second before the while loop starts.

The scope of variable "first" is bounded by while block. So it cannot be accessed outside it.

Your first and second variables are declared inside while loop. So the scope of them are inside while loop only you can not use them outside while loop.
void printXBaseY(int x, int y) {
boolean active = true;
String first = null;
String second = null
while(x >= y) {
int a = x % y;
int b = x / y;
first = "" + a;
second = "" + b;
String answer = "" + first + second;
}
String answer = "" + first + second;
println(x + " base " + y + " is " + answer);
}

while(x >= y) {
int a = x % y;
int b = x / y;
String first = "" + a; // here is the problem. You declared first and second within the while loop.
String second = "" + b;
String answer = "" + first + second;
}
Corrected code below
while(x >= y) {
int a = x % y;
int b = x / y;
String first = "" + a;
String second = "" + b;
String answer = "" + first + second;
String answer = "" + first + second;
println(x + " base " + y + " is " + answer);
}

Your variables first and second as well are declared inside your while loop, therefore its lifetime is bound within that loop.
If it is not clear for you what a scope is, you should read this interesting slide
http://classes.soe.ucsc.edu/cmps012a/Winter03-01/notes/Lecture27-4perpage.pdf

void printXBaseY(int x, int y) {
boolean active = true;
String first="";
String second="";
String answer="";
while(x >= y) {
int a = x % y;
int b = x / y;
first = "" + a;
second = "" + b;
// answer = "" + first + second;
}
answer = "" + first + second;
println(x + " base " + y + " is " + answer);
}

Related

Trying to replace something inside a string that has parentheses, java

Hi I'm petty new to java and I have a question,
I'm trying to replace the String " 22(S)" with " 22(I)" but for some reason the replace first doesn't replace the String.
Here is my code:
public class tes {
public static void main(String[] args) {
int y = 22;
String x = " 22(S)";
x = x.replaceFirst(" " + y + "(S)", " " + y + "(I)");
System.out.println(x);
}
}
While I know that I can do x.replaceFirst("S","I") , I want to understand why this is still producing 22(S) with my current code. Thanks.
Because ( and ) are grouping operators in regular expression. You need to escape them in the match term. Like,
x = x.replaceFirst(" " + y + "\\(S\\)", " " + y + "(I)");
And I get
22(I)
with no other changes.
public class Replace {
public static void main(String[] args) {
int y = 22;
String x = " 22(S)";
x = x.replaceAll(" " + y + "\\(S\\)", " " + y + "(I)");
System.out.println(x);
}
}
By using replaceAll also we can replace all the S letters to I

Deleting last new line string

So I've tried pretty much everything to get rid of the last newline character in my code. Its supposed to print a new line after every recursive call except for the last one. Any ideas?
public static boolean solve(double target, ArrayList<Double> numbers)
{
String print = "";
String newPrint = "";
double compare = 0;
boolean done = false;
for (double num : numbers)
{
if (!done)
{
ArrayList<Double> remaining = new ArrayList<Double>(numbers);
remaining.remove(num);
if (target == num)
{
done = true;
}
else
{
done = solve(target + num, remaining);
if (done)
{
print += ((int) target + (int) num) + " " + "-" + " " + (int) num + " "
+ "="
+ " "
+ ((int) target + "\n");
}
else
{
done = solve(target - num, remaining);
if (done)
{
print += ((int) target - (int) num) + " " + "+" + " " + (int) num + " "
+ "=" + " "
+ ((int) target + "\n");
}
else
{
done = solve(target * num, remaining);
if (done)
{
print += ((int) target * (int) num) + " " + "/" + " " + (int) num
+ " " + "=" + " "
+ ((int) target + "\n");
}
else
{
done = solve(target / num, remaining);
if (done)
{
print += ((int) target / (int) num) + " " + "*" + " "
+ (int) num
+ " " + "="
+ " " + ((int) target + "\n");
}
}
}
}
}
}
}
System.out.print(print);
return done;
}
}
For instance:
void recursiveF(...) {
if ... {
recursiveF(...);
println();
}
...
}
The result is a string but you don't want the last character, so remove it:
print = print.substring(0, print.length()-1);
Use trim() method. It will remove white spaces, newline etc from beginning and end of string.
System.out.print(print.trim());
Short Print the new line character before.
The first thing the recursive function should do is print the new line character.
This way you shift the odd case from the last function call, to the first call, which should not prepend a new line character.
You could add a parameter String prepend = "" to the signature of the recursive method, it's empty on the first call, all further calls have it set to String prepend = "\n".
Then you can just print prepend without bothering with its content.

Finding GCD java

Good Day! I have a problem on my code. It has an error and here's is the picture:
Here is my code:
private static int gcd(int a, int b, int c) {
return gcd(gcd(a,b),c);
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
//DecimalFormat fmt = new DecimalFormat("+##");
int x1 , y1, x2, y2, gcd,
inverted_x1, inverted_y1, inverted_x2, inverted_y2,
x1Times2, x2Times2, y1Times2, y2Times2,
x1raised, y1raised, x2raised, y2raised,
computeX, computeY, computeS,
x2inverted, y2inverted, invertedx2times2, invertedy2times2;
try{
x1 = Integer.parseInt(jTextField1.getText());
y1 = Integer.parseInt(jTextField2.getText());
x2 = Integer.parseInt(jTextField3.getText());
y2 = Integer.parseInt(jTextField4.getText());
int[] array = new int[4];
array[0] = x1;
array[1] = x2;
array[2] = y1;
array[3] = y2;
inverted_x1 = x1 *= -1;
inverted_y1 = y1 *= -1;
inverted_x2 = x2 *= -1;
inverted_y2 = y2 *= -1;
jTextField5.setText("= (x" + formatSign(inverted_x1) + ")² + (y" + formatSign(inverted_y1) + ")²"
+ " = (x" + formatSign(inverted_x2) + ")² + (y" + formatSign(inverted_y2) + ")²" );
x1Times2 = inverted_x1*2;
y1Times2 = inverted_y1*2;
x2Times2 = inverted_x2*2;
y2Times2 = inverted_y2*2;
x1raised = inverted_x1*inverted_x1;
y1raised = inverted_y1*inverted_y1;
x2raised = inverted_x2*inverted_x2;
y2raised = inverted_y2*inverted_y2;
jTextField9.setText("= x²" + formatSign(x1Times2) + "x" + formatSign(x1raised) + "+y²" + formatSign(y1Times2)
+ "y" + formatSign(y1raised) + "= x²" + formatSign(x2Times2) + "x" + formatSign(x2raised) + "+y²"
+ formatSign(y2Times2) + "y" + formatSign(y2raised));
x2inverted = x2raised *= -1;
y2inverted = y2raised *= -1;
invertedx2times2 = x2Times2 *= -1;
invertedy2times2 = y2Times2 *= -1;
computeX = x1Times2 + invertedx2times2;
computeY = y1Times2 + invertedy2times2;
computeS = x2inverted + y2inverted + x1raised + y1raised;
jTextField17.setText("= " + formatSign(computeX) + "x" + formatSign(computeY) + "y" + formatSign(computeS) + "= 0");
gcd = gcd(computeX, computeY, computeS);
jTextField18.setText("= " + formatSign(computeX/gcd) + "x" + formatSign(computeY/gcd) + "y" + formatSign(computeS/gcd) + "= 0");
jTextField6.setText("= " + formatSign(10/gcd));
XYLineChart_AWT chart = new XYLineChart_AWT("Locus of Point Graph", "", array);
chart.pack();
RefineryUtilities.centerFrameOnScreen( chart );
chart.setVisible( true );
}catch(Exception e){
JOptionPane.showMessageDialog(null, "Please fill necessary inputs");
}
}
the error shows at my return gcd(gcd(a,b),c);
I want to get the GCD of 3 numbers and later on divide it to my variables. Is there any other way? Or is there a way to solve the error?
Thanks in advance!
Because gcd(...) takes 3 arguments
private static int gcd(int a, int b, int c) {
return gcd(gcd(a,b),c);
}
In return, you are passing only 2. Also, with the code you have shown, if you pass 3 params, it will be infinite recursion. Thanks to #eis for pointing that out. I forgot to mention it :)

very new to the programming and at the little exercise I cannot see where I am wrong

So maybe many of you knows the exercise we need to do about learning primitives, where we need to print h3110 w0r1d 2.0 true
so mine is this;
public class main {
public static void main(String[] args) {
// H3110 w0r1d 2.0 true
byte bir = 0;
short iki = 31;
int uc = 10;
long dort = 1;
float bes = 2.0f;
char yedi = 'H';
char sekiz = 'w';
char dokuz = 'd';
char ekstra = ' ';
char ramk = 'r';
boolean on = true;
String son = (yedi + iki + uc + ekstra + sekiz + bir + ramk + dort + dokuz + ekstra + bes + ekstra + on );
System.out.println(son);
}
}
and their solution is this;
public class Main {
public static void main(String[] args) {
byte zero = 0;
short a = 3;
int b = 1;
char d = ' ';
float e = 2.0f;
boolean f = true;
String output = "H" + a + b + b + zero + d + "w" + zero + "r" + b + "d" + d + e + d + f;
System.out.println(output);
}
}
So mine is giving me boolean and float errors, but I cant see what is wrong with that primitives.
the error Im getting is this
Main.java:16: error: bad operand types for binary operator '+'
String son = (yedi + iki + uc + ekstra + sekiz + bir + ramk + dort + dokuz + ekstra + bes + ekstra + on );
^
first type: float
second type: boolean
1 error
The line:
String son = (yedi + iki + uc ...
assigns a concatenation of multiple parameters of different types, none of which is a string, into a string.
The "solution" is to start the assignment by concatenating a string to the other parameters:
String output = "H" + a + b + ...
^
which will cast the rest of them - to strings.
You can do the same with the first example by adding an empty string at the beginning:
String son = ("" + yedi + iki + uc ...
^
Side-Note: I totally agree with T.J. Crowder's comment above...
The example works because everything can be automatically converted to a String, and addition is left-associative.
The difference between a char and a String may not be obvious to you. 'C' is a char literal, while "C" is a String literal (which can contain multiple chars).
Let's go through a few steps of the string concatenation in the example, showing conceptually how the addition is performed:
"H" + a + b + b + zero + d + "w" + zero + "r" + b + "d" + d + e + d + f;
"H3" + b + b + zero + d + "w" + zero + "r" + b + "d" + d + e + d + f;
"H31" + b + zero + d + "w" + zero + "r" + b + "d" + d + e + d + f;
"H311" + zero + d + "w" + zero + "r" + b + "d" + d + e + d + f;
"H3110" + d + "w" + zero + "r" + b + "d" + d + e + d + f;
...and so on. Every addition will always be a String + some other value, which is fine.
The addition in your code, on the other hand, tries to add incompatible types like int and boolean, which doesn't fly. Also, it tries to store the result in a String variable, which is not possible, because the result is not a String.

Is there a way to store all arithmetic operators in just one variable to be used inside an output?

Instead of the variables sum, diff prod inside the
System.out.println(" " + **here)**, is there a way I can store it in just one variable?
So if I call it inside a statement (and if i use a variable "answer")it would look something like this and will still give me the same output:
System.out.println("Sum = " + answer);
System.out.println("Difference = " + answer);
System.out.println("Product = " + answer);
I'm really stuck at this part of the program, any kind of help or tips will do, thanks
You can use an array to store the sum, diff, and prod respectively. Or you can great a new class that has those attributes.
For instance (with an array):
int[] answer = {sum, diff, prod};
System.out.println("Sum = " + answer[0]);
System.out.println("Difference = " + answer[1]);
System.out.println("Product = " + answer[2]);
It can't work the way your example is stated, but you could do something like the following:
public class NumberPair {
private final int x;
private final int y;
public NumberPair(int x, int y) {
this.x = x;
this.y = y;
}
public int sum() {
return x+y;
}
public int difference() {
return x-y;
}
public int product() {
return x * y;
}
}
Then you could do the following:
NumberPair answer = new NumberPair(10, 5);
System.out.println("Sum = " + answer.sum());
System.out.println("Difference = " + answer.difference());
System.out.println("Product = " + answer.product());

Categories

Resources