I need the user to enter an integer input, check whether it starts by 0 and tell the user to enter another integer if that is the case
I tried parsing the integer input to a string, that works but only once. The string cannot be edited when program loops
I think the solution should not at all involve strings because i need the program to loop and check over and over until the input is valid (ie has no leading zeroes)
Splitting each digit of the int into an array does not work also because the ways i found pass by string.
public static void main(String[] args){
Scanner key = new Scanner(System.in);
int in= 0;
boolean looper=true;
while (looper == true) {
System.out.println("Enter an integer");
in = key.nextInt();
/* check whether in has any leading zeroes, example of
wrong input: 09999, 0099*/
if (/*in has no leading zeroes*/)
looper = false;
}
key.close();
}
Maybe another answer would be to have a method that creates a brand new string every time the program loops, so maybe like a recursion that automatically creates strings, not sure if that's even a thing though.
You can make it cleaner by using a do-while loop instead of while(true). Note that an integer starting with 0 is an octal number e.g.
public class Main {
public static void main(String[] args) {
int x = 06;
System.out.println(x);
// x = 09; // Compilation error - out of range
}
}
Thus, 06 is a valid integer. For your requirement, you can input to a String variable and prompt the user to again if it starts with a zero. If the input does not start with a zero, try parsing it to an int and process it if it succeeds; otherwise, loopback e.g.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
String input = "";
int in = 0;
boolean valid = true;
do {
System.out.print("Enter an integer: ");
input = key.nextLine();
if (input.startsWith("0")) {
System.out.println("Invalid input");
valid = false;
} else {
try {
in = Integer.parseInt(input);
System.out.println("You entered " + in);
// ... process it
valid = true;
} catch (NumberFormatException e) {
System.out.println("Invalid input");
valid = false;
}
}
} while (!valid);
}
}
A sample run:
Enter an integer: 09999
Invalid input
Enter an integer: xyz
Invalid input
Enter an integer: 123
You entered 123
As an aside, never close a Scanner(System.in) because it also closes System.in and there is no way to open it without rebooting the JVM.
I am running into a problem, that everytime the do{...} while(...) loop runs the second time, the first iteration of for(...) loop does not execute the following statement
array[o] = scan1.nextLine();.
This is what i have tried so far:
import java.util.Scanner;
public class test
{
public static void main(String args[]) throws Exception
{
int columns=2;
String array[]=new String[10];
char ins_check='y';
Scanner scan1=new Scanner(System.in);
do {
System.out.println("Enter the value");
for (int o = 1; o <= columns; o++) {
System.out.println("Enter the value");
array[o] = scan1.nextLine();
}
System.out.println("record inserted");
System.out.println("Do you want to insert again?(y/n)");
ins_check= (char) System.in.read();
}while(ins_check != 'n');
}
}
While several commenters told you what to do and what not to do, they didn't answer your question about the reason why this is occuring.
the first time of for loop does not execute this statement: array[o] = scan1.nextLine();
You are mistaken - the statement is well executed, it's only that an empty line is read. And this is because after the prompt "Do you want to insert again?(y/n)" you entered a line consisting of the two characters y \n, and System.in.read() read only one byte of data (the y), leaving the newline character \n in the input stream. The subsequent scan1.nextLine() gets this \n and returns the empty line.
Here is still someone who post answer faster then me. Take a look on reply from Amali, thats right answer :) this should work fine:
import java.util.Scanner;
public class test
{
public static void main(String args[]) throws Exception
{
Scanner scan1=new Scanner(System.in);
String array[]=new String[10];
String ins_check="y";
int columns=9;
do {
for (int o = 0; o <= columns; o++) {
System.out.printf("Enter the value for array[%s]",o);
array[o] = scan1.nextLine();
}
System.out.println("record inserted");
System.out.println("Do you want to insert again?(y/n)");
ins_check= scan1.nextLine();
}while(ins_check.equals("y"));
System.out.println("end");
}
}
So in the program I ask the user whether they want to rerun the program but when it does it prints the line "Enter your name," followed by a space, twice. Can someone please help me find the cause of this? It doesn't happen when you run it the first time by the way.
import java.util.Scanner;
public class PirateName
{
static Scanner input = new Scanner(System.in);
static String[]firstNames = {"Captain", "Dirty", "Squidlips", "Bowman", "Buccaneer",
"Two toes", "Sharkbait", "Old", "Peg Leg", "Fluffbucket",
"Scallywag", "Bucko", "Deadman", "Matey", "Jolly",
"Stinky", "Bloody", "Miss", "Mad", "Red", "Lady",
"Shipwreck", "Rapscallion", "Dagger", "Landlubber", "Freebooter"};
static String[]secondNames =
{"Creeper","Jim","Storm","John","George","Money","Rat","Jack","Legs",
"Head","Cackle","Patch","Bones","Plank","Greedy","Mama","Spike","Squiffy",
"Gold","Yellow","Felony","Eddie","Bay","Thomas","Spot","Sea"};
static String[]thirdNames =
{"From-the-West","Byrd","Jackson","Sparrow","Of-the-Coast","Jones","Ned-Head",
"Bart","O'Fish","Kidd","O'Malley","Barnacle","Holystone","Hornswaggle",
"McStinky","Swashbuckler","Sea-Wolf","Beard","Chumbucket","Rivers","Morgan",
"Tuna-Breath","Three Gates","Bailey","Of-Atlantis","Of-Dark-Water"};
static String[] letters = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o",
"p","q","r","s","t","u","v","w","x","y","z"};
public static void main(String[] args) {
System.out.println("Welcome to the pirate name generator");
System.out.println("");
boolean running = true;
while(running){
nameGenerator();
}
}
public static boolean nameGenerator()
{
boolean rerun = false;
int x = 0;
System.out.println("Enter your name (first and last): ");
String userName = input.nextLine();
System.out.println("");
try{
String first = userName.substring(0,1);
for (int i=0;i <= 25 ; i++)
{
if(first.equalsIgnoreCase(letters[i]))
{
first = firstNames[i];
}
}
String last1 = userName.substring(userName.indexOf(' ')+1);
for (int i=0;i <= 25 ; i++)
{
if(last1.substring(0,1).equalsIgnoreCase(letters[i]))
{
last1 = secondNames[i];
}
}
String last2 = userName.substring(userName.length() - 1);
for (int i=0;i <= 25 ; i++)
{
if(last2.equalsIgnoreCase(letters[i]))
{
last2 = thirdNames[i];
}
}
System.out.println("Your pirate name is: ");
System.out.println("");
System.out.println(first+" "+last1+" "+last2);
System.out.println("");
System.out.println("Would you like to try again? (Type 1 for yes, 2- no)");
int a = input.nextInt();
if (a==2)
{
rerun = false;
System.out.println("Good Bye!");
return rerun;
}
else
{
rerun = true;
}
return rerun;
}
catch (Exception e){
System.out.println(" ");
}
return rerun;
}
}
I see at least three problems.
At the end of the method, when you read the value of a, you're pulling an integer from the Scanner, but you're not pulling out the newline character that follows the integer. This means that next time you call nextLine(), all you'll get is a blank line. The cure for this is to add an extra input.nextLine() immediately after input.nextInt().
You're catching exceptions and throwing them away, without even printing their stack traces. That means that if your program does encounter a problem, you'll never find out any information about the problem.
You're not using the value rerun outside the nameGenerator method. When you call it, you're checking if running is true, but running will never change, so you'll just go on calling it forever. So you probably want to change the code that calls it to this.
boolean shouldRun = true;
while (shouldRun) {
shouldRun = nameGenerator();
}
It looks like you are using the input scanner for entering both ints and strings. You should use two separate scanners, or change it so that input is brought in with .nextLine() and then changed to an integer.
The problem is you enter two characters when deciding to try again. The first is the int, the second is the character. The second character is not an integer, so it is left in the buffer. Then when you get input a second time, you are using a scanner that already has characters in the buffer. So it processes the buffer and reads the left over char as an empty line.
http://www.java-forums.org/new-java/24042-input-nextline.html
In the program given I have to make sure that if two consequtive characters are the same. I shouldn't increase the value of the variable (Count)... I have tried "break;", but that skips me out of the "for loop" which is very counter-productive. How can I skip the given part and still continue the "for loop"?
Currently my output for "Hello//world" is 3. It should be 2 (the '/' indicates a ' '(Space)).
Code
import java.util.Scanner;
class CountWordsWithEmergency
{
public static void main()
{
Scanner input = new Scanner(System.in);
System.out.println("Please input the String");
String inp = input.nextLine();
System.out.println("thank you");
int i = inp.length();
int count = 1;
for(int j=0;j<=i-1;j++) //This is the for loop I would like to stay in.
{
char check = inp.charAt(j);
if(check==' ')
{
if((inp.charAt(j+1))==check) //This is the condition to prevent increase for
//count variable.
{
count = count; //This does not work and neither does break;
}
count++;
}
}
System.out.println("The number of words are : "+count);
}
}
You can use the keyword continue in order to accomplish what you are trying to do.
However you can also inverse your conditional test and use count++ only if it is different (!= instead of == in your if) and do nothing otherwise
if ((inp.charAt(j+1)) != check) {
count++;
}
The word you are looking for is "continue".
Try this:
if ((inp.charAt(j+1)) != check) {
count++;
}
Increment the value of count by checking with !=.
Try using continue where you want to skip an block.
Use "continue;" when you want to break the current iteration.
continue is a keyword in java programming used to skip the loop or block of code and reexecutes the loop with new condition.
continue statement is used only in while,do while and for loop.
You may want to use the continue keyword, or modify the logic a little bit:
import java.util.Scanner;
class CountWordsWithEmergency
{
public static void main()
{
Scanner input = new Scanner(System.in);
System.out.println("Please input the String");
String inp = input.nextLine();
System.out.println("thank you");
int i = inp.length();
int count = 1;
for(int j=0;j<=i-1;j++) //This is the for loop I would like to stay in.
{
char check = inp.charAt(j);
if(check==' ')
{
if((inp.charAt(j+1))!=check)
{
count++;
}
}
}
System.out.println("The number of words are : "+count);
}
}
Edit:
You may want to use the split method of the String class.
int wordsCount = str.split(' ').length;
Hope it helps :)
The following should work.
import java.util.Scanner;
class CountWordsWithEmergency
{
public static void main()
{
Scanner input = new Scanner(System.in);
System.out.println("Please input the String");
String inp = input.nextLine();
System.out.println("thank you");
int i = inp.length();
int count = 1;
for(int j=0;j<=i-1;j++) //This is the for loop I would like to stay in.
{
char check = inp.charAt(j);
if(check==' ')
{
if((inp.charAt(j+1))==check) //This is the condition to prevent increase for
//count variable.
{
continue;
}
count++;
}
}
System.out.println("The number of words are : "+count);
}
}
I need help with looping my code in Java. So far I have:
import java.util.Scanner;
public class chara{
public static void main(String[]args){
int count = 0;
Scanner input = new Scanner(System.in);
System.out.println("Input a string");
String user=input.nextLine();
if(user.length()<7)
{
return;
}
else
{
}
System.out.println("Now input a letter to be replaced");
String letter = input.next();
if(letter.length()!=1)
{
return;
}
else
{
}
String user2 = user.replace(letter, "-");
String user3 = user.replace(letter, "");
count += (user.length() - user3.length());
System.out.println(user2);
System.out.println(user3);
System.out.println("#"+letter+"'s: "+count);
}
}
The code does everything I want it to except that when the string condition is not met (user<7, letter!=1) the program terminates and what I need it to do is ask the question again. Does anyone know how I can achieve this?
You need to put your looping code in method that can be called, then when the conidtion is not met you can go back to your question, and depending on that condidtion, quit the program, or call the loop method.
You just need a loop with a break condition, this should do it for you:
Scanner input = new Scanner(System.in);
System.out.println("Input a string");
String user=input.nextLine();
while (true)
{
if(user.length() <7 ) {break;}
input = new Scanner(System.in);
System.out.println("Too long, input a string < 7");
user=input.nextLine();
}
if(user.length()<7)......
A simple way would be to wrap your main logic within a loop with a boolean condition. This condition stays true when there is an "error" in the input. The condition is then false when the user proceeds as wanted.
Your code would look as so :
import java.util.Scanner;
public class Tester{
public static void main(String[]args){
int count = 0;
boolean keepGoing = true;
Scanner input = new Scanner(System.in);
while(keepGoing) {
System.out.println("Input a string");
String user=input.nextLine();
if(user.length()<7)
{
keepGoing = true;
//enter an error message here
}
else
{
System.out.println("Now input a letter to be replaced");
String letter = input.next();
if(letter.length()!=1)
{
keepGoing = true;
//enter an error message here
}
else
{
String user2 = user.replace(letter, "-");
String user3 = user.replace(letter, "");
count += (user.length() - user3.length());
System.out.println(user2);
System.out.println(user3);
System.out.println("#"+letter+"'s: "+count);
keepGoing = false;
}
}
}
input.close(); //Close resources
}
}
Unrelated
The convention is that class names start with a capital letter. In your case your class should be Chara, not chara.
Also, when opening resources make sure you close them. This is to avoid having resources leaked. Some IDEs will tell you something like this Resource leak: 'input' is never closed. It's a good idea to use a good IDE to help you with potential problems like this one.