How do i exit this while loop [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 1 year ago.
Improve this question
I'm trying to get this loop down but I don't know how to break from it.
System.out.printf("Please enter your given name and surname (Enter 0 to return to main menu)%n");
String name = sc.nextLine();
while (name.equals("0")) {
System.out.printf(MENU_TEMPLATE);
name = sc.nextLine();
if the user enters their name then the program will carry on as normal, but I'm having trouble doing this.

you use a conditional, when you want to break the loop. Then you use the break command.
like
while (name != Integer.toString(0)) {
if (name == "Salami") {
break;
}
}
another way to break the loop is to use a counter.
int i = 0;
while (i < 10) {
//do some code here.
i++;
}

Related

Am using while loop, if_else and try_catch with scanner statement in Java and stuck. Am a beginner and hence confused on finding the error [closed]

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 3 years ago.
Improve this question
Trying to accept input from a user within [0,1,2,3,4] until he enters a valid number. using try-catch to fix the exception error
boolean good = true;
int x = reader.nextInt();
while (good != false) {
try {
if (x > launchEventList.size()-1) {
System.out.println("Please provide a valid input");
reader.nextInt();
} else {
System.out.println("\nDetails of event on index "+ x + " are ==>> " + getLe(x));
good = false;
}
}
catch (IndexOutOfBoundsException e) {
System.out.println("Invalid Input");
}
inside if statement store the reader.nextInt() to variable x.
x=reader.nextInt();

valid word counter out of bounds error [closed]

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
{
public static int WordCount (String cString)
{
String currentWord;
int index;
int spacePos;
int validWordCount=0;
boolean validWord;
char upClowC;
cString=cString.trim()+" ";
spacePos=cString.indexOf(" ");
validWord=true;
for(index=0;index<cString.length();index++)
{
currentWord=cString.substring(0,spacePos);
upClowC=Character.toUpperCase(currentWord.charAt(index));
if(upClowC<'A'||upClowC>'Z')
{
validWord=false;
}
}
if(validWord==true)
{
validWordCount++;
}
return validWordCount;
}
public static void main(String[] args)
{
String sentence;
System.out.println("enter a sentence:");
sentence=EasyIn.getString();
WordCount(sentence);
}
}
I'm trying to create a method which takes a sentence and picks out the valid words (i.e. no numbers or symbols), but I keep getting an out of bounds error.
I can't use an array.
Your problem is here:
currentWord = cString.substring(0, spacePos);
upClowC = Character.toUpperCase(currentWord.charAt(index));
currentWord gets shorter, but index is still running from 0 to the length of the string.
General notes:
Follow Java naming conventions and change the name of your method to begin with small letter
if(validWord) is enough when you want to compare something to true, otherwise it's like asking "is it true that the value is true" instead of simply "is the value true"
Next time post your stack trace to get better and sooner help
In your code, you are doing
spacePos = cString.indexOf(" ");
And then inside the loop:
currentWord = cString.substring(0,spacePos);
upClowC = Character.toUpperCase(currentWord.charAt(index));
Now, because of the loop, the index will take values from 0 to your string length minus 1. If your substring (currentWord) is smaller than your string - which probably is -, then currentWord.charAt(index) will try to index out of the bounds of the substring, which is why you get the error.

Is there something like a while switch? [closed]

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 was wondering if there is something that takes in a user input and tests it into preset 'cases' (like a switch) and if there is no 'cases' matching the user input the switch-thing resets (like a while statement). Then it prompts the user for an input and then tests if that matches and if it doesn't it keeps doing this until the input from the user matches one of the cases. I realize that you can do this with a while/if/else combo and am simply wandering if there is a way to do this with a while statement.
Edit:
What I ended up doing is...
String aString = scanner.next();
boolean switchOff = false;
while ( switchOff = false )
{
switch (aString)
{
case "example" : //What I want to happen
switchOff=true;
break;
default: aString = scanner.next();
break;
}
}
Would this work?
You can combine them with
OUTER: while(true) switch(tested) {
case GOOD:
// something
break;
case ALSO_GOOD:
// something
break;
default:
break OUTER;
}
do{ input = askInput(); } while( !match(input) );

Output accumulates each iteration instead of resetting [closed]

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
The code runs properly the first time then run it again using the while loop and lets say the first time I entered AA and it becomes CC then it runs again I enter AA again it will come out with CCCC do it again it comes out with CCCCCC I don't want that I need it to not keep the data from the string each time it loops.
import java.util.*;
public class SecretCypher {
public static void main(String args[]) {
Scanner kb = new Scanner(System.in);
StringBuffer e = new StringBuffer();
System.out.println("Welcome to Secret Cypher!");
char loop = 'Y';
while(loop == 'Y' || loop == 'y') {
System.out.println("");
System.out.println("Enter your cypher in upper case.");
String s = kb.nextLine();
char[] cs = s.toCharArray();
for (int i = 0; i < cs.length; i++) {
e.append((char)('A' + (cs[i] - 'A' + 2) % 26));
}
if(s == s.toLowerCase()) {
System.out.println("Remember to use upper case letters!");
System.exit(0);//Also I was bored of using break and this works any where in the code.
}
System.out.println(e.toString());
System.out.println("Do you want to enter another cypher? > ");
String again = kb.nextLine();
if(again.charAt(0) == 'N') {
System.out.println("Hope you come back again!");
break;
}
}
}
}
You're reusing the same string buffer. If you keep putting things into the same buffer without clearing it, you're obviously going to get extraneous stuff from previous iterations.
Simply declare the StringBuffer inside the while loop so that it is created on each iteration.
Anyway, you should learn to use your debugger, instead of asking here for us to debug. If anything, using the debugger can offer extremely valuable insight into the troubles that you are having here.

I need to figure out the logical bug in my Code [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
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.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Improve this question
when I call the method "getUnknownsAccel" with the problem1 object, for some reason the 'if' statement in the method is not executed to retrieve the value of the variable:
PhysicsProblem problem1 = new PhysicsProblem(accel, vI, vF, t, deltaX);
System.out.println("Which variable are you solving for? ");
String solveFor = scan.next();
// after receiving solveFor input, assesses data accordingly
if (solveFor.equalsIgnoreCase("acceleration"))
{
System.out.println("Solving for Acceleration!");
System.out.println("Are there any other unknowns? (enter 'none' or the name " +
"of the variable)");
missingVar = scan.next();
problem1.setMissingVar(missingVar);
do
{
problem1.getUnknownsAccel();
System.out.println("Are there any other unknowns? (enter 'none' or the name " +
"of the variable)");
missingVar = scan.next(); //// change all these in the program to scan.next, not scan.nextLine
}
while (!missingVar.equalsIgnoreCase("none") || !missingVar.equalsIgnoreCase("acceleration"));
if (missingVar.equals("none"))
{
// Write code for finding solutions
System.out.println("Assuming you have given correct values, the solution is: ");
}
}
After the do/while loop used to retrieve the name of the other variables that are unknown, I call the getUnknownsAccel method from this class file:
public void getUnknownsAccel()
{
//-----------
// checks for another unknown value that is not accel
//-----------
if (missingVar.equalsIgnoreCase("time"))
{
System.out.println("Please enter the value for time: ");
t = scan.nextDouble();
while (t <= 0 || !scan.hasNextDouble())
{
System.out.println("That is not an acceptable value!");
t = scan.nextDouble();
}
}
}
Let's assume for the sake of this problem, that the user WILL enter "time" as the unknown when prompted. Any idea why my code isn't executing the scan function to retrieve the time variable value? Instead, the program just repeats the system.out function "Are there any other unknowns..."
After scanning, you set missingVar to scan.next(), but you do not do anything. The loop continues.
After
missingVar = scan.next();
add the line
getUnknownsAccel();
Note, another issue is that you will need to handle later is that missingVar is local - to access it in getUnknownsAccel(), you should change the declaration to
public void getUnknownsAccel(String missingVar){
}
and instead use
getUnknownsAccel(missingVar);

Categories

Resources