I know that the variable maxreps isn't in the scope of my main method so I wanted it call it by creating an object, but it still isn't able to get maxreps.
How could I fix this?
public class LUIS{
public void james(){
int current=1;
int maxreps=1;
String adriana = "aabbddddnsspkrrgg";
for(int a=0; a<adriana.length(); a++){
if(adriana.charAt(a) == adriana.charAt(a+1)){
current++;
if(maxreps>=current){
maxreps=current;
}
}
}
}
public static void main(String[] args){
LUIS fritz = new LUIS();
final int drei = fritz.james;
System.out.println(maxreps);
}
}
As you noted, scoping prevents seeing a variable defined in a different scope. You can resolve your particular issue by returning the value
public int james(){ // <-- change from void to an int return
int current=1;
int maxreps=1;
String adriana = "aabbddddnsspkrrgg";
for(int a=0; a<adriana.length(); a++){
if(adriana.charAt(a) == adriana.charAt(a+1)){
current++;
if(maxreps>=current){
maxreps=current;
}
}
}
return maxreps; // <-- return the value
}
And then in the main method set a variable to the returned value.
Alternatively, you can define it as a class variable, but there are reasons to avoid doing so -- globals are generally bad.
1) final int drei = fritz.james; cannot compile. You cannot invoke a method in this way (that is without ()).
2) Besides, the james() method should have a more meaningful name.
This method computes the max series of a same character. So, you could call it computeMaxSeries()
3) And instead being a void method, you could return the max series number.
4) Besides this :
for (int a = 0; a < adriana.length(); a++) {
if (adriana.charAt(a) == adriana.charAt(a + 1)) {
will throw a StringIndexOutOfBoundsException as adriana.charAt(a + 1) refers to an index beyond the valid limit of the String length.
You should rather iterate until the last index -1 :
for (int a = 0; a < adriana.length()-1; a++) {
5) At last this is not consistent since you update maxreps by relying on maxreps instead of current :
if(maxreps>=current){
maxreps=current;
}
You should rather write :
if (current >= maxreps) {
maxreps = current;
}
So, finally the method would be :
public int computeMaxSeries(){
int current=1;
int maxreps=1;
String adriana = "aabbddddnsspkrrgg";
for(int a=0; a<adriana.length()-1; a++){
if(adriana.charAt(a) == adriana.charAt(a+1)){
current++;
if (current >= maxreps) {
maxreps = current;
}
}
}
return maxreps;
}
Now you can do :
final int maxreps = fritz.computeMaxSeries();
System.out.println(maxreps);
Related
I am still pretty new to programming and I am trying to do this small program where I write a static method that takes an array of strings and returns an integer. From there I have to find the index position of the smallest/shortest string and return that index value. I am completely lost and struggling with this. Can I get some help?
My code so far...
public class test
{
public static void main(String [] args)
{
String [] Month = {"July", "August", "September", "October"};
smallest(Month);
System.out.println("The shortest word is " + smallest(Month));
}
public static String smallest(String Month[])
{
String first = Month[0];
for (int i = 1 ; i < Month.length ; i++)
{
if (Month[i].length()<first.length())
{
first = Month[i];
}
}
return first;
}
}
Check the code below,
public class Test {
public static void main(String [] args)
{
String [] month = {"July", "August", "September", "October"};
// smallest(Month);
System.out.println("The shortest word index position is " + smallest(month));
}
public static int smallest(String Month[])
{
String first = Month[0];
int position=0;
for (int i = 1 ; i < Month.length ; i++)
{
if (Month[i].length()<first.length())
{
first = Month[i];
position=i;
}
}
return position;
}
}
Your code is actually pretty close, but --if I understand your task correctly-- instead of the actual smallest element, you should keep track of the index only, since that is what you want to return in the end.
public static int smallest(String[] months) {
int first = 0;
for (int i = 1; i < months.length; i++) {
if (months[i].length() < months[first].length()) {
first = i;
}
}
return first;
}
Focusing on the smallest method.
public static void smallest(String[] month) {
// since we have no knowledge about the array yet, lets
// say that the currently known shortest string has
// size = largest possible int value java can store
int min_length = Integer.MAX_INT, min_length_idx = -1;
for (int i = 0; i < month.length; i++) {
// is this current string a candidate for a new minimum?
if (month[i].length() < min_length) {
// if so, lets keep track of the length so that future
// indices can be compared against it
min_length = month[i].length();
min_length_idx = i;
}
}
return min_length_idx;
}
This method will then also cover the case where the array does not have any strings in it, i.e., empty array.
public static int smallest(String month[]) {
int smallest = 0;
for ( int i=0; i<month.length; i++ {
if (...) {
smallest = i;
}
}
return smallest;
}
Note: use standard conventions where variable names begin with a lower-case letter.
As an example we're combing through the permutations of the integer 123456789. Inspired by Heap's algorithm, we have the following
public static ArrayList<String> comb(char[] seq, int n, ArrayList<String> box){
if(n == 1){
if (isSquare(Integer.valueOf(String.valueOf(seq)))) {
box.add(String.valueOf(seq));
}
} else {
for(int i=0; i<n; i++){
comb(seq,n-1, box);
int j;
if ((n%2)==0) {
j = i;
} else {
j = 0;
}
char temp = seq[n-1];
seq[n-1] = seq[j];
seq[j] = temp;
}
}
return box;
}
In the present case we're interested whether a particular permutation is a square of an integer. Realised by
public static boolean isSquare(int n) {
if ((n%10)==2 || (n%10) ==3 || (n%10)==7 || (n%10) == 8) {
return false;
} else if ( (Math.sqrt(n)) % 1 ==0) {
return true;
} else {
return false;
}
}
However, to be able to use comb I must initialise an empty array outside of the method. What should I do to avoid inducing the need for global variable? I would still like to obtain a box with all solutions. I realise my error is in the parametrisation of comb .
Create a function that "wraps" the original recursive function, provides it with every parameter it needs and creates copies of objects if necessary:
Let's say you renamed your comb(...) function to combRecursive(...) for the sake of convenient naming.
public static ArrayList<String> comb(char[] seq, int n){
char[] seqCopy = Arrays.copyOf(seq, seq.length);
return combRecursive(seqCopy, n, new ArrayList());
}
Can I pass the return value from a method into the main method then utilize that value in another method? That sounds confusing but let me try to explain it better with some code...
public static void main(String[] args){
ArrayList<GeometricObject> geoList = new ArrayList<GeometricObject>();
findPositionLargestObject(geoList);
System.out.println("BIGGEST OBJECT AT "+ maxIndex +" AREA =
"+geoList.get(maxIndex).getArea());
showObjects(geoList.get(maxIndex));
}
//METHOD RETRIEVING INT OF ARRAYLIST
private static int findPositionLargestObject(
ArrayList<GeometricObject> geoList) {
int maxIndex = 0;
for (int i = 1; i < geoList.size(); i++) {
// AREA OF I COMPARES MAX INDEX
if (geoList.get(i).getArea() > geoList.get(maxIndex).getArea()) {
maxIndex = i;
}
}
return maxIndex;
}
// METHOD FOR PRINTING SINGLE OBJECT OF ARRAYLIST
private static void showObjects(GeometricObject geometricObject) {
System.out.println(geometricObject.toString());
}
Lets say I even instantiate the index in the main method such as
int maxIndex = 0;
I want the first method called to return the value, assign that value to the variable maxIndex then utilize that value for the showObjects method. Thanks for any insight that can be given to a coding novice like myself. Is instantiating the variable in the main method no good? What is the logic behind the JAVAC execution here?? The curriculum covered in my course feels like this is an enormous hole that needs to be filled. Basically, How do I utilize a value returned from a method then implement into another method?
Variables are only containers for a value bound to its type. If a method is returning a type, you can place it's return value in a variable located in another block of code. To provide a very basic example for an easier understanding of how this can work:
private String getString(int number) {
if (number == 2) {
return "Not One";
}
return "One";
}
private void printValue(String number) {
if (number.equals("One")) {
System.out.println("i is 1");
} else {
System.out.println("i is not one");
}
}
public static void main(String[] args) {
int i = 1;
String testNum = getString(i);//returns "One"
printValue(testNum);//output: i is 1
}
With this example in mind,
int maxIndex = findPositionLargestObject(geoList);
showObjects(geoList.get(maxIndex));
is valid.
Unless I'm missing something, assign the result of your function call. I suggest you program to the List interface. Also, if using Java 7+ you could use the diamond operator <> like
List<GeometricObject> geoList = new ArrayList<>(); // <-- diamond operator
// ... populate your List.
int maxIndex = findPositionLargestObject(geoList);
and then yes you can use the variable maxIndex
you can obtain the return value in main method like this,
int maxIndex=findPositionLargestObject(geoList);
Code:
public static void main(String[] args){
ArrayList<GeometricObject> geoList = new ArrayList<GeometricObject>();
int maxIndex=findPositionLargestObject(geoList);
System.out.println("BIGGEST OBJECT AT "+ maxIndex +" AREA =
"+geoList.get(maxIndex).getArea());
showObjects(geoList.get(maxIndex));
}
//METHOD RETRIEVING INT OF ARRAYLIST
private static int findPositionLargestObject(
ArrayList<GeometricObject> geoList) {
int maxIndex = 0;
for (int i = 1; i < geoList.size(); i++) {
// AREA OF I COMPARES MAX INDEX
if (geoList.get(i).getArea() > geoList.get(maxIndex).getArea()) {
maxIndex = i;
}
}
return maxIndex;
}
// METHOD FOR PRINTING SINGLE OBJECT OF ARRAYLIST
private static void showObjects(GeometricObject geometricObject) {
System.out.println(geometricObject.toString());
}
I want to know how to tell if an int has been changed (during the program).
Like with an if statement.
int i = 2;
int a = 1;
while(1 < 2) {
if(i % 100 == 0) i++;
}
if(i //Then checks if it changed) {
System.out.println("Changed :D");
}
Is there a way to tell if the variable i is changed DURING the program?
Since this is Java, are these variables data members of a class? In that case give them private access and provide getters and setters. Your setter can notify you if you so desire.
int i = 0;
boolean valueChanged = false;
while(some good condition) {
if (i % 100 == 0) {
i++;
valueChanged = true;
}
}
if(valueChanged) {
System.out.println("Changed :D");
}
// Your int variable
int i = 0;
// A scratch variable
int prev_value_of_i = i;
// Call this code to check whether i has changed since last call
if(i != prev_value_of_i) {
System.out.println("Changed :D");
prev_value_of_i = i;
}
Keep track of the original value of i in a separate variable and compare i to that?
This seems redundant, since the programmer should know when and where values are stored. If you don't, maybe step through with a debugger? #shoover's answer is the most flexible, handling however many unexpected times you might change the value without requiring adding lines of code inside your infinite loop.
class TalkativeInt{
private int x;
TalkativeInteger(int x){
this.x = x;
}
public void set(int a){
System.out.println("Changed!! "+x+" to "+a);
x = a;
}
public int get(){
//System.out.println("Accessed - that tickles");
return x;
}
}
I am trying to write a class that will remove a column from a 2d array, but I keep running into errors that I don't understand. I think I am misunderstanding something very basic here, any help would be appreciated
public class CollumnSwitch
{
int[][] matrix;
int temp;
public static void coldel(int[][] args,int col)
{
for(int i =0;i<args.length;i++)
{
int[][] nargs = new int[args.length][args[i].length-1];
for(int j =0;j<args[i].length;j++)
{
if(j!=col)
{
int temp = args[i][j];
}
nargs[i][j]= temp;
}
}
}
public void printArgs()
{
for(int i =0;i<nargs.length;i++)
{
for(int j =0;j<nargs[i].length;j++)
{
System.out.print(nargs[i][j]);
}
System.out.println();
}
}
}
You cannot access a non-static variable from a static context, you need to change int temp; to static int temp; or you can remove static from your method declaration.
You declare your nargs array in the coldel method, so it is not accessible from other methods. Meaning this doesn't work:
for(int i =0;i<nargs.length;i++) //You try to access nargs which is not possible.
{
for(int j =0;j<nargs[i].length;j++)
...
Maybe you want it to be the matrix array you have in your class? Like this:
in coldel:
matrix= new int[args.length][args[i].length-1];
and in printArgs
for(int i =0;i<matrix.length;i++)
{
for(int j =0;j<matrix[i].length;j++)
...
This require matrix to be static also (again, you can also remove static from coldel)
you can try like this:
static int[][] nargs;
public static void deleteColumn(int[][] args,int col)
{
if(args != null && args.length > 0 && args[0].length > col)
{
nargs = new int[args.length][args[0].length-1];
for(int i =0;i<args.length;i++)
{
int newColIdx = 0;
for(int j =0;j<args[i].length;j++)
{
if(j!=col)
{
nargs[i][newColIdx] = args[i][j];
newColIdx++;
}
}
}
}
}
public static void printArgs()
{
if(nargs != null)
{
for(int i =0;i<nargs.length;i++)
{
for(int j =0;j<nargs[i].length;j++)
{
System.out.print(nargs[i][j] + " ");
}
System.out.println();
}
}
}
Your difficulties are arising due to using variables outside of their scope. In java, variables basically only exist within the most immediate pair of braces from which they were declared. So, for example:
public class Foo {
int classVar; // classVar is visible by all code within this class
public void bar() {
classVar = classVar + 1; // you can read and modify (almost) all variables within your scope
int methodVar = 0; // methodVar is visible to all code within this method
if(methodVar == classVar) {
int ifVar = methodVar * classVar; // ifVar is visible to code within this if statement - but not inside any else or else if blocks
for(int i = 0; i < 100; i++) {
int iterationVar = 0; // iterationVar is created and set to 0 100 times during this loop.
// i is only initialized once, but is not visible outside the for loop
}
// at this point, methodVar and classVar are within scope,
// but ifVar, i, and iterationVar are not
}
public void shoo() {
classVar++; // shoo can see classVar, but no variables that were declared in foo - methodVar, ifVar, iterationVar
}
}
The problem you are having is because you are declaring a new 2-d array for each iteration of the for loop and writing one column to it, before throwing that away, creating a new array, and repeating the process.