Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I want to get this output via loops. However user needs to define the value when it runs. So, when the user inputs 6, the result should be this(notice 6 rows are created! with incrementing spaces between the characters):
##
# #
# #
# #
# #
# #
I have wrote the code so far and am really confused as to how to add spaces.. The code so far looks like this :
import java.util.*;
public class Pattern
{
public static void main(String[] args)
{
int input;
Scanner kb = new Scanner(System.in);
System.out.print("Enter a positive number: ");
input = kb.nextInt();
while (input <= 0)
{
System.out.print("That isn't positive, try again: ");
input= kb.nextInt();
}
for (int number = 0; number < input; number++)
{
System.out.print("#");
The thing you want is to print a number of spaces that is equivalent to the current line number - 1. So you'll have to create a for loop for that.
import java.util.*;
public class Pattern
{
public static void main(String[] args)
{
int input;
Scanner kb = new Scanner(System.in);
System.out.print("Enter a positive number: ");
input = kb.nextInt();
while (input <= 0)
{
System.out.print("That isn't positive, try again: ");
input= kb.nextInt();
}
for (int number = 0; number < input; number++)
{
System.out.print("#");
//print spaces equal to the number variable
for(int count = 0; count < number; count++)
{
System.out.print(" ");
}
System.out.println("#");
}
}
}
I just leave this here, in case you want a JDK 1.8 solution too :)
int lineCount = // read from console
String result = IntStream.range(0, lineCount)
.mapToObj(i ->
Stream.generate(() -> " ")
.limit(i)
.collect(Collectors.joining())
)
.map(s -> "#" + s + "#")
.collect(Collectors.joining("\n"));
System.out.println(result);
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I want to print out a sequence of numbers using this formula
Enter a number
if number is even divide number by 2.
But if number is odd multiply number by 3 and add 1
continue doing this until number becomes 1
sample input=3
Sample output=10 5 16 8 4 2
this is what I tried but still not getting it
package victor;
import java.util.Scanner;
public class proj {
public static void main(String[] args) {
Scanner put=new Scanner(System.in);
int temp=0;
boolean notOne=true;
System.out.println("input::: ");
int num=put.nextInt();
while(temp!=1){
if (num%2==0){
temp=num;
System.out.println(temp/2);
break ;
}
else {
temp=num;
System.out.println(temp*3+1);
break;
}
}
if(temp!=1){
notOne=false;
}
}
}
It's not working because you keep re-assigining the variable temp to the initially scanned num.
You keep checking if the initially scanned num is odd or even, when you should check if temp is odd or even.
You also break out of the loop for no reason.
And finally, you're not saving the result of the operations, you're only printing out the result.
Try to understand the points I mentioned above by noticing the differences between your code and the following:
while(temp!=1){
if (temp%2==0){
temp = temp/2;
}
else {
temp = temp*3+1;
}
System.out.println(temp);
}
You are not updating the value of temp. You are just printing it. Take the following statement
if (num%2==0){
temp=num;
System.out.println(temp/2);
break ;
}
Here you are setting temp to num and just printing temp/2 and never setting a value.
I wrote my version of it which is a bit more simpler. I hope this will help you. You can create a string to get a better output of course.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a number:");
int number = scan.nextInt();
while (number != 1) {
number = number % 2 == 0 ? number / 2 : ((number * 3) + 1);
System.out.println("Number became " + number);
}
}
}
Try this:
public class Main
{
public static void main(String[] args) throws Exception
{
System.out.println("Starting...");
//Lets start the program, first we need
//the Scanner class to access to the input
Scanner stdin = new Scanner(System.in);
System.out.print("Type a num: ");
//I dont use: nextInt() because when asking for another input, will scan only
//the rest of the line (Maybe just \n - line break )
int num = Integer.parseInt(stdin.nextLine());
//Optional
int loops = 0;
while(num!=1){
//Pair, so num/2
if ( num %2 == 0){
num/=2;
}
else{
//num*3 +1
num=num*3 +1;
//Note that:
//1 + num*3
//Doesnt alter the result
}
System.out.println("num: "+num);
loops++;
}
System.out.println("total loops: "+loops);
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
package com.jetbrains;
import java.util.Objects;
import java.util.Scanner;
public class SA {
public static void main(String[] args) {
//scanner object
Scanner input = new Scanner(System.in);
//comment
System.out.println("Please enter a line of text below:");
String letters = input.nextLine(); //User's string input
if (letters.length() < 7) {
System.out.println("The input is too short.");
}
//variables
int l = letters.length()-5; //where the last 5 characters are located in user's input string
String answer = letters.substring(l) + letters.substring(2,l) + letters.substring(0, 2); // first 2 & last 5 swapped
if (letters.length() > 7) {
System.out.println("Convert to upper cases:");
System.out.println(letters.toUpperCase());
System.out.println("Swap the first 2 characters with the last 5 characters:"); // Swap
System.out.println(answer);
System.out.println("Is it a palindrome?");
for (int i = (letters.length() - 1); i >= 0; i--) {
char backwards = (letters.charAt(i));
for (int n = letters.indexOf(0); n >= 0; n++) {
char forwards = (letters.charAt(n));
if (Objects.equals(forwards, backwards)) {
System.out.println("True");
else
System.out.println("False");
}
}
}
}
}
}
I've tried comparing my user's input by making the for-loop outputs into char variables but it always returns false. I'm not sure how to fix this last bit, I've tried doing other things but I am completely stumped. My class hasn't learned StringBuilder or StringBuffer so I cannot use them in my code. Any tips or hints would be very helpful, thank you.
I have modified your code little bit to get the correct result -
import java.util.Scanner;
public class StringAnalysis {
public static void main(String[] args) {
//Create scanner object
Scanner input = new Scanner(System.in);
//Comment to the user
System.out.println("Please enter a line of text below:");
String letters = input.nextLine(); //User's string input
if (letters.length() < 7) {
System.out.println("The input is too short. No analysis to be performed.");
}
//variables
int l = letters.length() - 5; //States the index number of where the last 5 characters are located in user's input string
String answer = letters.substring(l) + letters.substring(2, l) + letters.substring(0, 2); // first 2 & last 5 swapped
if (letters.length() > 7) {
System.out.println("Analysis #1: Convert to upper cases:"); // Upper case
System.out.println(letters.toUpperCase());
System.out.println("Analysis #2: Swap the first 2 characters with the last 5 characters:"); // Swapping
System.out.println(answer);
System.out.println("Analysis #3: Is it a palindrome?");
String backwards = "";
for (int i = (letters.length() - 1); i >= 0; i--) {
backwards = backwards + letters.charAt(i);
}
if(letters.equalsIgnoreCase(backwards)) {
System.out.println("True");
} else {
System.out.println("False");
}
}
}
}
You have a problem on the second loop for checking palindrome , i tried to solve it , but eventhough , it compares every backward letters to all forwards which is logically wrong , here is something better you can do :
System.out.println("Analysis #3: Is it a palindrome?");
boolean response = true;
for (int i = 0 ; i < letters.length() ; i++) {
String backwards = String.valueOf(letters.charAt(i));
String forwards = String.valueOf(letters.charAt(letters.length()-i-1));
if(!backwards.equals(forwards)) {
response = false;
}
}
System.out.println(response);
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I would very much appreciate your help.
The prompt: Write a program that reads from the console a sequence of n integer numbers and returns these numbers on a single line with the correct sign (<, > or =) between the numbers.
I have no idea how to construct the answer.
Thanks in advance:
desperate novice
If this is your homework question, these are the hints:
To read from console, you can use these options:
System.console.readLine()
System.in.read()
Scanner class - Scanner myScanner = new Scanner(System.in); then myScanner.nextLine()
You can split the inputs via String.split(",") if they are seperated by commas
You can convert the splitted input strings into Integer by Integer.parseInt(<strings from last step>) by iterating over them
Then you can take any 2-2 input and compare them and add to string with correct sign via concatenating.
Then you can output them into console.
imports:
import java.util.Arrays;
import java.util.Scanner;
Logic:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = Integer.parseInt(scanner.nextLine()); // No. of input to read
int[] inputs = new int[n];
for (int i = 0; i < n; i++) {
inputs[i] = Integer.parseInt(scanner.nextLine()); // inputs
}
// Arrays.sort(inputs) if you want the output to be sorted
for (int i = 0; i < n; i++) {
System.out.print(inputs[i]);
if (i == n - 1) continue;
String sign;
if (inputs[i] > inputs[i + 1]) {
sign = " > ";
} else if (inputs[i] < inputs[i + 1]) {
sign = " < ";
} else {
sign = " = ";
}
System.out.print(sign);
}
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
My task is to make an array of size 20. Ask the user how many numbers he/she wants to enter. Put all those numbers in an array, then output that array in reverse. I've gotten it completed up to the "output that array in reverse" part.
import java.util.Scanner;
public class Activity7 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System. in );
System.out.println("How many numbers?");
int quantityOfNumbers = keyboard.nextInt();
int[] numbers = new int[20]; //making an array the size of 20
//0 - 19 (Valid values of the array)
for (int subscript = 0; subscript < quantityOfNumbers; subscript++) {
System.out.println("Enter number " + subscript);
numbers[subscript] = keyboard.nextInt();
}
System.out.println("Array Contents");
for (int subscript = 19; subscript >= 0; subscript--) {
}
}
}
If you want to print the array with out the empty elements, you can use something like this. As 0 is the default int value, print it as long as it is not 0.
public static void reverse(int[] array)
{
for(int i=array.length-1;i>=0;i--)
{
if(array[i]!=0)
{
System.out.println(array[i]);
}
}
}
I'm not completely sure what you are looking for. Could you specify a bit more? I'm completing your code to match the provided output anyway:
import java.util.Scanner;
public class Activity7
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("How many numbers?");
int quantityOfNumbers = keyboard.nextInt();
int[] numbers = new int[20]; //making an array the size of 20
//0 - 19 (Valid values of the array)
for (int subscript = 0; subscript < quantityOfNumbers; subscript++)
{
System.out.println("Enter number " + subscript);
numbers[subscript] = keyboard.nextInt();
}
System.out.println("Array Contents");
for (int subscript = 19; subscript >= 0; subscript--)
{
if (subscript >= quantityOfNumbers) System.out.println("Subscript " + subscript + "is empty");
else System.out.println("Subscript " + subscript + "contains " + numbers[subscript]);
}
}
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
public class decisionMaker {
public static void main(String args[]) {
String option[] = new String[10];
// Output
for (int i = 0; i <= 9; i++) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the next option:");
option[i] = input.next();
System.out.println(" ");
}
for (int i = 0; i <= 9; i++) {
System.out.println("option: ");
System.out.println("option[i]+" ");
}
// Output
}
I'm trying to figure out how to add a count to the options, exit and end the program after entering a certain letter or number, and how to create a random output from the user input. I want it to give me one option that I had input at random. Can anyone help me with one or a few of these things. I'm trying to learn to code on my own, and I'm stuck on these.
Randomness
You can generate random numbers using java.util.Random;:
import java.util.Random;
public class SomeClass{
static Random rand = new Random();
public static void main(String args[]){
System.out.println(rand.nextInt());
}
}
About some broken code:
If you want to print out the value of a variable with System.out.println() then you need only type the variable without any quotation marks. The code you've written below will not compile:
System.out.println("option: ");
System.out.println("option[i]+" ");
Assuming that's what you want to do, it should instead be written as:
System.out.println("option: ");
System.out.println(option[i]);
Or even System.out.println("option: \n"+option[i]);
(The escape sequence \n when placed inside of quotation marks just indicates to the console to add a new line.)
Scanner:
Additionally, as nick zoum pointed out, your Scanner object should be initialized outside of the for loop, such as right underneath of the main() method.
Please comment below if you need clarification or if I misunderstood what you were looking for. It was very hard to understand your question.
You could try something like this:
public class DecisionMaker {
public static void main(String[] args) {
// output
Scanner scanner = new Scanner(System.in);
int size = getInt(scanner);
String option[] = new String[size];
for (int index = 0; index < size; index++) {
System.out.print("Enter the next option:");
option[index] = scanner.next();
}
int index = (int) (Math.random() * size);
System.out.println(option[index]);
scanner.close();
// output
}
public static int getInt(Scanner scanner) {
int size = 0;
while (size <= 0) {
if (scanner.hasNext()) {
if (scanner.hasNextInt()) {
size = scanner.nextInt();
}
}
if (size <= 0) {
System.out.println("The input: " + scanner.next() + " is not a valid value.");
}
}
return size;
}
}
How the program works:
The Scanner is initialized in the beginning and there is only
one instance of it.
Then the program will wait until the user inserts a valid number for
the size of options.
The next 5 lines were essentially copied from your code.
Finally we get a random Integer in the range of 0 - (size - 1) and print
the String of the array with that index.