How to use boolean to add numbers input by user? - java

I am writing this program for school work that asks the user to input a sequence of letters and numbers and determine whether it is a digit or not.
My teacher wants me to add up the characters that are digits(numbers) and output it as "Your numbers added up together are: place added number here"
and output the letters are a string saying "These are your letters: *place letters here."
I think I got the code right that determines whether it is a digit or not but how do I end up adding them? I tried using an if statement that checked if Character.isDigit is true but I keep getting errors and I think I'm writing it totally wrong. Any response would be greatly appreciated.
Here is my code:
import java.util.*;
import java.util.Scanner;
public class MyClass
{
public static void main(String args[])
{
int sum1 = 0;
String stringFull = "";
boolean isTrue = Character.isDigit(string1.charAt(i));
Scanner getString = new Scanner(System.in);
System.out.println("Please enter a sequence of letters: ");
String string1 = getString.nextLine();
for(int i = 0; i < 5; i++)
{
if (Character.isDigit(string1.charAt(i)))
{
sum1 += Character.getNumericValue(string1.charAt(i));
} else {
stringFull += string1.charAt(i);
}
if (isTrue)
{
System.out.println(sum1 * sum1);
}
}
}
}

You will get compilation error for below as i wasn't declared before this line
boolean isTrue = Character.isDigit(string1.charAt(i));
instead you should initialize it with false
boolean isTrue = false;
Then, your loop should loop till given string length, but you have hard-coded to 5, which will cause exception at runtime when string length is less than 5.
for(int i = 0; i < 5; i++)
should change to
for(int i = 0; i < string1.length(); i++)
Also, inside you for loop you are have following line of code, but you have never changed isTrue value inside the loop.
if (isTrue)
{
System.out.println(sum1 * sum1);
}
And, I think, right place to change isTrue value, where you are checking for digit.
if (Character.isDigit(string1.charAt(i)))
{
sum1 += Character.getNumericValue(string1.charAt(i));
isTrue = true;
}

You should use
Integer.parseInt(String.valueOf(string1.charAt(i)))
which returns the number, instead of
Character.getNumericValue(string1.charAt(i))
which returns the ascii code for the number

Related

I'm not getting output for my palindrome program in Java

import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int i;
String A=sc.next();
String B= "";
/* Enter your code here. Print output to STDOUT. */
for(i=A.length()-1;i<=0;i--){
B = B+A.charAt(i);
}
if(A.equals(B)){
System.out.println("Yes");
}
else{
System.out.println("No");
}
}
}
I'm not getting the required output for my code. I'm a beginner in Java.
The reason your program isn't giving you the desired output is because your for-loop is incorrect.
for(i.A.length()-1; i <= 0; i--) {/.../}
You are basically saying, whilst i is less than or equal to zero, execute the loop. i by default is greater than 0.
You can achieve a Palindrome check multiple ways. 2 Examples.
Example 1 using for-loop:
String A = "radar";
String B = "";
for(int i = A.length()-1; i >= 0; i -- ){
B = B + A.charAt(i);
}
System.out.println(A.equals(B) ? "Yes" : "No");
Example 2 with StringBuilder.
String A = "radar";
StringBuilder B = new StringBuilder(A).reverse();
System.out.println(A.equals(B) ? "Yes" : "No");
You are constantly getting an output of "No" because you're checking if i is less than or equal to zero on each loop, while you should be checking for greater than or equal to.
Change for (i = A.length() - 1; i <= 0; i--)
to
for (i = A.length() - 1; i >= 0; i--)
The for loop runs as long as the condition holds, in your case i<=0.
Unless the input has length 0 this condition never holds, thus the body of the for loop never gets executed and you immediately skip to if(A.equals(B))... which will always be false (except for the input "").
It should be i>=0.

StringBuilder.insert() not changing output

I'm trying to make a short program that converts any string into T H I S F O N T.
For example: "This is a test sentence" turns into "T H I S I S A T E S T S E N T N C E"
I have a StringBuilder inside a while loop, but using finale.insert(i, '\t'); doesn't work.
import java.util.Scanner;
public class Executable {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String x;
int i = 0;
System.out.print("Input text here: ");
x = input.nextLine();
StringBuilder finale = new StringBuilder(x.toUpperCase());
while(i > finale.length()) {
if(finale.substring(i, i) == " ") {
i += 2;
finale.insert(i, '\t');
}
}
System.out.println(finale);
}
}
Any help?
You have a few issues with your code. Before I present an implementation that works, let's look at those other issues.
Your while loop checks if i > finale.length(). Since i = 0 the while loop never has a chance to begin.
You are comparing strings using == and this is not correct. == is used to confirm two objects are equal, not the value of two strings. You would need to use string.equals() instead.
You're doing too much in your loop anyway. Using a simple for loop can accomplish the goal quite simply.
Here is a new loop you can use instead of what you have:
for (int i = 1; i < finale.length(); i++) {
finale.insert(i++, " ");
}
The output: T H I S F O N T
For those unfamiliar with for loops, here's a very simple breakdown of how the above is structured.
The for loop is defined in three parts:
for (variable_to_increment; repeat_until_this_condition_is_met; modify_variable_on_each_iteration) {
// Code to be executed during each pass of the loop
}
First, we define a variable that we can track on each loop: int i = 1. By setting i = 1, we are going to skip the first character in the string.
The next statement, i < finale.length() means that we want to keep repeating this loop until we reach the length of our string. For example, if the string is 5 characters long and we've run the loop 4 times, i now equals 5 and is no longer less than the string's length, so the loop ends.
The last part is i++. This tells Java what we want to do with i after each loop. In this case, we want to increment the value by 1 each time the loop repeats.
Everything inside the brackets is, obviously, the code we want to execute on each loop.
You're saying while i>finale.length() but i is initialized as 0. You never enter the while loop.
Some issues with your code (see inline comments):
import java.util.Scanner;
public class Executable {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String x;
int i = 0;
System.out.print("Input text here: ");
x = input.nextLine();
StringBuilder finale = new StringBuilder(x.toUpperCase());
while(i > finale.length()) { // this condition is incorrect. Initially
// this condition will always be false
// if you input some sentence. It should be
// i < finale.length()
if(finale.substring(i, i) == " ") { // here preferably you should use
// equals method to compare strings
i += 2;
// you are only incrementing the i if the ith
// substring equals " ". Firstly, substring(i,i)
// will return empty string because the second argument
// is exclusive
finale.insert(i, '\t');
}
}
System.out.println(finale);
}
}
If you want to have an alternate method (not very optimal) for doing what you want to do, you can try the following approach:
import java.util.Scanner;
public class Executable {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String x;
int i = 0;
System.out.print("Input text here: ");
x = input.nextLine();
String finale = x.toUpperCase().replaceAll(" ","").replaceAll("", " ");
System.out.println(finale);
}
}
First, convert the string to uppercase --> then remove all spaces between the words --> then insert spaces between all letters. The code line which does this is,
String finale = x.toUpperCase().replaceAll(" ","").replaceAll("", " ");
Here is a sample run:
Input text here: This is a sentence
T H I S I S A S E N T E N C E
The correct way with your method would be, just increment until you have twice the size of the initial String
while (i < x.length() * 2) {
finale.insert(i, '\t');
i += 2;
}
An easier way would be with a classic for-loop:
StringBuilder finale = new StringBuilder();
for (char c : x.toUpperCase().toCharArray()) {
finale.append(c).append('\t');
}
Use a for loop since you know the number of iterations:
Scanner input = new Scanner(System.in);
String x;
System.out.print("Input text here: ");
x = input.nextLine();
StringBuilder finale = new StringBuilder(x.toUpperCase());
int len = finale.length();
for (int i = 1; i < 2 * len; i+=2 ) {
finale.insert(i, '\t');
}
System.out.println(finale);
You are comparing strings with ==. Never do that; use equals instead.
For future readers: this job can be done elegantly using Java 8 Streams:
String result = str.chars()
.filter(i -> i != ' ')
.mapToObj(t -> (char) t)
.map(Character::toUpperCase)
.map(Character::valueOf)
.collect(Collectors.joining(" ");

Roman Numeral to Integer: what is wrong with my code

So I'm trying to make a converter from roman numerals to integers. What I have so far is this:
public int toNumber(String n){
int number = 0;
int first = 1;
int last = 0;
String substring = n.substring (last, first);
while(substring.equals("I")){
number = number+1;
last = last +1;
first=first +1;
}
while(substring.equals("V")){
number = number+5;
last = last +1;
first=first +1;
}
return number;
}
Obviously I only have I and V in right now, but when I make a tester class to try this out, it returns nothing and keeps letting me put in in a new line.
For the record, here is my tester class
import java.util.Scanner;
public class Tester{
public static void main (String[] args){
RomanNumeralConverter quantity = new RomanNumeralConverter();
Scanner user_input = new Scanner(System.in);
//this is for roman to number
System.out.println("input roman numeral");
String j = user_input.nextLine();
int g = quantity.toNumber(j);
System.out.println(g);
}
}
I'm almost entirely certain that it's a logic problem, but I have no idea what and I feel like I've tried everything I can think of
Your problem is a loop like this:
while(substring.equals("I")) {
number = number+1;
last = last +1;
first=first +1;
}
If the program enters that loop, it will stuck there, because you're not changing the value of substring. Therefore substring.equals("I") will always return true and the only way to stop that loop is terminating the application.
A better way to convert the entered String could be this:
public int toNumber(String n) {
int number = 0;
for (char chr : n.toUpperCase().toCharArray()) {
switch(chr) {
case 'I': number += 1;
break;
case 'V': number += 5;
break;
default: break;
}
}
return number;
}
It converts the provided String to uppercase (viii -> VIII) to avoid checking both cases of every char and converts it into a char array. This array will be used in a foreach loop that takes every single entry of it and tests it in a switch block. Every supported roman numeral has his own case there to increment number accordingly. Currently it supports I and V like in your code. Btw, number += 1 is just a short version of number = number + 1.
After that loop, it returns the converted integer value.

How do I get my value to print every time the loop increments in Java (For Loop)

I need to create a code that prints a pyramid like structure, given the user integer input which will be printed last. (I have attached an image of a final product below). I am new to programming, have been enjoying it, but am stuck in this problem.
My code can currently produce the user input 4 times. So I feel like I am close, just a little bit of tweaking will get the job done
I need my code to print out every single time that the loop increments instead of just displaying the user input a certain amount of times. I converted the integer to a string so that I can show the value x amount of times, but I feel that this is what is throwing me off. If I can somehow get the string to display the values at every incrementation then I will be golden. PLEASE HELP! Below is my code
import java.util.Scanner; //import scanner
public class NumberStack { // class
static Scanner myScanner; //declare scanner
public static void main(String[] args){ //add main method
myScanner= new Scanner (System.in); //scanner input declaration
int input= 0;
while (true) {
System.out.print("Enter an integer between 0 and 9 inclusive: ");
if (!myScanner.hasNextInt()) {
System.out.println("You have not entered an integer");
}
input= myScanner.nextInt();
if ( (input>=0) && (input<=9) ) {
String smln= Integer.toString(input);
String out="";
for (int p=0; p<input; p++) {
for (int j=0; j<input; j++) {
for (int i=0; i<((input*2)-1);i++) {
out += smln;
}
System.out.println(""+out);
out="";
smln= Integer.toString(input);
}
}
} //end of if statement
else {
System.out.println("You have not entered an integer within range");
}
} //end of while loop
} //end of main method
} //end of class
when you are facing problems like this one, you should try to look for a pattern...check this out
int input = 4;
for(int i = 1; i <= input; i++)
{
int times = i;
int length = 2 * i - 1;
String str = "";
for(int j = 0; j < length; j++)
{
str += i;
}
for(int k = 0; k < times; k++)
{
System.out.println(str);
}
}
Since your method is currently printing the data fro a particular number properly eg for input 4 it is printing
4444
4444
4444
4444
I would suggest that extract ur code for display into a separate function. And call that function using the number from a loop.
for(int i=1; i<=num;i++)
function_f1(i);
This should do the trick for you and since you are starting off with coding , it will also give you ideas on using methods.

out of bounds error with word count

I'm trying to write my own Java word count program. I know there may already be a method for this, but I'd like to get it work. I'm getting an out of bounds error at line 14. I'm trying to use an input word to count how many times it appears in an input string. So I'm looping up to stringlength - wordlength, but that's where the problem is.
Here is the code:
import java.util.Scanner;
public class wordcount {
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.print( "Enter word : " );
String word = s.nextLine();
Scanner t = new Scanner(System.in);
System.out.print("Enter string: ");
String string = t.nextLine();
int count = 0;
for (int i = 0; i < string.length()-word.length(); i = i+1){
String substring = string.substring(i,i+word.length());
if (match(substring, word)==true){
count += 1;
}
}
System.out.println("There are "+count+ " repetitions of the word "+word);
}
public static boolean match(String string1, String string2){
for (int i=0; i<string1.length(); i+=1){
if (string1.charAt(i)!=string2.charAt(i)){
return false;
}
}
return true;
}
}
First of all, two Scanners are not necessary, you can do many inputs with the same Scanner object.
Also, this if condition
if (match(substring, word) == true)
can be rewritten like
if (math(substring, word))
I would also recommend you to use i++ to increase the loop variable. Is not strictly necessary but is "almost" a convention. You can read more about that here.
Now, about theIndexOutOfBoundsException, I've tested the code and I don't find any input samples to get it.
Besides, there is an issue, you are missing one iteration in the for:
for (int i = 0; i < string.length() - word.length() + 1; i++) { // Add '+ 1'
String substring = string.substring(i, i + word.length());
// System.out.println(substring);
if (match(substring, word)) {
count++;
}
}
You can test it by putting a print statement inside the loop, to print each substring.
I'm not getting an out of bounds error, can you tell me what values you were using for word and string?
I have identified a bug with your program. If word is equal to string, it still returns count 0. I suggest adding one more iteration and using regionMatches instead. RegionMatches makes your match method obsolete and will return false if word.length() + i is equal or greater than string.length(), avoiding out of bounds issues.
As you can see I also moved the calculations to a seperate method, this will make your code more readable and testable.
And as Christian pointed out; you indeed do only need one Scanner object. I've adapted the code below to reflect it.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter word : ");
String word = sc.nextLine();
System.out.print("Enter string: ");
String string = sc.nextLine();
int count = calculateWordCount(word, string);
System.out.println("There are " + count + " repetitions of the word " + word);
}
private static int calculateWordCount(String word, String string) {
int count = 0;
for (int i = 0; i < string.length() - word.length() + 1; i++) {
if (word.regionMatches(0, string, i, word.length())) {
count++;
}
}
return count;
}

Categories

Resources