Output accumulates each iteration instead of resetting [closed] - java

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.

Related

Do while loop condition not matching with variables inputted through scanners [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 12 hours ago.
Improve this question
I am a beginner in Java and this issue arose when I was working on a HackerRank problem that I have solved but it still confuses me why it wouldn't work the first iteration of code I made to solve it. This code function is to separate a string and an integer into two columns with the integer being limited to three digits and string having 10 chr limit, covered by "========". Also, I intend the code only ends when the user has inputted "nothing" or white spaces.
However, the do while loop keeps going as its condition does not match the inputted variables created by the scanner, being white spaces. I had a clue that it might be when I used an integer scanner as it interfered with the string scanner, but I tried clearing the scanner by using nextLine(), and it wouldn't work with the loop. I tried using scanner.reset() and also declaring the integer first as a string and then converting it back to an integer but the loop keeps going. I tried simplifying it, and I found out that the loop ends when I use "word = scanner.nextLine();" but it wouldn't work with the loop. Hope you guys can educate me and possible ways to fix this issue.
package hackerRankTestCode;
import java.util.Scanner;
import java.lang.*;
import java.util.concurrent.atomic.DoubleAdder;
public class TestCode {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String word = "";
Integer number = 0;
String baruNumber = "";
System.out.println("================================");
do {
word = scanner.next();
number = scanner.nextInt();
String blank = new String(new char[15 - word.length()]).replace("\0", " ");
if(number<100 && number>=10){
baruNumber = "0"+number;
System.out.println(word+blank+baruNumber);
}
else if(number>=0 && number<10) {
baruNumber = "00"+number;
System.out.println(word+blank+baruNumber);
}
else if(number>=100) {
System.out.println(word+blank+number);
}
}
while(!word.isBlank() && number != 0);
scanner.close();
System.out.println("================================");
}
}

How do i exit this while loop [closed]

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++;
}

Is there a specific way to make this code better for a beginner in java? [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 1 year ago.
Improve this question
import java.util.Scanner;
public class hello {
public static void main(String[] args) {
int k=0;
System.out.println("Enter the number of times for a sentence to loop.\n");
Scanner i = new Scanner( System.in);
int j = i.nextInt();
System.out.println("Enter the sentence to be looped. \n");
Scanner sentence = new Scanner(System.in);
String sent = sentence.nextLine();
while (k < j ) {
System.out.println(sent);
}
}
}
This is just a program to take a sentence from a user and then print it the number of times the user requires it.
Just started learning it. I have a bit of experience in C , but this seems a bit too tedious could i use any other options ?
There's a couple of things that could be improved. Firstly, the code doesn't even work properly since k is never incremented (causes an infinite loop).
while (k < j ) {
System.out.println(sent);
k++;
}
Also, you only need one Scanner object to read user input. Creating a second one is just waste of memory and makes the code more confusing to read.
Scanner scanner = new Scanner(System.in);
int x = scanner.nextInt();
int y = scanner.nextInt(); //we can use the same object for a different variable.
In Java, class names should always start with an uppercase letter. This is to differentiate objects/classes from methods (which should start with a lowercase letter). This makes the code easier to read.
public class Hello {
Another thing, when you know exactly how many times you want to loop, it's better to use a for loop.
for(int k=0; k<j; k++) {
System.out.println(sent);
}

String index out of range even though the string is limited [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I am a student and I am learning Java.I recently got a question which said I had to find the largest word in a given string..I wrote a code but it is giving me an error that string index is out of bounds even though I limited it to the length of the string..Can someone help me with the code..Please use simple language(I am not an expert)
Code
import java.util.*;
class word
{
void def()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the string");
String s1=sc.nextLine();
int length=s1.length();
length++; //My name
int j=0; //0123456
int word=0;
int findex=0;
int lindex=0;
int lword=0;
for(int i=0;i<length;i++)
{
if(s1.charAt(i)==' ' && j==0)
{
lword=i;
findex=0;
lindex=i;
j=i;
}
else if(s1.charAt(i)==' ')
{
if(i-j-1>lword)
{
findex=j;
lindex=i;
lword=i-j-1;
}
j=i;
}
else if(i==length-1)
{
if(i-j-1>lword)
{
findex=j;
lindex=i;
}
}
}
System.out.println("Largest word is:"+s1.substring(findex,lindex+1));
}
}
By doing length++ you make sure that your length variable will be larger then the actual string length. at the last loop step there will be no char at s1.charAt(i)
Just remove the line with length++

Create a program that will input a heart symbol and will stop at the exclamation mark symbol (Call from another class with an argument) [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 7 years ago.
Improve this question
I showed this to my teacher and he said that I was 99% correct. The only problem is that I did not put an argument in the first class. I'm so confused because I don't think I've learned that part yet : (
Class 1:
import java.util.*;
public class hearts {
public static void hearts1(String[] args) {
char heart = '♥';
for (int i = 0; 1 < 254; i++)
{
System.out.print(heart++ + " ");
}
}
}
Class 2:
public class Caller {
public static void main(String[] args){
hearts.hearts1(args);
}
}
Generally I would advise you to not use "magical appeared" numbers in this sort of situation.
Furthermore you have created an endless loop because your loop condition is (1<254) which is alway true because 1 will always be smaller than 254.
Therefore I would write
for (char currentChar = heart; currentChar < '❣'; currentChar++)
{
System.out.print(currentChar + " ");
}
instead of
for (int i = 0; 1 < 254; i++)
{
System.out.print(heart++ + " ");
}
And generally said you are not using any arguments in your code...You are passing some arguments but you're never actually using them.
Maybe you should change your first class like this:
public static void hearts1(char startChar) {
char heart = startChar;
//...
}
And then change the calling to this:
hearts.hearts1('♥');
If you use this approach I would advise you to check if the given char-parameter (in Class1) is within a certain range of characters so you don't end up processing some chars you newver wanted to...
To take the idea with the scanner into consideration you could simply
public static hearts1() {
Scanner scanner = new Scanner(System.in);
System.outprinln("Enter starting char:");
String userInput = scanner.next();
char heart = userInput.charAt(0);
for (char currentChar = heart; currentChar < '❣'; currentChar++) {
System.out.print(currentChar + " ");
}
scanner.close();
}
But I don't advise this method because dependingon the user input it takes quite long for the program to print out the chars and furthermore it's really hard for the user to give the heart symbol as an input.
I hope this answers your question (partly)
Greetings Raven

Categories

Resources