In my code:
public static String input() {
Scanner input = new Scanner(System.in);
while(true) {
int qcount = 0;
String key = input.nextLine();
char[] keyCharArray = key.toCharArray();
for (int i = 0; i<keyCharArray.length;i ) {
//Here the while loop is supposed to break
if(keyCharArray[i]=='q') {
qcount ;
break;
}
}
int[] radie = new int[(keyCharArray.length)/2];
int[] höjd = new int[(keyCharArray.length)/2];
int counter = 0;
for(int i = 0; i < keyCharArray.length; i ){
if(i % 2 == 0){
radie[i/2] = keyCharArray[i] - '0';
}
else if(i % 2 != 0){
höjd[i/2] = keyCharArray[i] - '0';
}
}
for(int i = 0; i < (keyCharArray.length)/2; i ) {
System.out.print("r = " radie[i] " " "h = " höjd[i] "\n\r" "Basytans area: " area(radie[i], höjd[i]) "\n\r" "Mantelytans area:" area(radie[i]) "\n\r" "Volym: " volume(radie[i], höjd[i]) "\n\r");
}
return key;
}
}
The While loop is supposed to repeat the content until keyCharArray[i] =='q' -> There after the while loop is supposed to break
How can I make this work? Thanks
I have tried everything, yet I can't seem to solve it.
Appreciate any efforts, Thanks alot
Tried everything, doesn't work
sadasd
dsadsa
sdadsa
asdsda
CodePudding user response:
You current code is (partially) like this:
public static String input(){
Scanner input = new Scanner(System.in);
while(true){
int qcount = 0;
String key = input.nextLine();
char[] keyCharArray = key.toCharArray();
for (int i = 0; i<keyCharArray.length;i ) {
if(keyCharArray[i]=='q') {
qcount ;
break;
}
}
// The rest...
}
}
The problem with this is that the break
only breaks the inner for
loop.
The simplest solution is to use the qcount
variable you already have, and after the for
loop check if it's non-zero to break
out of the while
loop:
for (int i = 0; i<keyCharArray.length;i ) {
if(keyCharArray[i]=='q') {
qcount ;
break;
}
}
if (qcount > 0) {
break; // Breaks out of the while loop
}
As for my suggestion in the comment it would be something like this instead:
private boolean shouldBreak(String key) {
char[] keyCharArray = key.toCharArray();
for (int i = 0; i<keyCharArray.length;i ) {
if(keyCharArray[i]=='q') {
return true; // Return that we should break the while loop
}
}
return false; // Do not break the while loop
}
public static String input(){
Scanner input = new Scanner(System.in);
while(true){
String key = input.nextLine();
if (shouldBreak(key)) {
break; // Breaks out of the while loop
}
// The rest...
}
}
I personally recommend something like this, as it makes the code cleaner and easier to read and understand and maintain.
CodePudding user response:
Solution worked, thanks a lot.