This question already has answers here:
Printing with delimiter only between values
(3 answers)
Closed 2 years ago.
I was tasked to do a looping problem for Java, but I'm currently having a problem on how to display a factorial of a number. For example, 1x2x3x4x5 = 120.
I'm almost there, but I can't seem to figure out how to, or is there any possible way to display the factorial of a number because there is always an additional "x" at the end of the 5.
Here is my code:
import java.util.*;
public class trylangpo2 {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
int fctr;
System.out.println ("number");
fctr = input.nextInt();
for (int i = 1; i <=fctr; i++){
System.out.print(i);
int j;
for (j =1; j <=1 ; j++){
System.out.print("*");
}
}
}
}
Example output:
1x2x3x4x5x
Your loop for (j =1; j <=1 ; j++) can be removed. It only loops once so, just write System.out.print("*"). No loop required
Then if you think about it, you want to print the number and the * all the time, except when it is the last number (fctr)
So write it that way:
Scanner input = new Scanner (System.in);
int fctr;
System.out.println ("number");
fctr = input.nextInt();
for (int i = 1; i <=fctr; i++){
System.out.print(i);
if(i<fctr) {
System.out.print("*");
}
}
Try to add a condition if it’s not at the end of the loop. Then add start and if it’s the end, then just print the number:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int fctr;
System.out.println("number");
fctr = input.nextInt();
for (int i = 1; i <= fctr; i++) {
if (i < fctr) {
System.out.print(i + " * ");
} else {
System.out.print(i);
}
}
}
I always use a construct like
String sep="";
for (...) {
System.out.print(sep);
System.out.print(payload);
sep="x";
}
You need to make the printing of ***** condition. Don't print ***** if i == fctr. And you don't need that additional loop of j. As below :
public static void main(final String[] args) {
final Scanner input = new Scanner(System.in);
int fctr;
System.out.println("number");
fctr = input.nextInt();
// IntStream.range(1, fctr).
long factorial = 1;
for (int i = 1; i <= fctr; i++) {
factorial = factorial * i;
if (i == fctr) {
System.out.print(i);
} else {
System.out.print(i + "*");
}
}
System.out.print("=" + factorial);
}
Related
Im not sure how to compare the characters char < Char and add the count
it should print
Enter a line:
antidisestablishmentarianism\(whatever the user wants to input)
Your Answer 15
import java.util.Scanner;
public class CountRisingPairs {
public static void main(String[] args) {
Scanner in =new Scanner(System.in);
System.out.println(" Enter a string");
String S=in.next();
int count;
int value;
for (int i=65; i<91; i++) {
count=0;
for (int j=0; j<in.length(); j++) {
value=(int)in[j];
if (value == i) {
count++;
}
}
if (count>0)
System.out.println((char)i+" -- "+count);
}
}
}
i cant use hash map or any other type of loop.
The loop should iterate over all characters from the first to the next but last so you can compare adjacent characters. They can be compared just like integer values.
String s = "antidisestablishmentarianism";
int count = 0;
for( int i = 0; i < s.length() - 1; ++i ){
if( s.charAt(i) < s.charAt(i+1) ) count++;
}
System.out.println( "count = " + count );
For comparing chars in the input, you should probably keep a variable with the previous char to compare to. I don't think comparing to the index variable i is what you want. Then your if statement would be something like
if (value > previous) {
count++;
}
Also, when iterating over the input of a Scanner, you should probably do it with a while loop like this:
while (in.hasNext()) {
// Your counting here
}
You need a way to terminate that while loop - you can do that by checking for '\n' or something else. And of course, the while loop can be rewritten as a for loop if you want to.
String element = "antidisestablishmentarianism";
int count = 0;
for (int j=0; j<element.length(); j++)
{
if(j+1 < element.length()){
int x = Character.getNumericValue(element.charAt(j));
int y = Character.getNumericValue(element.charAt(j+1));
if(x>y){
count++;
System.out.println("Pair: "+element.charAt(j)+""+element.charAt(j+1));
}
}
}
System.out.println(count+" pairs found");
Based on your code, also closing the scanner using try-with-resources:
import java.util.Scanner;
public class CountRisingPairs {
public static void main(String[] args) {
try (Scanner in = new Scanner(System.in)) {
System.out.println(" Enter a string");
String inputString = in.next();
int count = 0;
char previousChar = 100;
for (char currentChar : inputString.toCharArray()) {
if (currentChar > previousChar) {
count++;
}
previousChar = currentChar;
}
System.out.println(count);
}
}
}
Here is my program which is supposed to create an array and initialize prime numbers to it. The prime numbers should then be printed but the program just keeps running.
import java.util.*;
public class primes
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter number of primes ");
int x = scan.nextInt();
int[] prime = new int[x];
int div=2,hold=2;
int c=0;
while (prime[x-1]==0)
{
for(int a=2; div>a;a++)
{
if(div>a && div%a==0)
a=div;
else if(div==(a-1))
hold=div;
}
if(div==2||hold!=prime[c-1])
{
prime[c]=hold;
c++;
}
div++;
}
for(int f =0; f<x;f++)
System.out.print(" "+prime[f]+" ");
}
}
I tried changing my loops but I just don't know whats wrong
Like the others mentioned your logic is not right, try something like:
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter number of primes ");
int x = scan.nextInt();
List<Integer> primes = getPrimes(x);
Integer[] primeArray = primes.toArray(new Integer[primes.size()]);
for(int i :primes.toArray(primeArray)){ // you could just use for(int i :primes){ if you don't need array
System.out.print(i + " ");
}
}
private static List<Integer> getPrimes(int upperLimit) {
ArrayList primes = new ArrayList();
for (int i = 2; i < upperLimit; i++) {
boolean isPrime = true;
// Is it prime?
for (int j = 2; j < i; j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if (isPrime)
primes.add(i);
}
return primes;
}
The above will print out up to the numbers entered so if you type 5 it will print out 2 3 but not 5.
The following is an other example with Java 8, this one will print as many prime numbers based on the input, if you input 5 you will get 2 3 5 7 11
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter number of primes ");
int x = scan.nextInt();
long[] prime = primes(x).toArray();
Arrays.stream(prime).forEach(value -> System.out.print(value + " " ));
}
private static LongStream primes(long max) {
return LongStream.iterate(2, i -> i + 1)
.filter(PrimeNumber::isPrime)
.limit(max);
}
private static boolean isPrime(long x) {
return LongStream.rangeClosed(2, (long)(Math.sqrt(x)))
.allMatch(n -> x % n != 0);
}
Your code is wrong. First correct it, And i think you want to store prime numbers coming in range of 1 to N where N is user provided number. Use arrayList (growable) to store it.
It will keep on running because you have this: while (prime[x-1]==0). Where x is an input from the user. Say 5 for instance, then prime[5-1] initially is going to contain a 0 always, and you are running your while loop on this condition which is always going to turn true, thus never ending. Also, your prime number generation logic is not right!
I ran your code in debugger mode and I found the problem.
I tested your program with x=5.
At the end of the first while loop iteration you have :
prime[0] = 2
div = 3
hold = 2
c = 1
And here's the problem :
if(div==2||hold!=prime[c-1])
{
prime[c]=hold;
c++;
}
This part won't ever be reached anymore because :
div is never decrement, so it will always be superior to 2.
hold is
equal to prime[c-1], and never change value.
So prime will always stick to be : 2 0 0 0 0, and your while loop will never end.
I found what was wrong and rewrote the code, it works now. The program asks the user for the number primes they want to see and it prints them after storing them in a basic integer array.
import java.util.*;
public class Prime
{
public static void main(String [] args)
{
Scanner scan= new Scanner(System.in);
int i=0, hold=2, d=2;
boolean flag = true;
System.out.println("Enter the number of primes.");
int[] prime= new int[scan.nextInt()];
for(;flag;){
for(int a=2;d>a;a++){
if(d==(a)||d%a==0){
break;
}
if((d-1)==a){
hold = d;
}
}
d++;
if(hold==2 || hold!=prime[i-1]){
prime[i] = hold;
i++;
}
if(i==prime.length)
flag= false;
}
for(int x=0;x<prime.length;x++)
System.out.print(prime[x]+" ");
System.out.println("");
}
}
I am taking a course and I have the programs run in a loop so you can easily exit by entering "Quit". I am running into trouble working with arrays. This has the user type in sentences and then at the end shows the user what they typed. I want to have the program check each input the user types in and if it is "Quit", I want to exit the program. I am new to Java so looking for something that is within my understanding without using a break if possible.
I have attempted to use a boolean in my while loop to quit when it is set to false.
public static void main(String[] args)
{
String [] Responses = new String [10];
boolean ExitLoop = true;
do
{
Scanner Input = new Scanner(System.in);
int n = 0;
for (int i = 0; i < 10; i++)
{
System.out.println("Please enter sentence " + (i+1) + ": ");
Responses[n] = Input.nextLine();
if (Responses[n] == "Quit")
{
ExitLoop = false;
}
n++;
}
System.out.println();
for (int j = 0; j < 10; j++)
{
System.out.println("Sentence " + (j+1) + " " + Responses[j]);
}
}
while (ExitLoop);
}
To exit the application you can call the following line from anywhere.
System.exit(0);
Integrated into you code it would look like this.
for (int i = 0; i < 10; i++)
{
System.out.println("Please enter sentence " + (i+1) + ": ");
Responses[n] = Input.nextLine();
if (Responses[n].equals("Quit"))
{
System.exit(0); //add this to exit the application
}
n++;
}
If you wanted to keep separation of concerns you could make a method that exits the application.
public void ExitApplication()
{
//you can add pre-exit checks and other items here
System.exit(0);
}
Then you could simply call the method from inside you loop.
if (Responses[n].equals("Quit"))
{
ExitApplication();
}
The '==' operator only checks if the strings refer to the same memory location, which they do not. Try using the string.equals() method for comparing the actual string values.
if (Responses[n].equals("Quit")) {
ExitLoop = false;
}
You can use one variable for iteration, and you need to use equals for comparing string.
Try that:
public static void main(String[] args) {
final int countSentences = 10;
final String[] sentences = new String[countSentences];
final Scanner scanner = new Scanner(System.in);
for (int i = 0; i < countSentences; i++) {
System.out.println("Please enter sentence "+(i+1)+": ");
sentences[i] = scanner.nextLine();
if (sentences[i].equals("Quit")) System.exit(0);
}
System.out.println();
for (int j = 0; j < countSentences; j++)
System.out.println("Sentence "+(j+1)+" "+sentences[j]);
}
I am able to get the numbers from a String but it seems it only reads one digit of number example is if I input Test24 XXX23, it only reads 4 and 3 instead of 24 and 23, also I need help in storing all numbers that are odd/even in an array and display them later like: Odd (3 5 7), Even(2 4 6)
public class acc2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter something with numbers:");
String s = input.nextLine();
System.out.print("\n");
String digits = s.replaceAll("[^0-9.]", "");
int x = Integer.parseInt(digits);
int len = s.length();
for (int i = 0; i < len; i++) {
if (Character.isDigit(s.charAt(i))) {
System.out.print(s.charAt(i));
i++;
while (i < len && Character.isDigit(s.charAt(i))) {
System.out.print(s.charAt(i));
if (s.charAt(i) % 2 == 0) {
System.out.println("is even");
} else {
System.out.println("is odd");
}
i++;
}
System.out.print(" ");
}
}
if (x <= 100) {
if (x >= 50) {
System.out.print(x + " passed");
} else {
System.out.print(x + " failed");
}
} else {
System.out.print("Value is to high ");
}
}
}
I'm not entirely sure what the goal is, but I have a few suggestions. First, if you want to read 24 and 23 as two separate numbers instead of one (e.g., 2423 as done currently), then adjust digits to read String[] digits = s.replaceAll("[^0-9.\\s+]", "").split("\\s+"); - this will create a string array of each number group defined as being separated by one or more spaces (i.e., 24 and 23 instead of 2423). Second, you can create two Integer lists, one for even and one for odd (for general consumption, it's impossible to know the length of each array (you could always use a huge number, but that's inefficient), which is why I suggest a list). You have the right idea in terms of a %2 test for even/odd, just change the current iterators to iterate over each digit in each digit grouping:
for(int i=0; i<digits.length; i++){
for(int j=0; j<digits[i].length(); j++){
// do stuff
}
}
String inp="Test24 XXX23";
Pattern p=Pattern.compile("[0-9]+");
Matcher m=p.matcher(inp);
System.out.println(m.matches());
int i=0,j=0,k=0;
int[] even=new int[10];
int[] odd=new int[10];
while (m.find()) {
System.out.println(inp.substring(m.start(), m.end()));
i=Integer.parseInt(inp.substring(m.start(), m.end()));
if(i%2==0){
even[j]=i;j++;
}
else{
odd[k]=i;k++;
}
}
System.out.println(even[0]+" "+odd[0]);
>> Extend this program to print all odd and even numbers with for loop
the following code extracts digits and also generate the array of odd and even numbers.This is what are you looking for.
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Scanner;
import java.util.Set;
public class StackSolution {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter something with numbers:");
String s = input.nextLine();
String digits = s.replaceAll("[^0-9.]", "");
int len = digits.length();
Set<Integer>odd,even;
odd=new LinkedHashSet<Integer>();
even=new LinkedHashSet<Integer>();
for (int i = 0; i < len; i++) {
int no=Integer.parseInt(""+digits.charAt(i) );
Integer dig=new Integer(no);
if ( no%2==0) {
even.add(dig);
} else {
odd.add(dig);
}
}
int[] oddArray,evenArray;
oddArray=new int[odd.size()];
evenArray=new int[even.size()];
oddArray=toIntArray(odd);
evenArray=toIntArray(even);
System.out.print("Odd: (");
for(int no:oddArray){
System.out.print(" "+no);
}
System.out.println(" )");
System.out.print("Even: (");
for(int no:evenArray){
System.out.print(" "+no);
}
System.out.print(" )");
}
static int[] toIntArray(Set<Integer> list){
int[] ret = new int[list.size()];
Iterator<Integer> itr=list.iterator();
int i=0;
while (itr.hasNext()) {
Integer integer = (Integer) itr.next();
ret[i]=integer.intValue();
i++;
}
return ret;
}
}
I feel like I am really close to getting what I want accomplished with this class -- but the method getNumbers continues to error -- advising I need .class where i say if numbers[i].isValid(i) -- and if I change it I get "int cannot be dereferenced." Part of my assignment is showing that I can use multiple methods to accomplish something and I know I'm definitely shaky on it. Any advice on that method would be appreciated. It is trying to populate an array and verify each number is between 0 and 59 and also that each number is not a repeating number.
import java.util.*;
public class Luck //edited
{
public int numbers[];
public Luck()
{
numbers = new int[4];
}
public void greeting()
{
System.out.println("Please enter 5 numbers, each > 0 and < 59.");
}
public void getNumbers()
{
Scanner reader = new Scanner(System.in);
int count = 0;
int[] numbers = new int[4];
while(count<5)
{
System.out.println("Please enter a number > 0 and < 59");
for(int i=0; i<5; i++)
{
numbers[i] = reader.nextInt();
if((isValid(numbers[i]) || isNotRepeat(numbers[]))
{
count++;
System.out.println("Number " + count + " is " + numbers[j]);
}//end second if
else TryAnother();
//else TryAgain();
}//end for
}//end while
}//end method
public boolean isNotRepeat(int numbers[]) //edited
{
for(int i=0; i< 5; i++)
{
for(int j=0; j< 5; j++)
{
if (i == j)
return false;
else return true;
}//end for
}//end for
}
public boolean isValid (int number)
{
number = newNumber;
if (newNumber < 0 || newNumber > 59)
return false;
}
public void showNumbers(int numbers[])
{
int count = 0;
//int numbers[] = new int[4];
//int i;
for(int i=0; i < 5; i++)
{
System.out.println("Number " + count + 1 + " is " + numbers[0]);
}
}
public void goodLuck()
{
System.out.println("Good luck!");
}
}//end class
numbers is an int[] (array of int). In several places in your code, you are trying to call methods on the elements of numbers, for example here:
if(numbers[i].isValid(i))
if (numbers[j].isNotRepeat(numbers[]))
That is not going to work, because you cannot call methods such as isValid and isNotRepeat on an int. Also, the second line quoted above isn't even valid Java syntax (what do you mean when you try to pass numbers[] to a method?).
You probably meant something like this:
if(isValid(numbers[i]))
(Where's the method isNotRepeat?).
There are two visible errors in your code:
1 Your constructor Name should be same as your class name.
public Luck()
should be
public Lucky()
2 you cant invoke isValid() and isNotRepeat on an int primitive.
if you just want to check if an number is valid, just do
if(isValid(i)) or if(isNotReapeat(array))
EDIT:
change
if((isValid(numbers[i]) || isNotRepeat(numbers[]))
to
if((isValid(numbers[i]) || isNotRepeat(numbers)) // you dont need the brackets, you only need to pass the reference variable