Running a scanner program - java

I am trying to write a program that basically will read any integer from 1,000 to 999,999 and will then display it with a comma separating the thousands. So far I have this, and eclipse doesn't like it. Why?
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
// Scanner scan = new scanner(system.in);
double value, integer;
System.out.println("Enter your value without a comma");
integer = scan.nextdouble();
System.out.println(integer,);
scan.close();

you have a lot of errors in the code which is why eclipse doesnt like it ;)
To name a few:
new scanner -> Scanner with capital S
system.in -> same with system
check out this snippet below and it will run just fine :)
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone {
public static void main(String[] args) throws java.lang.Exception {
Scanner scan = new Scanner(System.in);
double value, intValue;
System.out.println("Enter your value without a comma");
intValue = scan.nextDouble();
System.out.println(intValue);
scan.close();
}

Your code looks pretty problematic, to say the least. First of all, is the line in which you declare the Scanner supposed to be commented? If not, that could be part of the problem. You should watch out that you pass the upper-case System.in to your Scanner. You also want to use the nextDouble() method. (Java is case sensitive!) You also want to be careful in your second print statement that you do something more like System.out.println(integer+",");

So, first, the solution:
import java.text.NumberFormat;
import java.util.Locale;
import java.util.Scanner;
public class Ideone {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a number:");
long number = scan.nextLong();
NumberFormat f = NumberFormat.getInstance(Locale.ENGLISH);
System.out.println(f.format(number));
scan.close();
}
}
And the problems with you code:
the package declaration is commented, why ?
you import java.lang.* but you don't use it.
your main method throws java.lang.Exception, but I don't see anything in your code throwing that.
you have commented out the scan declaration.
scanner should have the first letter uppercase (java is case-sensitive), same thing for system
you declare a double called value, but you don't use it.
you declare a double called integer (when what you really want is an integer).
you use scan.nextdouble() instead of scan.nextDouble() (but remember, you want an integer, so you should call scan.nextInt()).
I don't see any code trying to put a "," in your number.
you print integer,, this is not even close to what you want, you could have tried integer+"," to concatenate, but it's also not what you want.
you are missing the closing brackets.
the indentation of your code is really bad.
You should have a look at https://stackoverflow.com/tags/java/info in the section Beginners' resources, and try to understand a little bit more and to solve some of your problems by yourself.

Why have you commented the scanner instantiation, also I see the typo in there. The compiler will throw an exception on uninitialized 'scan' object.
Scanner scan = new Scanner(system.in);

In addition to Micah answer, I would suggest you do a check on the input from users to check the range 1000 - 999,999 and re-prompt the user to input the value, if not it will beat the purpose of the range.
System.out.println("Enter your value without a comma");
integer = scan.nextDouble();
while (integer > 999999 OR integer < 1000)
{
System.out.println("Please keep your range in between 1000 - 999,999");
integer = scan.nextDouble();
}

Related

Getting number of elements from user input?

I've been googling this but I still don't understand why this doesn't work. The user would enter an array of integers and I need to find how many elements are in that array.
Scanner s = new Scanner(System.in);
int n = 0; //# of elements in list
while(s.hasNextInt()) {
n++;
s.next();
}
System.out.println(n);
I looked up if using variable outside the scope works, and I've been answers saying that if you're gonna use the variable outside the scope, you should declare and initialize outside the scope (in this case, the while loop). However, this still doesn't work for me. My code right now won't even print "0". Any help would be greatly appreciated.
When you read from command line you have to signal EOF (end of file), otherwise how will your program know if you have stopped entering your elements or not? On windows you can press Ctrl-D and your scanner will stop reading, for example.
You can break out of the loop with the condition that a word is entered, such as "exit" since you want to get an int count. Your code works to count the number of integers entered into a scanner, but you never declared an array to hold all the values.
package com.company;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
ArrayList array = new ArrayList(); //declare your array
Scanner s = new Scanner(System.in);
int n = 0; //# of elements in list
while(s.hasNextInt())
{
n++;
s.next();
array.add(s);//store the array value
if (s.hasNext("exit"))//allow an exit to the loop
break;
}
System.out.println(array.size()); //better, use the size of the array
}
}
Your code works fine.
Check this link. https://ideone.com/vrnoEz
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner s = new Scanner(System.in);
int n = 0; //# of elements in list
while(s.hasNextInt()) {
n++;
s.next();
}
System.out.println(n);
}
}

Use scanner to read inputs next to a certain word

Here is an example of such input.
A 3
B 1
A 2 etc.
As shown above, each input is separated by a line and appears an indeterminate amount of times.
How do I only read the numbers next to the 'A' and convert it all into a string using Scanner?
You can write something like:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main29 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
String string = scanner.next();
int number = scanner.nextInt();
System.out.println(number);
}
}
}
output:
3
1
2
As you can see I just write a loop which works until scanner can read token from STDIN. Inside of loop I read String tokens use next method and then read Integer tokens use nextInt method.
I think now you can add and required logic to the loop i.e. print numbers after A as you wish.

number converting to other number

Hello I have a bit of a problem with calculating numbers from a file.
My input is the following rawData.txt:
19.95
5
The output however is this:
49.0 57
My code looks like this:
import java.util.Scanner;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.PrintStream;
class ReadAndWrite
{
public static void main(String args[])
throws FileNotFoundException {
Scanner diskScanner = null;
diskScanner = new Scanner(new FileReader("rawData.txt"));
PrintStream diskWriter = new PrintStream("cookedData.txt");
double total;
double unitPrice = diskScanner.findWithinHorizon(".", 0).charAt(0);
System.out.println(unitPrice);
int quantity = diskScanner.findWithinHorizon(".", 0).charAt(0);
System.out.println(quantity);
total = unitPrice * quantity;
diskWriter.println(total);
diskScanner.close();
}
}
Eventually the cookedData.txt file contains the number 2793.0
Please help
You are fetching only the first character of each line - because of the charAt(0), then cast it to a double (casting char to double!!)
I can't understand what you are trying to do, but converting char to double using casting is almost always NOT what you should do.
Try using Double.parseDouble instead. see it here: https://docs.oracle.com/javase/7/docs/api/java/lang/Double.html#parseDouble(java.lang.String)
diskScanner.findWithinHorizon(".",0).charAt(0);
means that you are getting any character, because the first parameter of findWithinHorizon is a regular expression, and "." means one character. From that string you take the first char, i.e. 1. The ascii value of 1 is... 49.

What is wrong with my Java coding? It is saying that it cannot find the symbol scanf. How should I recode this?

I am trying to make a Java code that enables the user to input any number and the Java makes a triangle out of that number using *
My code is not compiling, but I think I've finally almost got it down. The only problem is, that it is not recognizing scanf.
Here is my code:
import java.util.Scanner;
class triangle
{
public static void main(String[] args)
{
char print='*';
int row,col;
int noOfRows;
System.out.printf("Enter number of rows to be printed\n");
scanf("%d",noOfRows);
{
for(col=1;col<=row;col++)
{ // this brace is useless, since there is only one statement in this for loop
System.out.printf("%c",print);
} // same for this one
System.out.printf("\n");
}
}
}
How can I fix this?
scanf() and printf() are supported by C and C++ in java:
1. BufferedReader or Scanner for reading from console(System.in).
2. print() or println() for printing to console.(System.out).
You need to declare a new object of the scanner.
Also, to print, is System.out.println("");
You should use Scanner class like this: Scanner scanner = new Scanner(System.in); and do something like this:
System.out.println("Enter number of rows");
noOfRows = scanner.nextInt();
My friend, you use scanf in "C"of "C++" in java we use System.in

What import should I use for keyboard scanners and Math.?

I tried every import I know, and it still basically keeps giving me class, interface, or enum expected error on every line that uses Keyboard or Math.
If you're wondering what the program does, it's suppose to find the distance between 2 points that the user puts in.
// Sam
// 9.25.13
// import csl.Keyboard from the L: drive jdk
import java.io.*;
import java.util.*;
public class swagggg
public static void main ( String [] args)
{
// declare variables
int x1, y1 ,x2, y2;
double distance;
// get user input
Scanner Keyboard = new Scanner (System.in);
System.out.println("Enter the first set of coordinates: ");
x1 = Keyboard.nextInt();
y1 = Keyboard.nextInt();
System.out.println("Enter the second set of coordinates: ");
x2 = Keyboard.nextInt();
y2 = Keyboard.nextInt();
// calculate using the Math class static method
distance = Math.sqrt(Math.pow(x2-x1,2) + (Math.pow(y2-y1,2));
// out results
System.out.println ("The distance between (" +x1+","+y1+") and ("+ x2 +","+y2+") is " + distance);
}
}
/
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Now it compiles but when I type in the first coordinate, it looks like this
Enter the first set of coordinates:
(2,9)
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at C2p8.main(C2p8.java:17)
Process completed.
The Keyboard class doesn't exist in the JDK. Probably it's a custom class made by your teacher of some sort. You would need either the .jar of that class or the actual code. Are you supposed to do your work in your computer? If that's the case the teacher probably gave you that file. The only class I think that you might be needing here instead of Keyboard is Scanner but that one has nextInt() not readInt() method. Also that one has to be instantiated, it is not static and it appears your Keyboard one is.
For the Math class, you're not supposed to import it. It is imported automatically always.
Keyboard is not part of the standard library. Perhaps you meant java.util.Scanner, but that doesn't have readInt() method, it has nextInt(). There's a comment at the top of your code that tells you where it is, it looks like a custom class.
Math is java.lang.Math.
You're missing a ; at the end of
double distance; // <missing that ;
And you have a dangling quote here
y1 = Keyboard.readInt();' // < what is that?
Get rid of it.
Had you used a proper IDE like Eclipse, Netbeans, or IntelliJ you wouldn't have had any of these problems.
java.lang.Math.* for the math...
For getting input from the keyboard, you need a scanner.
Scanner scannerVariableNameWhichYouCouldCallKeyboard = new Scanner(System.in);
so if you simply added the line Scanner Keyboard = new Scanner(System.in);, all of your Keyboard lines would work. You may have to import java.util.Scanner;.
And for reference, if you're working in Eclipse, you can have Eclipse automatically handle your imports by either hovering over the thing that needs an import and waiting for the pop up, or I think Ctrl+O.

Categories

Resources