My content data in Notepad is 1 to 25. How can I display the data that is marked in red below. The other values can be ignored.
change
int i = sc.nextInt();
System.out.println(i + " ");
to
int i = sc.nextInt();
if(i%10 <= 5) {
System.out.println(i + " ");
}
Idea is that i%10 will give the unit digit of a number. So if it is <= 5 print that number.
Related
I have no idea how to phrase the title so feel free to make changes! I am stuck on this program that I have made involving a loop. I want the input to be 1 5 which means the code starts adding from 1 and all the way until 5, the expected output would be 1 + 2 + 3 + 4 + 5 = 15 but my code (see below) would print something like 1 + 2 + 3 + 4 + 5 + = 15. How do I get rid of that unwanted addition symbol?
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int start = keyboard.nextInt();
int end = keyboard.nextInt();
double dend = (double)end;
double dstart = (double)start;
double n = (dend - dstart + 1);
double sum = (n/2)*(dend+dstart);
int intsum = (int)sum;
for (int i =start; i <= end; i++) {
System.out.print(i+" + ");
}
System.out.print(" = "+intsum);
}
You could reduce the looping by one, and then print again
for (int i =start; i < end; i++) {
System.out.print(i+" + ");
}
System.out.print(end);
System.out.print(" = "+intsum);
or you could have if logic in your loop
for (int i =start; i <= end; i++) {
System.out.print(i);
if (i != end) System.out.print(" + ");
}
The logic could be something like:
for (int i =start; i <= end; i++)
{
if (i > start)
System.out.print(" + ");
System.out.print(i);
}
The idea is you only print "+" AFTER the first iteration of the loop.
Another option is to use a StringJoiner:
StringJoiner sj = new StringJoiner(" + ");
for (int i =start; i <= end; i++)
{
sj.add( i + "" ); // converts the "i" to a string
}
System.out.print( sj.toString() );
The StringJoiner will add the delimiter for you automatically as required.
As already mentioned by Scary Wombat you can reduce the lopping by one but in your code you are doing string concatenation for each element which not good (because of immutability nature of string in java).
So better to use some mutable string object (either StringBuilder/StringBuffer) and also you can have look at Collectors.joining() (which is introduced in Java8) if you would like implement this using streams.
An alternate solution would be to count the number of iterations and check if it is on it's last iteration. If not, then print a "+".
I am not really good at coding and I've been confused in this step where I don't know to make my code read the correct number of place values.
For example I run my code and it generates 5 random numbers then I input 5 random numbers the output of this would be "They share 0 numbers in the right place value.
For example,in order for me to get what I want, I get 5 random generated numbers which are 54123, I input 00123 it would say they hold 3 numbers in the right place value.
//this is what I think something needs to be edited
//This is my whole code on a google doc: https://docs.google.com/document/d/1ug1rRNwgZwBAf9kvaeAEFoo81r_W9Br6rRX4xc0fFUk/edit?usp=sharing
//I didn't enter my whole code on this post because I think it is to long and the only part I want is where it can calculate how many numbers in the right place value
System.out.println(s);
String f = scan.next();
for(int p=0; p<s.length(); p++) {
for(int z=0;z<f.length();z++){
if (s.substring(p,p+1).equals(f.substring(z,z+1))){
n++;
} }}
int rt= 0;
for(int p=0; p<s.length(); p++) {
for(int z=0;z<f.length();z++){
// this where i count the numbers in the right place
rt=99;
} }
System.out.println(" They share " + rt + " numbers in the right place value");
System.out.println(" They share " + n + " numbers in common");
System.out.println("guess number 1");
if(n ==5){
System.out.println(" Congratulations you win! ");
System.exit(0);
}
String generatedNums = "54123";
String nums = "00123";
int length = generatedNums.length() <= nums.length() ? generatedNums.length() : nums.length();
int count = 0;
for (int i = 0; i < length; i++) {
if (generatedNums.charAt(i) == nums.charAt(i)) {
count++;
}
}
System.out.println(count);
I need help validating input. I have a program that works with student grades based off user input. if someone enters grades below 0 or over 100 I want this loop to restart. Here is what I have so far:
double scores[] = new double[size];
for (int i = 0;i<= scores.length-1;i++)
{
System.out.print("\n\nScore number " + (i+1) + ": ");
scores[i] = sc.nextInt();
}
System.out.println("Here are your scores: " + Arrays.toString(scores));
I'm confused on how to implement invalid checker. I know it has something to do with a while loop. such as while a value is 0, and if someone enters invalid answer it will change from 0. But not sure how exactly I should do this, or if theres a better way
Any help appreciated. thanks
You can make use of a nested while loop and conditional statement for this:
for (int i = 0;i< scores.length;i++){
while(true){
System.out.print("\n\nScore number " + (i+1) + ": ");
int score = sc.nextInt();
if(score >= 0 && score <=100){
scores[i] = score;
break;
}else{
System.out.println("Error: score entered is outside allowable range");
System.out.println("Please try again");
continue;
}
}
}
You can simply ask the user to re-enter the value of the score which has been entered wrong.
double scores[] = new double[size];
for (int i = 0; i<= scores.length-1; i++)
{
System.out.print("\n\nScore number " + (i+1) + ": ");
scores[i] = sc.nextInt();
if(scores[i] < 0 || scores[i] > 100) {
i -= 1;
continue;
}
}
I'm confused on how to implement invalid checker. I know it has something to do with a while loop.
do-while loop is preferred in input validation because it allows input to be received first, then check if it passes the requirement. If input is invalid, repeat.
for(int i=0; i<scores.length; i++){
do{
System.out.print("\n\nScore number " + (i+1) + ": ");
input = sc.nextInt();
}while(input < 0 || input > 100);
scores[i] = input;
}
The for-loop and do-while loop serve different purpose. Hence, do not be confused by the
- for-loop which is only responsible to receive multiple inputs for the array and the
- while loop which is only responsible for validating every single input.
I need to print the factors of a perfect number. Here's the gist of my main class:
ArrayList<Integer> perfNums = new ArrayList<>();
Scanner in = new Scanner(System.in);
System.out.print("Enter the upperbound: ");
upperbound = in.nextInt();
for (int i = 1; i <= upperbound; i++) {
if (isPerfect(i)) { //boolean to check if number is a perfect number
perfNums.add(i);
}
}
System.out.println("Perfect numbers between 1 and " + upperbound + " are:");
for (int i = 0; i < perfNums.size(); i++) {
System.out.print(perfNums.get(i) + " = ");
printFactor((int)perfNums.get(i));
System.out.println();
}
Here's the printFactor class.
private static void printFactor(int number){
int factor = 1;
while(factor < number){
if (number%factor == 0) System.out.print(factor+ " + ");
//I don't know how to print the + sign otherwise.
factor++;
}
}
And here's a sample output:
Enter the upperbound: 10000
Perfect numbers between 1 and 10000 are:
6 = 1 + 2 + 3 +
28 = 1 + 2 + 4 + 7 + 14 +
496 = 1 + 2 + 4 + 8 + 16 + 31 + 62 + 124 + 248 +
8128 = 1 + 2 + 4 + 8 + 16 + 32 + 64 + 127 + 254 + 508 + 1016 + 2032 + 4064 +
I've got the main gist of it but I've struggled with an output issue. Due to the restrictions of my online submission system, my output needs to fit exact specifications.
My question is how do I go about printing all the factors of my perfect number but removing the + sign at the end? (e.g)6 = 1 + 2 + 3
I'm not too sure of many methods to print from a while loop. Would a for-loop be better for my goals? Or are there alternative methods to print the factors of a number?
The least amount of change to address this might be something like this:
private static void printFactor(int number)
System.out.print(1);
int factor = 2;
while (factor<number) {
if (number%factor == 0) System.out.print(" + " + factor);
factor++;
}
}
1 is always a factor, so you can print that before the loop and then prepend + to every subsequent factor.
You should cache the output you want to print into a StringBuilder. Then you are able to remove the last plus sign before you print the whole String. It also has a better performance.
private static void printFactor(int number)
{
StringBuilder output = new StringBuilder();
int factor = 1;
while (factor < number)
{
if (number % factor == 0)
output.append(factor + " + ");
factor++;
}
// remove last plus sign
output.deleteCharAt(output.length() - 1);
// print the whole string
System.out.print(output.toString());
}
Since factor starts from value 1 and number % 1 == 0 will always be true, you might print 1 first and then flip factor and + in System.out.print. Like this:
private static void printFactor(int number) {
if(number > 0) {
System.out.print(1);
}
int factor = 2;
while (factor<number) {
if (number % factor == 0) {
System.out.print(" + " + factor);
}
factor++;
}
}
Not the best solution, but it will do the job.
Try to create a variable String numb and use substring method like this:
String numb ="";
while(factor<number){
if(number%factor == 0)
numb= numb + factor+ " + ";
factor++;
}
System.out.print(numb.substring(0, numb.trim().length()-1));
Just for the sake of using Java 8 :)
private static void printFactor(int number){
System.out.println(IntStream.range(1, number)
.filter(p -> number % p == 0)
.mapToObj(i -> String.valueOf(i))
.collect(Collectors.joining(" + ")));
}
Thanks everyone for the quick response. You all have been a lifesaver, and I managed to pick up some new things to consider when I code in the future.
Anyway, while waiting for a reply I was fiddling with the code and came up with a rather inelegant solution, if anybody's interested. Here's the changes to the main class:
System.out.println("Perfect numbers between 1 and " + upperbound + " are:");
for(int i=0; i<perfNums.size(); i++){
System.out.print(perfNums.get(i) + " = ");
outputString = printFactor2(perfNums.get(i));
if(outStr.endsWith(" + ")) outStr = outStr.substring(0, outStr.length()-3);
//because the submission system would cry foul with even a single extra space
System.out.println(outStr);
}
And here's the changes to the printFactor class:
private static String printFactor2(int number){
String out = "";
int factor = 1;
while(factor<number){
if(number%factor == 0) out += factor + " + ";
factor++;
}
return out;
}
Basically, what I did was append the factors to a string, then removing the trailing + sign using the substring method. On hindsight, I probably should've called the substring method inside the printFactor class instead. Something like return out.substring(0, out.length()-3); perhaps?
Nevertheless, thanks everyone!
I have written a simple program in java to find the factorial, which works fine. I am now trying to refine the output, but I'm not sure how to do it.
My Program:
import java.util.Scanner;
public class UserInput {
public static void main(String[] args) {
int fact = 1;
Scanner number = new Scanner(System.in);
System.out.println("Enter the number : ");
int n = number.nextInt();
if (n < 0) {
System.out.println("Enter positive number");
} else {
System.out.print("Factorial Sequence is :");
for (int i = n; i >= 1; i--) {
fact = fact * i;
System.out.print(i + "*");
}
System.out.println("Factorial of number " + n + " is :" + fact);
}
}
}
Output shown is in this format (a single line, * after the 1):
Factorial Sequence is :5*4*3*2*1*Factorial of number 5 is :120
I want output in this format:
Factorial Sequence is :5*4*3*2*1
Factorial of number 5 is :120
Since 1 is not going to modify the factorial result your code can be rewriten as:
for (int i = n; i >= 2; i--) {
fact = fact * i;
System.out.print(i + "*");
}
System.out.println("1");
Another option is to use string concatenation during your for loop:
String s = "Factorial Sequence is :";
for (int i = n; i >= 1; i--) {
fact = fact * i;
s += i + (i > 1 ? "*" : "");
}
System.out.println(s);
Only 'benefit' this has over the other options is it saves calling System.out.print each iteration, at the expense of a string concatenation operation. Probably no performance difference at all, and certainly not significant here, but it is an alternate means to the same end.
EDIT: Use #demostene's excellent suggestion to avoid the final '*' after the final '1' - it avoids the conditional expression within the for loop, which is really nice as your factorial becomes larger.
To make the gap, you can add an \n literal to represent a newline.
System.out.println("\nFactorial of number " + n + " is :" + fact);
And for the last *, you can either remove it at the end or not add it if i is 1..
System.out.print(i + (i > 1?"*":""));
This says if i is greater than 1, return a *, otherwise return an empty string.
Just add a print line statement:
System.out.println(); // add this line
System.out.println("Factorial of number " + n + " is :" + fact);