Scanner only reading first set of input - java

This is a code I have developed to separate inputs by the block (when a space is reached):
import java.util.Scanner;
public class Single {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.println("Three Numbers:");
String numbers = in.next();
int length = numbers.length();
System.out.println(length);
int sub = length - length;
System.out.println(sub);
System.out.println(getNumber(numbers, length, sub));
System.out.println(getNumber(numbers, length, sub));
System.out.println(getNumber(numbers, length, sub));
}
public static double getNumber(String numbers, int length, int sub){
boolean gotNumber = false;
String currentString = null;
while (gotNumber == false){
if (numbers.substring(sub, sub + 1) == " "){
sub = sub + 1;
gotNumber = true;
} else {
currentString = currentString + numbers.substring(sub, sub);
sub = sub + 1;
}
}
return Double.parseDouble(currentString);
}
}
However, it only reads the first set for the string, and ignores the rest.
How can I fix this?

The problem is here. You should replace this line
String numbers = in.next();
with this line
String numbers = in.nextLine();
because, next() can read the input only till the first space while nextLine() can read input till the newline character. For more info check this link.

If I understand the question correctly, you are only calling in.next() once. If you want to have it process the input over and over again you want a loop until you don't have any more input.
while (in.hasNext()) {
//do number processing in here
}
Hope this helps!

Related

Palindrome Checker with nested loops thats checks the input and then flips its to compare

Im stuck on this, I need a code that use 2 nested loops for this assignment (there are other solutions, but I need to demonstrate my understanding of nested loops). But I just dont get it. The outer loop repeats the entire algorithm and the inner loop iterates half-way (or less) through the string. I am not sure on what I need to put inside the for loops. This is what I have so far. Any Assistance would be pleasured.
import java.util.Scanner;
public class pali
{
public static void main(String[] args)
{
String line;
Scanner input = new Scanner(System.in);
System.out.println("Enter a String to check if it's a Palindrome");
line = input.nextLine();
String x = 0;
String y = input.length-1;
for (String i = 0; i < line.length-1; i ++){
for (String j = 0; j < line.length-1; j ++){
if (input.charAt(x) == input.charAt(y))
{
x++;
y--;
}
}
}
}
Example Output:
Enter a string: 1331
1331 is a palindrome.
Enter a string: racecar
racecar is a palindrome.
Enter a string: blue
blue is NOT a palindrome.
Enter a string:
Empty line read - Goodbye!
Your algorithm is flawed, your nested loop should be to prompt for input - not to check if the input is a palindrome (that requires one loop itself). Also, x and y appear to be used as int(s) - but you've declared them as String (and you don't actually need them). First, a palindrome check should compare characters offset from the index at the beginning and end of an input up to half way (since the offsets then cross). Next, an infinite loop is easy to read, and easy to terminate given empty input. Something like,
Scanner input = new Scanner(System.in);
while (true) {
System.out.print("Enter a string: ");
System.out.flush();
String line = input.nextLine();
if (line.isEmpty()) {
break;
}
boolean isPalindrome = true;
for (int i = 0; i * 2 < line.length(); i++) {
if (line.charAt(i) != line.charAt(line.length() - i - 1)) {
isPalindrome = false;
break;
}
}
if (isPalindrome) {
System.out.printf("%s is a palindrome.%n", line);
} else {
System.out.printf("%s is NOT a palindrome.%n", line);
}
}
System.out.println("Empty line read - Goodbye!");
import java.util.Scanner;
public class pali
{
public static void main(String[] args)
{
String line;
Scanner input = new Scanner(System.in);
System.out.println("Enter a String to check if it's a Palindrome");
line = input.nextLine();
String reversedText ="";
for(int i=line.length()-1/* takes index into account */;i>=0;i++) {
reversedText+=line.split("")[i]; //adds the character to reversedText
}
if(reversedText ==line){
//is a palidrome
}
}
Your code had lot of errors. I have corrected them and used a while loop to check if its a palindrome or not. Please refer below code,
import java.util.Scanner;
public class Post {
public static void main(String[] args) {
String line;
boolean isPalindrome = true;
Scanner input = new Scanner(System.in);
while (true) {
System.out.println("Enter a String to check if it's a Palindrome");
line = input.nextLine();
int x = 0;
int y = line.length() - 1;
while (y > x) {
if (line.charAt(x++) != line.charAt(y--)) {
isPalindrome = false;
break;
}
}
if (isPalindrome) {
System.out.println(line + " is a palindrome");
} else {
System.out.println(line + "is NOT a palindrome");
}
System.out.println();
}
}
}

Java Scanner delimiter and System.in

I have some problem when I ask the user to input some numbers and then I want to process them. Look at the code below please.
To make this program works properly I need to input two commas at the end and then it's ok. If I dont put 2 commas at the and then program doesnt want to finish or I get an error.
Can anyone help me with this? What should I do not to input those commas at the end
package com.kurs;
import java.util.Scanner;
public class NumberFromUser {
public static void main(String[] args) {
String gd = "4,5, 6, 85";
Scanner s = new Scanner(System.in).useDelimiter(", *");
System.out.println("Input some numbers");
System.out.println("delimiter to; " + s.delimiter());
int sum = 0;
while (s.hasNextInt()) {
int d = s.nextInt();
sum = sum + d;
}
System.out.println(sum);
s.close();
System.exit(0);
}
}
Your program hangs in s.hasNextInt().
From the documentation of Scanner class:
The next() and hasNext() methods and their primitive-type companion
methods (such as nextInt() and hasNextInt()) first skip any input that
matches the delimiter pattern, and then attempt to return the next
token. Both hasNext and next methods may block waiting for further
input.
In a few words, scanner is simply waiting for more input after the last integer, cause it needs to find your delimiter in the form of the regular expression ", *" to decide that the last integer is fully typed.
You can read more about your problem in this discussion:
Link to the discussion on stackoverflow
To solve such problem, you may change your program to read the whole input string and then split it with String.split() method. Try to use something like this:
import java.util.Scanner;
public class NumberFromUser {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] tokens = sc.nextLine().split(", *");
int sum = 0;
for (String token : tokens) {
sum += Integer.valueOf(token);
}
System.out.println(sum);
}
}
Try allowing end of line to be a delimiter too:
Scanner s = new Scanner(System.in).useDelimiter(", *|[\r\n]+");
I changed your solution a bit and probably mine isn't the best one, but it seems to work:
Scanner s = new Scanner(System.in);
System.out.println("Input some numbers");
int sum = 0;
if (s.hasNextLine()) {
// Remove all blank spaces
final String line = s.nextLine().replaceAll("\\s","");
// split into a list
final List<String> listNumbers = Arrays.asList(line.split(","));
for (String str : listNumbers) {
if (str != null && !str.equals("")) {
final Integer number = Integer.parseInt(str);
sum = sum + number;
}
}
}
System.out.println(sum);
look you can do some thing like this mmm.
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Input some numbers");
System.out.println("When did you to finish and get the total sum enter ,, and go");
boolean flag = true;
int sum = 0;
while (s.hasNextInt() && flag) {
int d = s.nextInt();
sum = sum + d;
}
System.out.println(sum);
}

how to add an additional method to get word count and first word of a string

I'm still fairly new to Java and understanding the basics of everything, we just started talking about methods.
I'm having a hard time implementing this new method.. without using arrays or vectors or anything in the sort..
Any help would be greatly appreciated!
public class ClosedLab07{
public static void main(String[] args) {
Scanner keyboard = new Scanner (System.in);
String str = getInputString(keyboard);
int count = getWordCount(str);
System.out.println("Your string has " + (count+1) + " words in it.");
// Fill in the body with your code
}
// Given a Scanner, prompt the user for a String. If the user enters an empty
// String, report an error message and ask for a non-empty String. Return the
// String to the calling program.
private static String getInputString(Scanner inScanner) {
String str = "";
while (str.equals("")){
System.out.print("Enter a string: ");
str = inScanner.nextLine();
if (str.equals("")){
System.out.println("ERROR - string must not be empty.");
System.out.println();
}
}
return str;
// Fill in the body
// NOTE: Do not declare a Scanner in the body of this method.
}
// Given a String return the number of words in the String. A word is a sequence of
// characters with no spaces. Write this method so that the function call:
// int count = getWordCount("The quick brown fox jumped");
// results in count having a value of 5. You will call this method from the main method.
// For this assignment you may assume that
// words will be separated by exactly one space.
private static int getWordCount(String input) {
int i = 0;
int wordCount = 0;
while (i < input.length()){
char pos = input.charAt(i);
if (pos == ' '){
wordCount++;
}
i++;
}
return wordCount;
// Fill in the body
}
private static String getFirstWord(String input)
// THIS IS THE METHOD I'M WORKING ON
}
Add this line to your new method
return input.split("\\s")[0]; // split returns an array of all the words. you need just the first word

How do you check if a string is a palindrome in java?

I am trying to write a program that checks if a string is a palindrome and so far I know I am on the right path but when I enter my code it keeps on running for ever. I don't know what the problem is and would like help finding out the solution. In my program I want the user to enter word or words in the method Printpalindrome and then the program should know if the string is a palindrome or not.
Here is my code:
...
Scanner console = new Scanner (System.in);
String str = console.next();
Printpalindrome(console, str);
}
public static void Printpalindrome(Scanner console, String str) {
Scanner in = new Scanner(System.in);
String original, reverse = "";
str = in.nextLine();
int length = str.length();
for ( int i = length - 1; i >= 0; i-- ) {
reverse = reverse + str.charAt(i);
}
if (str.equals(reverse))
System.out.println("Entered string is a palindrome.");
}
}
Because of this line:
n = in.nextLine();
your program is waiting for a second input, but you already got one before entering the function.
Remove this line and it works.
Here's your program, cleaned (and tested) :
public static void main(String[] args){
Scanner console = new Scanner (System.in);
String n = console.next();
Printpalindrome(n);
}
public static void Printpalindrome(String n){
String reverse = "";
for ( int i = n.length() - 1; i >= 0; i-- ) {
reverse = reverse + n.charAt(i);
System.out.println("re:"+reverse);
}
if (n.equals(reverse))
System.out.println("Entered string is a palindrome.");
else
System.out.println("Entered string is NOT a palindrome.");
}
Of course, this isn't the best algorithm, but you already know there are many QA on SO with faster solutions (hint: don't build a string, just compare chars).
Remove
Scanner in = new Scanner(System.in);
and
n = in.nextLine();
from Printpalindrome function
and it should work.
This can be implemented in a far more efficient manner:
boolean isPalindrom(String s){
if (s == null /* || s.length == 0 ?*/) {
return false;
}
int i = 0, j = s.length() - 1;
while(i < j) {
if(s.charAt(i++) != s.charAt(j--)) {
return false;
}
}
return true;
}
The argument for PrintPalindrom is ignored. You read another value with `in.nextLine()'. Which is the reason for your issues.
Ur code with some correction:-
import java.util.*;
class Palindrome
{
public static void main(String args[])
{
String original, reverse = "";
Scanner in = new Scanner(System.in);
System.out.println("Enter a string to check if it is a palindrome");
original = in.nextLine();
int length = original.length();
for ( int i = length - 1; i >= 0; i-- )
reverse = reverse + original.charAt(i);
if (original.equals(reverse))
System.out.println("Entered string is a palindrome.");
else
System.out.println("Entered string is not a palindrome.");
}
}
I tried your code and what i observed was that :
first of all you are making a string to enter on the line 2 of your code:
String n=console.next();
next the the program again goes to waiting when this line gets executed:
n = in.nextLine();
actually this particular line is also expecting an input so that is why the program halt at this point of time.
If you enter your String to be checked for palindrome at this point of time you would get the desired result .
But I would rather prefer you to delete the line
n = in.nextLine();
because, with this, you would have to enter two words which are ambiguous.

Java Word Counter -- Write method that accepts string object as argument and returns word count

The assignment for java is to write a method that accepts string objects as an argument and returns the number of words it contains. Demonstrate the method in a program that asks the user to input a string and passes it to the method. The number of words should be displayed in the screen.. I know its close but there are probably some errors.
public class WordCounter
{
public static void main(String[] args)
{
//Imported scanner here
Scanner in = new Scanner(System.in);
//
//Asks and gets the users input here
//
private static string getInput(Scanner in)
{
String input;
System.out.println("Enter a string here: ");
input = in.nextLine();
//
//Create an if/else statment to find out if the user entered input.
//
if(input.length() > 0)
{
getInput(input);
}
else
{
System.out.println("Error -- You must enter a string!");
System.out.println("Enter a string here: ");
input = in.nextLine();
}
return input;
} //Close public static string getInput here
//
//Calculates the number of words the user inputs
//
public static int getWordCount(String input)
{
int wordcount = 0; //Initializes word counter to 0 at start of program
for(int i = 0; i <= input.length() -1; i++)
{
if(input.charAt(i) == ' ')
{
wordcount++;
}
}
return wordcount;
} //Close public static int getWordCount here
//Print out the number of words within the users string here
System.out.println("The number of words in the string are: " + wordcount);
} //Close public static void main string args here
} //Close public class word counter here
Try this smple method to find wordCount,
public int getWordCount(String value)
{
String[] result = value.split(" ");
return result.length;
}
you wrote all the methods in your main method it wont compile. Place it out side and then try.
Corrections:
You need to call getWordCount if there are any characters in the
input string
if(input.length() > 0)
{
getInput(input); // getWordCount(input);
}
If you just want to count the number of words in the string, do this
int counter = 0;
for(int i = 0; i <= input.length() -1; i++) {
counter++;
}
If you want to avoid counting spaces put, the condition and do continue.

Categories