Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am writing a program involving ArrayList.
The program is about editing the ArrayList through user input:
ArrayList<Type> array = new ArrayList<Type>();
switch (verify)
{
case 1:
//A list of statement including variables, conditionals and loops
break;
case 2:
//Another list of statement here includes variables, loops etc
break;
default:
do something else;
}
My question is that I don't want to put a lot of statement in a single case, is it possible for me to separate them and redirect the Java to read blocks of statement from somewhere else?
Use methods and pass the ArrayList to them:
public static void main(String args) {
ArrayList<Type> array = new ArrayList<Type>();
switch (verify) {
case 1:
case1(array);
break;
case 2:
case2(array);
break;
default:
do something else;
}
}
private static void case1(ArrayList<Type> array) {
//A list of statement including variables, conditionals and loops
}
private static void case2(ArrayList<Type> array) {
//Another list of statement here includes variables, loops etc
}
The ArrayList is a mutable type, so any changes you make to the list within the case1() and case2() methods affect the ArrayList in your main method.
Use functions!
public class Main {
public static void main(String[] args) {
//snip
ArrayList<Integer> array = new ArrayList<Integer>();
switch(verify) {
case 1: doAThing(array);
break;
case 2: doSomethingElse(array);
break;
default: doAThirdThing(array);
}
}
private static void doAThing(ArrayList<Integer> array) {
//do logic here
}
private static void doSomethingElse(ArrayList<Integer> array) {
//do logic here
}
private static void doAThirdThing(ArrayList<Integer> array) {
//do logic here
}
By the way, I'm impressed you're already looking for ways to keep your code clean and easy to write. Mature programmers usually break out complicated code into smaller functions, exactly like you're thinking about doing. I'm excited for you to continue studying Java!
Related
This question already has answers here:
Switch statement just returning the last case
(4 answers)
Closed 3 years ago.
I'm debugging my application in IntelliJ and it seems like my code is going into 2 switch statements instead of 1.
My code looks like this:
final String CASE_1 = "case_1";
final String CASE_2 = "case_2";
switch(CASE): {
CASE_1: {
// do something
}
CASE 2: {
// do something
}
}
My application executes the code that's in both cases.
Is there any reason why the code would go into both cases?
(I'm intentionally not pasting my actual code since it's impossible to reproduce locally without creating the whole structure of the project)
Put a break after each case, otherwise it forwards to the next case.
public class Main {
public static void main(String args[]) {
final String CASE_1 = "case_1";
final String CASE_2 = "case_2";
String CASE = "case_1";
switch(CASE){
case CASE_1:{
System.out.println("Case 1 Found");
break; //Put a break here if you don't want the code to execute for the next case as well.
}
case CASE_2:{
System.out.println("Case 2 Found");
}
}
}
}
Because you dont end the case
public void runTest(String CASE) {
switch (CASE) {
case CASE_1:
// code block
break;
case CASE_2:
// code block
break;
default:
break;
}
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
In this code the method setEid isn't working dont know what's the problem with while loop
this code of mine has no error but it isnt showing any output
public class Emp {
private String eid;
public String getEid() {
return eid;
}
public void setEid(String e) {
while (e.length() < 12) {
eid = e;
}
}
}
public class Test {
public static void main(String[] args) {
Emp z = new Emp();
z.setEid("rgrge");
System.out.println("\n" + z.getEid());
}
}
enter code here i expect the static initialization of setEid argument should not take more than 12 characters
Your setter method have a while loop if eid length is less than 12 then it always stuck in this method.
public void setEid(String e){
while(e.length()<12)
eid=e;
}
and In your main method
public static void main(String[] args) {
Emp z=new Emp();
z.setEid("rgrge"); // you call setter
System.out.println("\n"+z.getEid());
}
you pass "rgrge" in setter and its length is less than 12. Tht's why your program is stuck in loop and not showing any thing.
Change setter implementation to this.
public void setEid(String e){
if(e.length()<12) // change while to if
eid=e;
}
so first there should have had if instead of while.
Change:
while(e.length()<12) change this as if(e.length()<12)
Explanation:
your setEid method never going to run because there is no break condition there. your while loop condition tends to the infinite. your code gets stuck in that while loop.
here you passed z.setEid("rgrge");. in your example, Length of string e is 5 which is obviously less than 12, so the condition will always be satisfied and your program will be stuck in infinite loop.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 4 years ago.
This is just something im trying out, i just recently started coding in java would like some help. Would like to ask user to pick their favorite movie, then take their input and use if statements to give different responses to each response.
import java.util.Scanner;
public class miniFFF {
public static void main (String[]p) {
System.out.println("What is your favourite movie? pick from the answers below:");
System.out.println("a");
System.out.println("b");
System.out.println("c");
System.out.println("d");
System.out.println("e");
answer();
//ifStatements();
System.exit(0);
}
public static String answer() {
String favMovie;
Scanner test = new Scanner(System.in);
favMovie = test.next();
if(favMovie == "a") {
System.out.println("1234");
}
else if (favMovie == "b") {
System.out.println("123");
}
return favMovie;
}
}
Using switch will make your code much readable.
switch (favMovie){
case "a": //do for a
break;
case "b" //do for b
break;
default: //no match
}
Java enum was designed for when you have a finite set of options. As good practice it will be a better option over string literal
I don't really see a question there and your code seems, I could point two thing I might do differently tho.
One I would use equalIgnoreCase instead of == in case someone doesn't put the correct capitalization (Also add a general case)
Also putting the method outside main seems to be better practice.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
This is a specific question, don't downvote it just because it doesn't help you.
public class Answer {
public static String answer(int n) {
String nums="";
int limit = 10005;
int x=2;
while(limit>0){
if(isPrime(x)){
limit-=String.valueOf(x).length();
nums = nums + String.valueOf(x);
}
x+=1;
}
String out="";
if(n==0){
out="23571";
}else{
for(int i=1;i<6;i++){
out += String.valueOf(nums.charAt(n+i));
}
//Problem Solved: instead of this loop, it should be out = nums.substring(n,n+5)
}
return out;
}
public static boolean isPrime(int number) {
for(int check = 2; check < number; ++check) {
if(number % check == 0) {
return false;
}
}
return true;
}
}
Nothing is wrong with this code as far as I know, I'm just using it as an example for you to use.
"It must implement the answer() method in the solution stub." was in the directions for me, but I don't know much about the vocabulary of programming, I only understand logic behind programming, so this is the only thing I don't know how to solve. So what I am asking is where do I put the "answer()" at in this program?
It was looking for substring, which I didn't include because I haven't used java in about a year and simply forgot about it.
Here as I can figure out you have problems in understanding the meaning of "stub". It is simply the test method as provided by the answer here. And if you want to test the above code you have to implement the main method in your code to do the same. Something like this
public static void main(String [] args){
//Either use Scanner object or provide the hard coded input as per your requirements
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
System.out.println(answer(n));
}
EDIT AS PER OP REQUIREMENT
Okay so as per your requirement it is asking you for the unit test. There are many ways to do it but my preferred is to make stub concrete class
Implementation an stub concrete class in JUNIT
class Answer {
public String answer(int n){
// Code body
return "result"// in your case out variable
}
}
class solution extends Answer {
#Override
public String answer(int n){
//return "your stubbed result";
}
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
Is there a way in Java 8 to simultaneously declare and initialize a final variable with the result of a complex expression?
In other words, is something like the following possible?
final int x = [capturedVariable] {
switch (capturedVariable) {
case 1: return 42;
case 2: return 84;
default: return 66;
}
};
While the syntax is obviously "creative", I hope the intent is clear.
Edit 1: While this particular example can be written using ternary operators, it's merely an example of a complex expression and I'm looking for a general solution.
Edit 2: Maybe a less controversial way to look at this question is the following: What is the syntax to simultaneously declare and invoke a lambda/closure in Java 8?
I don't see how Java 8 is relevant here, you can assign a final variable in multiple places so long as you always assign it and only ever assign it once, for example this is legal Java code (assuming blah is a valid boolean):
final int test;
if (blah) {
test = 1;
} else {
test = 2;
}
The expressions can be as complicated as you like so long as the compiler is able to deterministically prove that you always initialize the variable once and only once. (For example loops would make it fail).
Seems overkill, but you could use a Supplier:
final int x = new Supplier<Integer>() {
public Integer get() {
// Complexity here
return result;
}
}.get();
I'm sure it's my Java-fu being weak (I guess not), but the only way I could get the lambda version working is to have a reusable call utility function somewhere:
class Utils {
public static <T> T call(Supplier<T> x) {
return x.get();
}
}
...and then:
final int x = Utils.call(() -> {
// Complexity here
return result;
});
Matthias points out in a comment (refined by Aominè) that you can avoid that intermediary function, but it isn't much prettier than the first solution above:
final int x = ((Supplier<Integer>) () -> {
// Complexity here
return result;
}).get();
...but at least it doesn't require generating a class.
You ca create your own Interface an create init method which take an init and return another int for example :
Init i = (x) -> {
switch (x) {
case 1:
return 42;
case 2:
return 84;
default:
return 66;
}
};
final int x = i.init(1);
...
interface Init {
int init(int x);
}