StringBuilder not printing its value? [closed] - java

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 7 years ago.
Improve this question
I'm a noob to java, so I'm sorry if this is a simple question.
I always found it interesting that you could condense a number into a single digit by adding its digits together. Thus, I decided to try to make a program to do it for me! Here's an example.
Input: 557
5 + 5 + 7 = 17
1 + 7 = 8
Answer: 8
See! This obviously would work with any number. But, my program is terminating with no output. Can anyone help me out? I'm not so used to tringBuilder, so I think that might be the issue.
import java.util.Scanner;
import java.lang.StringBuilder;
public class MagicNumberApp
{
public static void main (String [] args)
{
int number;
String numberstring;
boolean keepGoing = false;
Scanner input = new Scanner(System.in);
StringBuilder builder = new StringBuilder();
sopl("Welcome to Magic Number! \nThe idea is to add the idividual digits of a number "
+ "\nuntil it is condensed into a one digit number.\n\nInput a number...");
sop(">");
number = input.nextInt();
numberstring = Integer.toString(number);
if (numberstring.length() < 1)
keepGoing = true;
sopl("");
number = 0;
while (keepGoing)
{
for (int i = 0; i < numberstring.length(); i++)
{
number += Character.getNumericValue(numberstring.charAt(i));
builder.append("+" + numberstring.charAt(i) + " ");
}
builder.append("=" + number);
sopl(builder);
if (numberstring.length() > 1)
{
numberstring = Integer.toString(number);
number = 0;
sopl("");
}
else
{
keepGoing = false;
}
}
}
public static void sop (Object o)
{
System.out.print(o);
}
public static void sopl (Object o)
{
System.out.println(o);
}
}

Your keepGoing logic is backwards. You are setting keepGoing to true is the inputted number is less than 1 digit and you initialized it to false.
if (numberstring.length() < 1)
keepGoing = false;
All numbers have at least one digit, even 0, so there is no need for the above test before the while loop. Remove it. But you must initialize keepGoing to true.

I believe the problem lies in this line:
if (numberstring.length() < 1)
keepGoing = true;
Right now it is saying that keepGoing will only be true if numberstring has a length of 0. You can change it to something like this:
if (numberstring.length() > 1)
keepGoing = true;
Edit: I have an additional suggestion. You can add an else statement to print a message if the user input does has one digit:
else
sopl(number + " only has one digit. Try again!");

In addition to all the answers. I recommend you read your input as String and save yourself the initial conversion to string.
numberstring = input.nextLine();

Related

Integer cannot be converted to boolean using "indexOf()" [closed]

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 4 years ago.
Improve this question
I'm trying to count how many times the word "ing" occurred in a string asked by a user, I'm having an error saying it cannot be converted.
I tried using s.indexOf("ing")
package javaapplication3;
import java.util.*;
public class JavaApplication3 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String s,q = null;
String i = "ing";
int count=0;
System.out.println("Entrer une ligne de texte :");
s = in.next();
if ( s.indexOf("ing") ){
count++;
q = s.replaceAll("ing", "ed");
}
System.out.println("\"ing\" est occuree " +count +" fois.");
System.out.println(q);
}
}
I expect the output would give me and count how many times it occurred but I'm having an error.
Use s = in.nextLine(); rather than next() to read the whole line
You need to count until the lookFor part is still in the word, each time replace the first occurence by something else, and continue using a while loop
String lookFor = "ing";
while (s.indexOf(lookFor) != -1) {
count++;
s = s.replaceFirst(lookFor, "ed");
}
same as
String lookFor = "ing";
while (s.contains(lookFor)) {
count++;
s = s.replaceFirst(lookFor, "ed");
}
You should loop over your input till your string does not have the required literal available,
int count = 0;
while (s.indexOf("ing") != -1) {
s = s.replaceFirst("ing", "");
count++;
}
System.out.print("Total occurances : "+count);

validate input is a number, in a range of numbers or a specific character [closed]

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 6 years ago.
Improve this question
I have written the following code that checks if an input value is a number or the character 'R' or 'r'.
I also need to check that if it is a number, it is greater than 0 and less than an array length.
Is it possible to do all of this on same line as the existing conditions?
int array_length = menu.length;
while (!input.hasNextInt() && !input.hasNext("[rR]")) {
System.out.println("Invalid option entered. Please try again.");
System.out.println();
System.out.print("Select option > ");
input.next();
}
I'm not optimizing string comparison here, but basically that's what you probably need.
Scanner input = new Scanner(System.in);
int array_length = 5;
String value;
while (!"R".equals(value = input.next()) &&
!"r".equals(value) &&
!(value.matches("[0-9]+") && Integer.parseInt(value) >= 0 && Integer.parseInt(value) < array_length )) {
System.out.println("Invalid option entered. Please try again.");
System.out.println();
System.out.print("Select option > ");
}
System.out.println("Thanks!");
I'd like to use regular expression for your case.
int size = 3; // replace by your menu length
String input = "r";
String regEx = String.format("^(r|R|[1-9][0-9]*{1,%d}$)", size);
Pattern p = Pattern.compile(regEx, Pattern.DOTALL);
Matcher m = p.matcher(input);
while (m.find()) {
// your logic here
// if it comes to this point, it means
// the input is a number or
// the input is r or
// the input is R and
// the input must be greater than 0
// the input must be in range is 'size'
System.out.println("Qualified with all above criteria");
}

Simple bulls and cows java game [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 7 years ago.
Improve this question
I try to create a verry simple Bulls and Cows game (https://en.wikipedia.org/wiki/Bulls_and_Cows). The game is for my school project. My knowledge is limited, so I need to make the game using only loops, IF-else constructions and other simple functions.
The written code works somewhat - generate code and understands that number is hited, but did not indicate how many cows and bulls have in the wrong assumptions.
I would be glad if someone point me in the right direction :) Thanks in advance
import java.util.Random;
import java.util.Scanner;
public class BCgame{
public static void main(String[] args){
Random r= new Random();
int number= 0;
int trynum = 0;
while(uniq(number= (r.nextInt(9000) + 1000)));
String targetStr = number +"";
boolean game = true;
Scanner input = new Scanner(System.in);
do{
System.out.println(number);
int bulls = 0;
int cows = 0;
System.out.print("Guess a number: ");
int guess;
guess = input.nextInt();
if (uniq(guess) || guess < 1000) continue;
trynum++;
String guessStr = guess + "";
for(int i= 0;i < 4;i++){
if(guessStr.charAt(i) == targetStr.charAt(i)){
bulls++;
}else if(targetStr.contains(guessStr.charAt(i)+"")){
cows++;
}
}
if(bulls == 4){
game = false;
}else{
System.out.println(cows+" Cows and "+bulls+" Bulls.");
}
}while(game);
System.out.println("You won after "+trynum+" guesses!");
}
public static boolean uniq(int num){
String checknum = num+"";
if(checknum.charAt(0) == checknum.charAt(1)) return false;
else if(checknum.charAt(1) == checknum.charAt(2)) return false;
else if(checknum.charAt(2) == checknum.charAt(3)) return false;
return true;
};
}
You've already gone a long way towards the solution using the Rosetta example (http://rosettacode.org/wiki/Bulls_and_cows#Java). Just continue to work through it.
Experimentation is key to learning a language well, so make sure you understand what each line is doing and test the results.
Also, learn how to use your debugging tools to see which lines are behaving differently to what you expect, and then try and understand why.
If you get stuck on a specific statement then post that. Otherwise, this question is too unspecific, especially when Rosetta has a working example for you.

Creating a loop to check array (java)

Homework assignment Suggestions only please as I wish very much to learn this as second nature!
The goal is to create an array with a user specified question amount (array size) followed by an answer key (said array size now filled). Then to have the user input the "students" answers to check against key.
I wrote all that no worries. Works lovely. The issue I am having is in two areas:
Create a loop that asks to grade another quiz.
Have it only check/score/calculate every other answer. ie: even answers only.
I have used a do/while loop to continue checking but couldn't get a sentinel value to stick. Also depending on where I placed it, the answers kept coming up as the first check. So I am unsure as to where to place and how to write it. I even tried to use a for loop boxing in the array and student answer portion to no avail.
As regards to having it check every other one, I thought of modifying the count of "i" to something like ((i+1)*2) instead of i++ for the two for loops but I just get errors as that seems to not be proper at all.
Thank you in advance!
import java.util.Scanner;
import java.text.NumberFormat;
public class EvenQuizzes {
public static void main(String[] args) {
int quizQuest = 0, count = 0;
double percentTotal = 0.0;
Scanner scan = new Scanner(System.in);
System.out.print("How many questions are in the quiz? Or enter 0 to quit. ");
quizQuest = scan.nextInt();
int[] answers = new int[quizQuest]; // scan in question total and apply
// to array
System.out.println("Enter the answer key: ");
for (int i = 0; i < answers.length; i++) {
answers[i] = scan.nextInt();
}
for (int i = 0; i < answers.length; i++) {
System.out.println("Enter the answer to be graded : ");
int toGrade = scan.nextInt();
if (toGrade == answers[i]) {
count++;
}
}
percentTotal = ((double) count / quizQuest);
NumberFormat defaultFormat = NumberFormat.getPercentInstance();
defaultFormat.setMinimumFractionDigits(2);
System.out.println("The questions answered correctly total: " + count);
System.out.println("The percentage correct is: " + defaultFormat.format(percentTotal));
System.out.println("\nAnother quiz to be graded?");
}
}
// do ( quizQuest != 0){ //condition check to run new quiz against KEY
// for (int j = 0; (quizQuest = scan.nextInt()) != 0; j++); {
At the bottom is what I had considered for the loop portion I am having trouble with.
As you asked for hints (and not the code), here it is:
For more than one quizzes, use do-while, as follows:
do{
//do something
//scan the value of quiz quest
//do something
}while(quizquest != 0)
Now, if only answers at even positions are to be checked, do following:
for (int i =0; i <answers.length; i++)
{
System.out.println("Enter the answer to be graded : ");
int toGrade = scan.nextInt();
if(i % 2 == 0 && toGrade == answers[i]){
count++ ;
}
}
Create a loop that asks to grade another quiz: You could use a do-while loop with a boolean indicating if the user (teacher?) wants to grade another quiz:
do{
boolean continue = false;
// check if the user wants to continue
while(continue);
Have it only check/score/calculate every other answer. ie: even answers only: You can check for even answers with the modulo operator:
if(i % 2 == 0){
// even answer
}
Hope this helps!
You should have a variable, perhaps named continue, whose default value is 'Y'. At the very beginning, create a while loop that checks the condition continue==Y, and at the end when you ask "Another quiz to be graded?", read in the input to the variable continue.

String cannot be converted to double error java [closed]

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 8 years ago.
Improve this question
My code is suppose to read up to 100 string and store the values in an array.
When an empty string is entered it stops reading information from a user.
Then it validates the strings, converts to double numbers and is stored into a separate array.
Then the average of all valid numbers is found.
The only things that are printed are:
1) the number of valid strings entered
2) all valid strings in reverse order they were inputed
and
3) the average of all valid inputs.
I think I have it okay, except when converting the strings into double numbers. I placed that into a try/catch along with everything else after that because otherwise it can't find the valid inputs.
I am getting an error:(48: error: incompatible types: String cannot be converted to double).
I have tried adding an else to my if statement but it doesn't connect the if and else statements. Though when I add the else statement the error goes away and it just tells me the only error is that it cannot find the if for the else.
What can I do?
EDIT: Thank you, it works now. But I don't think I am finding the average correctly. Any suggestions?
import java.util.*;
public class Grades{
public static void main(String args[]){
int arraycount = 0;
final int SIZE = 10;
int validArraycount = 0;
final int ValidArraySize = 10;
int valuesinValidArray = 0;
Scanner reader = new Scanner(System.in);
String initialInput = new String ("");
String [] sArray = new String[SIZE];
double [] ValidArray = new double[ValidArraySize];
double sum = 0;
boolean exit = false;
System.out.println("You may enter up to 100 grades.");
System.out.println("When you are done entering grades, press the enter/return key.");
//Prints to user. Stops if nothing is entered.
while((arraycount < SIZE)&&(exit == false)){
System.out.println("Enter line " + (arraycount+1) + ": ");
initialInput = reader.nextLine();
if (initialInput.length()<1){
exit = true;
}
else{
sArray[arraycount]=initialInput;
arraycount++;
}
}
//convert string to double
try{
double convertedInput = Double.parseDouble(initialInput);
//validate strings entered by user
if(convertedInput >= 0 && convertedInput <=100){
ValidArray[validArraycount] = initialInput;
}
//Prints number of valid values entered
if(ValidArray.length>0){
System.out.println("The number of valid grades entered is " + ValidArray[0]);
}
//for printing array backwards
for (int i = (arraycount-1); i>=0; i--){
System.out.print(ValidArray.length);
}
//calculates sum of all values in array of ValidArray (of grades)
for(double d : ValidArray){
sum += sum;
}
//avergae of valid number array
double average = (sum/ValidArray.length);
System.out.println("Average: " + average);
}
catch(NumberFormatException e){
}
}
}
ValidArray[validArraycount] = initialInput;
is probably supposed to be
ValidArray[validArraycount] = convertedInput;
At this line:
ValidArray[validArraycount] = initialInput;
You are trying to assign a String to an array of doubles. This is where the error is coming. You can try calling double.parseDouble(initialInput) on this if you are sure it will be a double in String form.
It looks like you're assigning the wrong value to your array. Replace:
ValidArray[validArraycount] = initialInput;
With:
ValidArray[validArraycount] = convertedInput;
As previously mentioned, to fix your String conversion issue, you're assignment line should be:
ValidArray[validArraycount] = convertedInput;
To fix your average problem, your code should look like this:
//calculates sum of all values in array of ValidArray (of grades)
for(double d : ValidArray){
sum += d; // <-------- changed from sum += sum;
}
//avergae of valid number array
double average = (sum/ValidArray.length);

Categories

Resources