Checking text length is divisible by 2 - java

I want to check whether a length of an input text is divisible by 2.
so it will be like
if my text length is 3, the result will be 1.5 and it will display not divisible by 2 and
if my text length is 6, the result will be 3.0 and it will display divisible by 2
but my codes will display the output "not divisible by 2" regardless what is the text length.
what have I done wrong?
import java.util.Scanner;
public class Test1 {
public static void main (String[]args)
{
String a =null;
int l = 0;
double result = 0.0;
Scanner scan = new Scanner(System.in);
System.out.println("Enter your string\n");
a = scan.nextLine();
l = a.length();
result = (double)l/2.0;
System.out.println(result);
if((double)result % 2 != .0) {
System.out.println("not divisiable by 2");
}
else {
System.out.println("divisiable by 2");
}
}
}

The mod operation is your friend but only with integers...
if (integer % divisibleBy == 0) { do stuff; }
Edit: I also found this page that does a really good job outlining the various uses mod the mod operator and explains why your double mod doesn't work like you expect.
Edit: Also more review of your code; it looks like you divide by 2 and then do mod by 2. So 6/2 = 3 and 3 is not even. Wonder if your code would work if you used 8 -> 8/2 = 4 and 4%2 = 0.

Check the length of the text, then do a modulo to it.

Modulo , an operation which checks if a number will have a remainder if its divided by another number
yourNumber%5 == 0
where yourNumber is the lenght of your String. Take it from here.

First, length() returns an int, and it's simpler to work with integers, so why are you casting the length to double? The % (modulo) operator is meant to work with integers, not doubles; remember, double numbers are floating-point numbers, so there's always room for numerical error if you use them.
Second, you don't need to use so many variables; keep it simple:
a = scan.nextLine();
if(a.length() % 2 == 0)
System.out.println("Length of string is divisible by 2");
else
System.out.println("Length of string is not divisible by 2");
Easier to read (and write), don't you think?

import java.util.Scanner;
public class Test1 {
public static void main (String[]args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter your string\n");
String str = scan.nextLine();
int length = str.length();
if(length % 2 !=0) {
System.out.println("not divisible by 2");
}
else {
System.out.println("divisible by 2");
}
}
}
There were a lot of problems with your code:
You are using a double to store the result for some reason, when it should've been an int
Your variable names are not descriptive of what they are for.
There is no need to initialize variables to a default value only to overwrite them with new values.

haha i hate these little mistakes. i do them all the time. Just switch both to %
String a =null;
int l = 0;
double result = 0.0;
Scanner scan = new Scanner(System.in);
System.out.println("Enter your string\n");
a = scan.nextLine();
l = a.length();
//this is your problem
result = (double)l%2.0;
//this is your problem
System.out.println(result);
if((double)result % 2 != .0) {
System.out.println("not divisiable by 2");
}
else {
System.out.println("divisiable by 2");
}

Related

How do you make it so that when you enter a number it puts a space between each integer

import java.util.Scanner;
public class Digits {
public static void main(String[] args) {
/*
*
count = 1
temp = n
while (temp > 10)
Increment count.
Divide temp by 10.0.
*/
//Assignment: fix this code to print: 1 2 3 (for 123)
//temp = 3426 -> 3 4 2 6
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
int count = 1;
int temp = input.nextInt();
while(temp >= 10){
count++;
temp = temp / 10;
System.out.print(temp + " ");
}
}
}
Need help fixing code.
Example: when you type 123 it becomes 1 2 3.
Your code is dividing by ten each time, that could be used to print the value in reverse. To print it forward you need a bit more math involving logarithms. Sometime like,
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
int temp = input.nextInt();
while (temp > 0) {
int p = (int) (Math.log(temp) / Math.log(10));
int v = (int) (temp / Math.pow(10, p));
System.out.print(v + " ");
temp -= v * Math.pow(10, p);
}
Alternatively, read a line of input. Strip out all non digits and then print every character separated by a space. Like,
String temp = input.nextLine().replaceAll("\\D", "");
System.out.println(temp.replaceAll("(.)", "$1 "));
Most of your code is correct, and what you are trying to do is divide by 10 and then print out the value - this probably should have been a modulus operation % to get the remainder of the operation and print that out - but a nice way of thinking about it.
Nevertheless.
You can just use a string and then split the string on each character
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
// we know that we are going to get some input - so we will just grab it as a String
// whilst we are expecting an int - we will test this later.
// we are doing this as it makes it easier to split the contents of a string
String temp = input.next();
// is this an int? - we will test this first
try {
// if this parsing fails - then it will throw a java.lang.NumberFormat exception
// see the catch block below
int test = Integer.parseInt(temp);
// at this point it is an int no exception was thrown- so let's go
// through and start printing out each character with a space after it
// the temp(which is a string).toCharArray returns a char[] which we
// can just iterate through and set the variable of each iteration to 'c'
for (char c : temp.toCharArray()) {
// now we are going to print out the character with a space after it
System.out.print(c + " ");
}
} catch (NumberFormatException ex){
// this is not an int as we got a number format exception...
System.out.println("You did not enter an integer. :(");
}
// be nice and close the resource
input.close();
}
Answering solely your question, you can use this one-line code.
int test = 123;
System.out.println(String.join(" ", Integer.toString(test).split("")));
Output is: 1 2 3

I have a problem with splitting up my Java program into separate methods within the same class, could I have some advice on how to go about it?

I was given the task of splitting my program which which allows the user to enter an array of numbers and after an odd number between 1 and 10 to check whether the odd number is a factor of each of the 5 numbers in the array. I keep on trying out different ways but none seem to work. Could someone help me out or send a sample of how I should sort it? This is the program:
import java.util.Scanner;
public class CheckboxExample{
public static void main(String args[]) {
CheckBox c = new CheckBox();
new CheckboxExample(); // links to checkbox class
Scanner s = new Scanner(System.in);
int array[] = new int[10];
System.out.println ("Please enter 10 random numbers"); // prompts the user to enter 10 numbers
int num; // declares variable num
try{
for (int i = 0; i < 10; i++) {
array[i] = s.nextInt(); // array declaration
}
}catch (Exception e){
System.out.println ("You have an error");
}
System.out.println ("Please enter an odd number between 1 and 10");
try{
num = s.nextInt ();
if (num % 2 == 0){
do{
System.out.println ("\nYour number is even, enter an odd one");
num = s.nextInt ();
}while (num % 2 == 0);
}
if (num < 0 | num > 10){
do{
System.out.println ("Your number is outside of the range, try again");
num = s.nextInt ();
}while (num < 0 | num > 10);
}
for (int i = 0; i < 5 ; i++){
if (array[i] % num == 0) {
System.out.println("Your number is a factor of " + array[i] );
}
}
}catch (Exception e){
System.out.println ("error");
}
}
}
A method should ideally be responsible for one task. In your case you should think about the different things your code try to do and organize them in a sense that each of the methods you call does one thing of the list of things you try to do.
As an example: As far as I understand your code does the following things:
Read an array of 10 values
Read an odd number
Verify the number is odd
Verify the number is in range
Calculate if the number is a factor of one of the 10 numbers in the array
Now one possible approach would be to separate your code in 5 methods that do exactly these things.
At first you call the method that reads the 10 numbers.
Then you call the method to read the odd number.
3. and 4. are actually part of reading the number, since you need to retry on an invalid input, so you could write your method for inputting the odd number in a way that it uses the methods for verifying the input.
Finally when you have all the valid input, you call the method which produces your result (ie. if the number is a factor of the numbers in the list).
A general outlier for your code could look like:
public class CheckboxExample {
public static void main(String args[]) {
CheckBox c = new CheckBox();
new CheckboxExample(); // links to checkbox class
Scanner s = new Scanner(System.in);
int array[] = readInputArray();
int number = readOddValue();
calculateFactors(array, number);
}
private int[] readInputArray() {...}
private int readOddValue() {...}
private void calculateFactors(int[] array, int number) {...}
//additional methods used by readOddValue which verify if the value is actually odd
}
Please note that this is just one way to split your code into methods and there are several ways to design and implement each of these methods.

Java Modular calculator

I'm attempting a code abbey problem and i'm very stuck. My goal for the program is to take in numbers with a math operation before the number and to do that math operation such as:
5
+ 3
* 7
+ 10
* 2
* 3
+ 1
% 11
answer:
1
I feel as if i'm very close but cannot seem to get the answer I want to also add my answers up every single time.
import java.util.Scanner;
public class ModularCalculator {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter Initial Number:");
int iN = in.nextInt();
int sum = 0;
for (int i = 0; i <= 1000000; i++) {
String a = in.next();
int b = in.nextInt();
if (a.equalsIgnoreCase("+")) {
System.out.println(b + iN);
} else if (a.equalsIgnoreCase("*")) {
System.out.println(b * iN);
} else {
System.out.println(b % iN);
sum = b + iN;
}
}
}
}
Your issue is that your not doing proper algebra. Remember the order of operations. In your particular case, we can simplify it to only use the operations that you have, which are: Multiply, Modulo, Addition. Technically, Modulo isn't really standardized in where it is ordered, but I think most languages have Modulo as the same as Multiply/Divide, so a safe bet is to order it that way.
Since this is for a homework assignment clearly, I'm not going to fix your code for you. I will tell you though, that is definitely your issue. Think about how you would go about solving this...hint hint...don't read a token at a time...try reading more than that...
this will not work correctly ! because you are not working right , for example :
the answer of 1+2*3 equals to 7
but your program will return 9 as answer
i think you must learn about postfix and prefix and how to use stack to achieve this goal , here is a link for study :
http://www.cs.man.ac.uk/~pjj/cs212/fix.html
The problem you were having was that you weren't storing the value from last calculation properly. Al I did was just storing last calculated value in "iN".
Scanner in = new Scanner(System.in);
System.out.println("Enter Initial Number:");
int iN = in.nextInt();
int sum = 0;
for (int i = 0; i <= 1000000; i++) {
String a = in.next();
int b = in.nextInt();
if (a.equalsIgnoreCase("+")) {
iN = b + iN;
} else if (a.equalsIgnoreCase("*")) {
iN = b * iN;
} else {
iN = b % iN;
sum = b + iN;
}
System.out.println(iN);
}

Making loops in order to test values [duplicate]

This question already has answers here:
Validating input using java.util.Scanner [duplicate]
(6 answers)
Closed 7 years ago.
I need help making a loop that looks at each value from 1 to number-1.
Also how to test each value to see if it is a
divisor of number, and if it is, adding it to the sum.
This is what I have so far:
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.print("Please enter a positive integer: ");
int n = input.nextInt();
while (n < 0) {
System.out.println(n + " is not positive.");
System.out.print("Please enter a positive integer: ");
n = input.nextInt();
}
}
You can use this as a starting block for your application:
package Testers;
import java.io.Console;
public class Application {
public static void main(String[] args)
{
Console console = System.console();
if (console == null)
{
System.err.println("No console.");
System.exit(1);
}
boolean keepRunning = true;
while (keepRunning)
{
String name = console.readLine("Type your positive integer");
try{
int integer = Integer.parseInt(name);
if(integer < 0){
System.out.println("You must specify a positive integer!");
}
for(int i = 1; i<integer; i++){
// our variable "i" is smaller than "integer". This will parse all the numbers between one and "integer" -1.
if(i % 2 == 0){
//"i" IS divisible by 2. Of course, you can change this value to what you want to change it to.
//Here you can add it to a sum
}else{
//"i" is not divisible by 2. Of course, you can change this value to what you want to change it to.
}
}
}catch(NumberFormatException e){
System.out.println("You must specify a positive integer!");
}
}
}
}
If you want to do something for a known number of times, it is mostly a good idea to use a for loop. If you want to do something for number 1 to n-1, the loop could look like
for(int i = 1; i < n; i++) { // do stuff }
Note that it starts counting from 1 and stops as soon as i is greater or equal than n.
In order to know whether a number, say n, is divisible by some number, say k, the modulo-operator % could be used. If n % k == 0 this means that n is divisible by k. With an if-statement this can be tested and when you have some sum variable you can add whatever you want to that variable to sum things up.
Hope that helps

How to input a lot of data until you type in an invalid number in java

User inputs numbers one by one and then once they type in an invalid number (has to be from 1-200) the program calculates the average of the numbers that were inputted.
I'm just wondering what would the code be for this. I know the one for inputting one piece of data. Example would be:
`Scanner in = new Scanner(System.in);
String numberOfShoes = "";
System.out.println("Enter the number of shoes you want: (0-200) ");
numberOfShoes = in.nextLine();`
this is just an example, but this time I want the user to input a lot of numbers. I know I'm going to include a loop somewhere in this and I have to stop it once it contains an invalid number (using a try catch block).
* I would also like to add that once the user inputs another number it always goes to the next line.
Just use a while loop to continue taking input until a condition is met. Also keep variables to track the sum, and the total number of inputs.
I would also suggest having numberOfShoes be an int and use the nextInt() method on your Scanner (so you don't have to convert from String to int).
System.out.println("Enter your number of shoes: ");
Scanner in = new Scanner(System.in);
int numberOfShoes = 0;
int sum = 0;
int numberOfInputs = 0;
do {
numberOfShoes = in.nextInt();
if (numberOfShoes >= 1 && numberOfShoes <= 200) { // if valid input
sum += numberOfShoes;
numberOfInputs++;
}
} while (numberOfShoes >= 1 && numberOfShoes <= 200); // continue while valid
double average = (double)sum / numberOfInputs;
System.out.println("Average: " + average);
Sample:
Enter your number of shoes:
5
3
7
2
0
Average: 4.25
It added 5 + 3 + 7 + 2 to get the sum of 17. Then it divided 17 by the numberOfInputs, which is 4 to get 4.25
you are almost there.
Logic is like this,
Define array
Begin Loop
Accept the number
check if its invalid number [it is how u define a invalid number]
if invalid, Exit Loop
else put it in the array
End Loop
Add all numbers in your array
I think you need to do something like this (which #Takendarkk suggested):
import java.util.Scanner;
public class shoes {
public void main(String[] args){
int input = 0;
do{
Scanner in = new Scanner(System.in);
String numberOfShoes = "";
System.out.println("Enter the number of shoes you want: (0-200) ");
numberOfShoes = in.nextLine();
input = Integer.parseInt(numberOfShoes);
}while((input>=0) && (input<=200));
}
}
you can use for loop like this
for(::)
{
//do your input and processing here
if(terminating condition satisified)
{
break;
}
}

Categories

Resources