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.
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 3 years ago.
Improve this question
I was going through a Palindrome( Specifically String Palindrome) Problem and was checking whether the string is palindrome or not. But a problem struck in the program
public static void main(String args[])
{
Scanner sc= new Scanner(System.in);
int n,flag=0;
n=sc.nextInt();
char a[]=new char[n];
int l=0;
int h=n-1;
while(l<h)
{
if(a[l++]!=a[h--])
{
flag=1;
}
}
if(flag==1)
{
System.out.println("String is not Palindrome");
}
else{
System.out.println("String is Palindrome");
}
}
So above is the code which I wrote but the problem is, I have created a character array instead of the string.
The main point of the argument is the above code correct in terms of code standards.
is the above code correct in terms of code standards
Not really:
Don't name a local variable l (lowercase L). It is too easy to confuse with 1 (one).
Since I don't know what h is supposed to be a shorthand for, I changed l and h to i and j below, as those are very common integer iterator variable names.
Don't declare a local variable before it's needed. Use int n = sc.nextInt();
Don't put array declaration on the variable name. Put it on the type, since it defines the type.
Don't use 0 / 1 for false / true values. Change flag to a boolean, and name it better, e.g. describe its value. notPalindrome seems appropriate here. It helps document the code.
The while loop should be a for loop. It helps keeping loop logic together, and isolated from other logic, and it helps limit the scope of the loop variable(s).
Those were my comments related to coding standards.
However, your code doesn't work, because you never get a string from the user. Your choice of using char[] is fine, but you need to change the logic for getting it. See code below for how to use toCharArray() to do that.
Also, once a difference is found, you should exit the loop, either by also checking the boolean variable in the loop condition, or by using break. Personally, I prefer break.
Scanner sc = new Scanner(System.in);
String sentence = sc.nextLine();
char[] a = sentence.toCharArray();
boolean notPalindrome = false;
for (int i = 0, j = a.length - 1; i < j; i++, j--) {
if (a[i] != a[j]) {
notPalindrome = true;
break;
}
}
if (notPalindrome) {
System.out.println("String is not Palindrome");
} else {
System.out.println("String is Palindrome");
}
please use below code to check given String/number Palindrome or Not
public static void main(String args[]) {
String original, reverse = "";
Scanner in = new Scanner(System.in);
System.out.println("Enter String ");
original = in.nextLine();
int n = original.length();
for ( int index = n - 1; index >= 0; index-- ) {
reverse = reverse + original.charAt(index);
}
if (original.equals(reverse)) {
System.out.println("String is Palindrome");
} else {
System.out.println("String is not Palindrome");
}
}
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 is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I have this code bellow which is supposed to take a user input and store it in an array, and I was just wondering why it is not allowing me to input any numbers.
Should the input part be inside the if statement? Also what is the best way to make it work properly?
import java.util.*;
public class fun_with_loops {
static Scanner scan = new Scanner(System.in);
public static void main (String[] args) throws java.io.IOException
{
int[] numbers = new int[10];
int numberSize = 0;
System.out.print("Enter a few numbers please\n");
while (numbers.length < 10)
{
int input = scan.nextInt();
if (input != 0)
{
numbers[numberSize] = input;
numberSize++;
}
else
{
break;
}
}
}
}
Problem
The following expression on loop's control is always evaluated as false:
while (numbers.length < 10)
since array's length is in fact equals 10 as when declared.
Solution
In order to program work as expected you have to use numberSize variable as control:
while (numberSize < 10)
since it grows based on number of inputs.
As Am_I_Helpful stated, you are using a while loop on a value that will not change. I am not sure if the use while is needed in this case. Since you want to loop a specific amount of times you might want to use a for loop. If the amount of times will depend on the size of your array, you could still replace the "10" by your array length (numbers.length).
for (int i; i< 10; i++)
{
int input = scan.nextInt();
if (input != 0)
{
numbers[numberSize] = input;
numberSize++;
}
else
{
break;
}
}
Hoping it helped!
Dan
a short and sweet summary of when to use each loop:
http://mathbits.com/MathBits/CompSci/looping/whichloop.htm
but of course it always depends of your goal while coding so it's sometimes hard to say which is best if you are not the one coding.
Because the array is initialized to size 10, the length will always be 10. A counter variable needs to be used. Here is the code:
static Scanner scan = new Scanner(System.in);
public static void main (String[] args) throws java.io.IOException
{
int[] numbers = new int[10];
System.out.print("Enter a few numbers please\n");
int count = 0;
while (count < 10)
{
int input = scan.nextInt();
if (input != 0)
{
numbers[count] = input;
count++;
}
else
{
break;
}
}
The length property returns the size of the array, not the number of elements that are present in the array. You need to keep track of number of elements in the array on your own.
for(int eleCount = 0; eleCount < 10; eleCount++)
{
int input = scan.nextInt();
if (input != 0)
{
numbers[eleCount] = input;
}
else
{
break;
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm trying to get the user's input, then store the input into an array. I'm going to get a string input and with this code, I thought it would work, but it's not working. Any help would be appreciated!
import java.util.Scanner;
public class NameSorting {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String[] array = new String[20];
System.out.println("Please enter 20 names to sort");
Scanner s1 = new Scanner(System.in);
for (int i = 0; i < 0;){
array[i] = s1.nextLine();
}
//Just to test
System.out.println(array[0]);
}
}
Since you know that you want to have an array of 20 string:
String[] array = new String[20];
Then your for loop should use the length of the array to determine when the loop should stop. Also you loop is missing an incrementer.
Try the following code to get you going:
public static void main(String[] args) throws Exception {
Scanner s = new Scanner(System.in);
String[] array = new String[20];
System.out.println("Please enter 20 names to sort");
for (int i = 0; i < array.length; i++) {
array[i] = s.nextLine();
}
//Just to test
System.out.println(array[0]);
}
Look at your for-loop, it lacks of increment attribute. Example: for(int i = 0; i < 0; i++)
If you want to debug each loop I recommend you to print assignment inside for-loop
for (int i = 0; i < 0;)
{
array[i] = s.nextLine();
System.out.println(array[i]); // Debug
}
for (int i = 0; i < 0;){
array[i] = s.nextLine();
}
For the first iteration i will be initialised to '0' and since i should be less then '0' as per your condition it wont even go into the loop.change the loop to
for(int i=0;i<20;i++){
array[i]=s.nextLine();
}