Output contents of array in reverse in Java [closed] - java

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]);
}
}
}

Related

How to determine if user's input string is read the same backwards ( palindrome ) JAVA [closed]

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);

Creating a random output from an user input array [closed]

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.

Add spaces to string with loop [closed]

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);

Creating if statement for the small program [closed]

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 8 years ago.
Improve this question
I am currently struggling with my first java program.
The question's task was to create a program that prompts the user to enter 5 numbers and store them in an array. Then the array should be printed, after that's done the program prompts the user to enter a number to search. Depending on the number the program should print "(display number) is on the list" or "(display number) is not on the list"
I have been struggling with this for quite a while now not fully understanding the conditional task.
Here is what my code looks like:
public class NewClass {
public static void main(String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in);
// Enter three numbers
System.out.print("Enter five numbers: ");
int number1 = input.nextInt();
int number2 = input.nextInt();
int number3 = input.nextInt();
int number4 = input.nextInt();
int number5 = input.nextInt();
System.out.println("The sorted numbers are "
+ number1 + ", " + number2 + ", " + number3 + ", " + number4 + ", " + number5);
System.out.println("Enter a number to search: ");
}
I added comments to document what the code was doing. This should hopefully help you grasp the concept.
public class NewClass {
public static void main(String[] args) {
Scanner input = new Scanner(System. in );
//Create an array of integers to store user input
int[] userNumbers = new int[5];
System.out.print("Enter " userNumbers.length + " numbers: ");
//Goes into a loop, and sets each array index to the user inputted integer
for (int i = 0; i < userNumbers.length; i++) {
userNumbers[i] = input.nextInt();
}
System.out.println("Enter a number you would like to search for");
boolean exists = false;
int numToSearch = input.nextInt();
//for each number in the user numbers array, check to see if that number matches the number to search. If so, set exists = true and break out of the loop to check no further.
for (int num: userNumbers) {
if (numToSearch == num) {
exists = true;
break;
}
}
//if else to decide which output to show the user.
if (exists) {
System.out.println(numToSearch + " is in the list");
} else {
System.out.println(numToSearch + " is not in the list");
}
}
}
At first instead of storing your numbers in single variables, you store them in an array.
The next thing you'll do is use
boolean tmp = false;
int search = input.nextInt();
This will give you the number the user is searching for.
When you have it (the program will wait at the instruction until there's input), you loop over your array and in each iteration you compare it to the given number. You do this by using
if (array[i] == search) {
tmp = true}
With i being your iteration variable.
After the end of the for loop, you'll do another if where you, depending on the state of the tmp variable either print that the number exists or it doesn't.
Sorry for short explanation.
Try following....
public class NewClass {
public static void main(String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in);
List<Integer> integers = new ArrayList<Integer>();
// Enter three numbers
System.out.print("Enter five numbers: ");
int number1 = input.nextInt();
int number2 = input.nextInt();
int number3 = input.nextInt();
int number4 = input.nextInt();
int number5 = input.nextInt();
integers.add(number1);
integers.add(number2);
integers.add(number3);
integers.add(number4);
integers.add(number5);
System.out.println("The sorted numbers are "
+integers);
System.out.println("Enter a number to search: ");
int searchNum = input.nextInt();
if(integers.contains(seacrchNum)){
System.out.println(searchNum+" is on the list");
}else{
System.out.println(searchNum+" is not on the list");
}
}
Explainations :
Placed all the entered numbers into an arrayLists and then prompt for the search Number to be entered. and Check wheather the search number is der in the ArrayLists or not. Based on the condition display the Message

Why doesn't the following program work? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I can't figure out why the following program doesn't work. Please help me where did I make a mistake. Thank you.
import java.util.Scanner;
public class LargestNumber {
public static void main(String[] args) {
int[] numbers = new int[100];
int largestNumber = 0;
System.out.println("Enter numbers. When you want to finish, type 'finish'.");
Scanner sc = new Scanner(System.in);
do {
if (sc.hasNextInt()) {
for (int counter = 0; counter < 10; counter++)
numbers[counter] = sc.nextInt();
}
if (!sc.hasNextInt() && !sc.hasNext("finish")) {
System.out.println("It's neither number nor 'finish'.");
}
}
while (!sc.hasNext("finish"));
for (int x : numbers) {
if (x > largestNumber) {
largestNumber = x;
}
}
System.out.println("The largest number is: " + largestNumber);
}
}
This part:
do {
if (sc.hasNextInt()) {
for (int counter = 0; counter < 10; counter++)
numbers[counter] = sc.nextInt();
}
if (!sc.hasNextInt() && !sc.hasNext("finish")) {
System.out.println("It's neither number nor 'finish'.");
}
}
while (!sc.hasNext("finish"));
makes no sense. You:
test if the next thing in the input is an integer;
attempt to parse ten next tokens, assuming that they are all integers;
at the eleventh token you check whether it's another integer or "finish";
throw an exception if it's neither;
repeat everything if it's not "finish".
What you should actually do is something much, much simpler:
check next token:
if it's "finish", you're done;
if it's an integer, parse it;
otherwise throw error;
repeat this for up to 100 times;
you are done accepting input. Proceed to processing it.
I think that Scanner is unnessecarily complicated and doesn't work to much of the time. Here's how to do it the old fashioned way:
public class LargestNumber {
public static void main(String[] args) {
int largestNumber=0;
System.out.println("Enter numbers. When you want to finish, type 'finish'.");
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
String line;
while (!(line = r.readLine()).equals("finish")) {
int val = Integer.parseInt(line);
if (val > largestNumber)
largestNumber = val;
}
System.out.println("The largest number is: " + largestNumber);
}
}
For this, enter each number on a new line. I used a shorter algorithm here, which is to read one number, and if it is bigger than the maximum so far, the new number is the maximum so far
According to the doc:
Throws:
InputMismatchException - if the next token does not match the Integer regular expression, or is out of range
So i thing you could do this instead:
int counter = 0;
while (counter < numbers.length) {
if (sc.hasNextInt()) {
numbers[counter++] = sc.nextInt();
} else {
if (sc.hasNext("finish")) {
sc.close();
break;
} else {
System.out.println("It's neither number nor 'finish'.");
sc.next();
}
}
}
for (int x : numbers) {
if (x > largestNumber) {
largestNumber = x;
}
}
System.out.println("The largest number is: " + largestNumber);
hope that helps

Categories