I am a very new to Java, so my knowledge is very limited. I have been trying to find the problem in this block of code.
import java.util.Scanner;
public class avgFinder {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Input numbers to average. Separate by a space.");
String nums = scan.next();
String[] parseNums = nums.split("[ ]");
double sum = 0;
int cnt = 0;
for (int a=0; a<=parseNums.length-1; a++) {
sum += Double.parseDouble(parseNums[a]);
cnt++;
}
double mean = sum/cnt;
System.out.println("Mean: " + mean);
}
}
But when I input a a set of numbers, only the first number gets printed instead of the actual mean. Example:
Input numbers to average. Separate by a space.
1 2 3
Mean: 1.0
Another thing is if I replace nums.split("[ ]") with nums.split("[,]") and put commas instead of spaces between the numbers in the output, it actually outputs the mean. I like spaces better though, it looks cleaner. Why is this happening?
Try this
use nextLine() instead of next()
nextLine returns complete line of text while next returns only one word
Also use nums.split(" ");
import java.util.Scanner;
public class avgFinder {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Input numbers to average. Separate by a space.");
String nums = scan.nextLine();
String[] parseNums = nums.split(" ");
double sum = 0;
int cnt = 0;
for (int a=0; a<=parseNums.length-1; a++) {
sum += Double.parseDouble(parseNums[a]);
cnt++;
}
double mean = sum/cnt;
System.out.println("Mean: " + mean);
}
}
Calling Scanner.next() will return the next element in a line before a space, so you only getting the first number in your input. Use Scanner.nextLine() which will return all the values on that line.
Scanner.next() returns the next word. By default, words are separated by whitespace. So when you call Scanner.next(), your scanner reads the digits of the first number, hits a space, and says "ok, that's the end of the word. Time to return the result" and you end up with just the first number.
That's why it works when you replace the spaces with commas: Without any spaces, the scanner doesn't find whitespace until it reaches the line break, so it returns the whole line.
Scanner.nextLine() returns the entire line instead of just one word (it reads until it hits a line break), so I'd suggest using that instead.
Related
I am learning java program. I have a question to solve . the question is
enter the no . of people:
enter the product_name, price, stock_available:
total amount is price * no. of people
if the stock available is less than the no of people the print value 0
Example:
**input:**
no . of people : 3
product_name, price, stock_available: book, 100, 3
**output:** 300
public class Product {
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter the no . of people:");
int people=sc.nextInt();
String[] string = new String [3];
System.out.println("Enter the product_name, price, quantity_available:");
for (int i = 0; i < 3; i++)
{
string[i] = sc.nextLine();
}
int quantity=Integer.parseInt(string[2]);
int price=Integer.parseInt(string[1]);
if(people<=quantity) {
System.out.println("Total amout is:"+(price*people));
}
else
{
System.out.println("value is "+0);
}
}
}
console error:
Enter the no . of people:
3
Enter the product_name, price, quantity_available:
book
30
Exception in thread "main" java.lang.NumberFormatException: For input string: "book"
How to solve this error and how to do better way using oops concept ?
For Loop I always prefer to read input using next() .
Using next() will only return what comes before the delimiter (defaults to whitespace). nextLine() automatically moves the scanner down after returning the current line.
As you were using sc.nextLine() this may one reason you were getting java.lang.NumberFormatException.
Try as sc.next(); to read your input
Your problem is you are using :
for (int i = 0; i < 3; i++)
{
string[i] = sc.nextLine();
}
this sc.nextLine() while taking input. Now the problem is sc.nextLine() reads a line until '\n' or enter is encountered. Now, for the first cycle in for loop it it putting a '\n' in the buffer. Because nextLine() stop taking input while '\n' encountered. So, In the next cycle the value of string[1] = '\n'. And when you try to parse this to an Integer then an error occurs. Because this is not an Integer.
Try this:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the no . of people:");
int people = sc.nextInt();
String[] string = new String [3];
System.out.println("Enter the product_name, price, quantity_available:");
for (int i = 0; i < 3; i++)
{
string[i] = sc.next();
}
int price = Integer.parseInt(string[1]);
int quantity = Integer.parseInt(string[2]);
if(people <= quantity) {
System.out.println("Total amount is: "+ (price*people));
}
else
{
System.out.println("value is: "+0);
}
}
You can use an extra sc.nextLine() just before the loop...
sc.nextLine() ----> add this line
for (int i = 0; i < 3; i++)
{
string[i] = sc.nextLine();
}
when you press enter after getting the value of people... your string[] array takes a value in its 0 index position. So the nextLine scans only 2 values from the console and then throws an exception.
On that time your string[] values are = {"", "NAME", "PRICE"}
And you are trying to parse a string value (NAME) to int
According to your input style, your code does not serve your purpose.
Problem:
Case 1: You tried to input something like:
product_name, price, stock_available: book, 100, 3
But in your code, using for loop you tried to get 3 string values.
for (int i = 0; i < 3; i++)
{
string[i] = sc.nextLine();
}
So, after first input, when you press enter without any input, it throws java.lang.NumberFormatException: For input string: ""
Case 2: nextLine() scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.
Since this method continues to search through the input looking for a line separator, it may buffer all of the input searching for the line to skip if no line separators are present. And this is the reason, you may get this exception.
when the loop executes, string[0]'s value will be ""/blank string, which it gets from the buffered line separator. string[1]'s value will be your first string input(product_name).
so, when you tried to parse it as int, it threw number format exception.
Solution:
Case 1. If you want to take input in one line then, do not use for loop. Get input as a string and parse it to get your values.
String[] string = new String[3];
String inputString = null;System.out.println("Enter the product_name, price, quantity_available:");
inputString=sc.next();
string=inputString.split(",");
String product = string[0];
int quantity = Integer.parseInt(string[2]);
int price=Integer.parseInt(string[1]);
Case 2. If you do not solve the buffered line separator issue, then you should use next() method to take input.
This is very simple application. So, oop concept is not necessary for the current context.
i have a project wherein i have to create multiple classes that form the image of each (ex: Digit0, Digit1,...,Digit9) with a small and a large size. there are 10 different classes so i'll just simplify to what's important. (for example class Digit1 contains a print function that outputs a small number 1 or a big number 1). i have no problem creating the classes for these digits, where i'm stuck is in figuring out the tester program.
the tester program should allow the user to input a number (ex: 1, 25, 4354435454 etc.) and input a size (1 for small, and 2 for large) and print out the desired images. so far i have this code and it works but it only allows single digit numbers
import java.util.Scanner;
public class DigitDisplay
{
public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
int digits = scan.nextInt();
int segmentSize = scan.nextInt();
while ((digits!=0)&&(segmentSize!=0)) //terminates when 0 0 is input
{
if (digits==0)
{
if (segmentSize==1) //this is the small size
{
Digit0 small = new Digit0(1);
//this references the small sized 0 created as a method in class Digit0
System.out.println(small.toString());
//this prints the small digit 0
}
else //this is the large size
{
Digit0 big = new Digit0(2);
System.out.println(big.toString());
}
}
//...the other digits are placed as else ifs
}
}
}
i tried altering the scanner objects so that it takes in String digits instead of int digits. so that i could simply split it and use a for loop to go through each character of the string, but i can't seem to get it to work. i really hope i made sense here. i'm a beginner and would really appreciate the help
import java.util.Scanner;
public class DigitDisplay
{
public static void main (String[] args)
{
Scanner scan = new Scanner (System.in);
String digits = scan.next(); //takes in a string of numbers
digits.split(" "); //splits the string into its digits
//int segmentSize = scan.nextInt(); commenting this out because it works. just need to focus on the
digits themselves
while ((!digits.equals("0")) && (segmentSize!=0)) //terminates when input is 0 0
{
for (int i=0; i<digits.length(); i++) //goes through all digits of string
{
int num = digits.charAt(i);
switch (num)
{
case 0:
System.out.println("zero"); //there is a longer code referencing the two sizes but the sizes work but i simplified it again. this is just for me to know whether it is printing the right thing
break;
default:
System.out.println("other"); //these are the other digits, but i just condensed them together just to see if its printing right
break;
}
}
digits = scan.next();
digits.split(" ");
//segmentSize = scan.nextInt();
}
}
}
when i input 002, i want to ouput:
zero
zero
other
but instead, it just outputs "other" for all three.
Looking at the question, I think this is what you're looking for:
Scanner scan = new Scanner (System.in);
String digits = scan.nextLine(); //takes in a string of numbers.
int[] digits_split = new int[0]; //creates an int array to store split digits.
digits_split = digits.split(" "); //splits the string into the digits_split array.
By creating an int array it's now easier to validate the digits.
now you can use this loop to check your split digits:
note below is Pseudo Code and has not been tested...
for(int i = 1; i <= digits.length; i++)
{
if(digits_split[i]=0)
{
System.out.println("zero");
}
else
{
System.out.println("other");
}
}
Also ensure that when entering your digits you put a space in between each one so when the program requests for digits you type: 0 0 2
EDIT:
If your digits contain commas use:
digits = digits.replace(",","");
Also once you've split the string use trim:
digits = digits.trim();
It tidy's things up a little.
ALSO:
when i input 002, i want to ouput:
You need to input: (0[space]0[space]2) to get the output you want. As you're splitting on a " ". Otherwise use a symbol.
Hope this helps,
Rob.
So, I am very new at coding but have a college assignment to create a Word Manipulator. I am supposed to get a string and an INT from the user and invert every Nth word, according to the int input.
I am following steps and am stuck with this error at line 38 (the start of my last FOR LOOP). The compiler is giving me an Not an Statement Error in this line but I cant see where I went wrong.
Could someone gimme a light, please?
ps: I am not allowed to use Token or inverse().
import java.util.Scanner;
public class assignment3 {
public static void main(String[] args) {
// BOTH INPUTS WERE TAKEN
Scanner input = new Scanner (System.in);
String stringInput;
int intInput;
System.out.println("Please enter a sentence");
stringInput = input.nextLine();
System.out.println("Please enter an integer from 1 to 10. \n We will invert every word in that position for you!");
intInput = input.nextInt();
int counter = 1;
// ALL CHARS NOW ARE LOWERCASE
String lowerCaseVersion = stringInput.toLowerCase();
// SPLIT THE STRING INTO ARRAY OF WORDS
String [] arrayOfWords = null;
String delimiter = " ";
arrayOfWords = lowerCaseVersion.split(delimiter);
for(int i=0; i< arrayOfWords.length; i++){
System.out.println(arrayOfWords[i]);
// THIS RETURNS AN ARRAY WITH ALL THE WORDS FROM THE INPUT
}
// IF THE INTEGER INPUT IS BIGGER THAN THE STRING.LENGTH, OUTPUT A MESSAGE
// THIS PART IS WORKING BUT I MIGHT WANT TO PUT IT IN A LOOP AND ASK FOR INPUT AGAIN
if (intInput > arrayOfWords.length){
System.out.println("There are not enough words in your sentence!");
}
// NOW I NEED TO REVERSE EVERY NTH WORD BASED ON THE USER INPUT
//THIS IS WHERE THE ERROR OCCURS
for(int i=(intInput-1); i<arrayOfWords.length; (i+intInput)){
char invertedWord[] = new char[arrayOfWords.length()];
for(int i=0; i < arrayOfWords.length();i++){
ch[i]=arrayOfWords.charAt(i);
}
for(int i=s.length()-1;i>=0;i--){
System.out.print(invertedWord[i]);
}
}
}
}
(i+intInput) isn't a statement. That's like saying 12. Perhaps you mean i=i+intInput or i+=intInput which assigns a value to a variable
well, for one thing, i dont see "s" (from s.length()) initiated anywhere in your code.
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);
}
What I want to do is ask the user for a number of strings to read into an array, and then ask the user to input that number of strings and read them into the array. When I run this code it never asks me for an input the first cycle of the first for-loop, just prints out "String #0: String #1: " and then I can input text. Why is that and what did I do wrong?
import java.util.Scanner;
public class ovn9
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.print("Number of inputs: ");
int lines= sc.nextInt();
String[] text=new String[lines];
for(int x=0; x<text.length; x++)
{
System.out.print("String #"+x+": ");
text[x] = sc.nextLine();
}
for(int y=0; y<text.length; y++)
System.out.println(text[y]);
}
}
Buffering.
nextInt() does not consume the newline in the input buffer that was put there when you entered the number of inputs. In the iteration 0 of the for loop, there's already a line of input in the buffer and nextLine() can complete immediately and the program will wait for new input line only in iteration 1. To ignore the newline in the input, you can add just another nextLine() call before entering the for loop.
Maybe you should change your loop to use 'sc.next()'
for ( int x = 0; x < lines; x++ ) {
System.out.print("String #" + x + ": ");
text[x] = sc.next();
}
It can be explained by the Java API
String next(): Finds and returns the next complete token from this scanner.
String nextLine(): Advances this scanner past the current line and returns the input that was skipped.