This question already has answers here:
Why this giving me 0? [duplicate]
(7 answers)
Closed 8 years ago.
I have written a small program to improve my Java skills. I am trying to get the list of names and print the same using while loop. But the while loop which gets input is not terminating upon reaching the limit. My while condition looks okay. But I'm not sure, what is going wrong. Here is the code:
import java.io.DataInputStream;
import java.io.IOException;
public class MyTestProgram {
public static int count;
public static DataInputStream din;
public static String names[];
public static void main(String[] args) throws NumberFormatException, IOException {
din = new DataInputStream(System.in);
int counter = 0;
System.out.print("Enter the numer of persons: ");
count = Integer.parseInt(din.readLine());
names = new String[count];
System.out.println("Enter the names one by one:");
while (counter < count) {
names[counter] = din.readLine();
counter = counter++;
}
System.out.println("List of names entered:");
while (counter < count) {
System.out.println(names[counter]);
counter = counter++;
}
}
}
For starters, change the way you increament the counter variable.
Just use:
counter++;
Since counter = counter++;, Increments counter, and returns what counter was before the increment, which gets assigned to counter. Here is the explanation.
Also reset your counter variable once first loop is completed.
Related
This question already has answers here:
How to break a while loop from an if condition inside the while loop?
(3 answers)
Closed 2 years ago.
//File name: SmallIO.java
import java.util.Scanner;
public class SmallIO{
public static void main(String[] args){
Scanner keyboard = new Scanner (System.in);
String a = ""; // initialise to empty string
while (true){
//an infinite loop, use Ctrl-C (from command prompt) to quit
System.out.println("Enter a line:");
a = keyboard.nextLine();
System.out.println("Your line: " + a);
System.out.println();
}//end of while
}//end of main
}//end of class
There are multiple ways, the simplest one would be to use an actual for loop:
for (int i = 1; i <=5; i++) {....}
This is the same as:
int i = 1;
while (i <= 5) {.... i++; }
To break a loop(any loop), you use the break statement.
To break a loop after 5 iterations, you use a counter
This is one of the way to use a counter in combination with break
int counter = 0;
while(true) {
counter++;
if (counter == 5) break;
}
This question already has answers here:
Make a upside down triangle in java
(3 answers)
Closed 4 years ago.
I'm a beginner in java and I need help with this code. I have to let the user enter a word and the output as follows,(I used Canada as an example)
Canada
anada
nada
ada
da
a
However, I'm not sure what to do. This is what I have so far
import java.util.*;
public class javapdf2413_17 {
public static void main (String [] args) {
Scanner in = new Scanner (System.in);
System.out.println("Enter in a single word");
String wordEntered = in.next();
for (int i = wordEntered.length(); i>=0; i--) {
System.out.println(wordEntered.substring (0, i));
}
}
}
This should do it
for (int i = 0; i < wordEntered.length(); i++) {
System.out.println(wordEntered.substring(i));
}
The above substring method takes the beginning index of the string and returns a substring from that index (inclusive) till the end of the string.
You're close. String.substring(1) will return everything from the second character to the end. And I would use that in a loop with test against the empty string. Like,
while (!wordEntered.isEmpty()) {
System.out.println(wordEntered);
wordEntered = wordEntered.substring(1);
}
the question I've asked isn't too clear but essentially I have been tasked to:
Write a program to read in 5 integer numbers from the user. You
should store the numbers in an array.
Use loops for efficiency.
I would know how to do this if it weren't for loops, however I am unsure how to use loops for this certain task.
What I have is this (I know this is completely wrong I was just trying to base it on the example from the book).
import java.util.Arrays;
import java.util.Scanner;
public class fivenumbersloops {
public static void main(String[] args)throws Exception {
Scanner aids = new Scanner(System.in);
int[] numbers = new int[5];
do
{
System.out.println("Enter a whole number: ");
numbers[0] = aids.nextInt();
numbers[0]++;
}while (numbers[0]==numbers[5]);
}
}
I know it's the bottom bit which is completely wrong, but if someone could help point me in the right direction I would appreciate it.
What you want is a for loop. This for loop initializes the variable i to 0, continues while i is less than 5 and increments i for each iteration. The variable i is used to specify the position to place the input number into the array.
public static void main(String[] args) throws Exception {
Scanner aids = new Scanner(System.in);
int[] numbers = new int[5];
for (int i = 0; i < 5; i++) {
System.out.println("Enter a whole number: ");
numbers[i] = aids.nextInt();
}
}
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.
This question already has answers here:
Why won't this print any integers?
(5 answers)
Closed 7 years ago.
I'm very confused as to why this isn't working, would appreciate some help:
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int min = Integer.MAX_VALUE;
System.out.println("Enter a number");
int input = in.nextInt();
while(in.hasNextInt()){
if(input < min){
min=input;
}
}
in.close();
System.out.println(min);
}
}
The loop isn't ending for some reason when I enter something other than an int.
Because it's waiting for the next integer, and will keep reading forever. One solution is to use getline() and parse the returned string as an integer. If conversion fails, you'll have to handle it. If 0-length string is returned, then exit.
A solution would be to take .next() and use a try-catch to parse an int out of it:
while (in.hasNext() {
String input = in.next();
try {
int printInt = Integer.parseInt(input);
System.out.println(printInt);
} catch () {}
}
Additionally, I think you're forgetting to call in.nextInt() inside your while loop.