I need to solve the following problem: Write a method named tokenStats that accepts as a parameter a Scanner containing a series of tokens. It should print out the sum of all the tokens that are legal integers, the sum of all the tokens that are legal real numbers but not integers, and the total number of tokens of any kind. For example, if a Scanner called data contains the following tokens:
3 3.14 10 squid 10.x 6.0
Then the call of tokenStats(data); should print the following output:
integers: 13
real numbers: 9.14
total tokens: 6
If the Scanner has no tokens, the method should print:
integers: 0
real numbers: 0.0
total tokens: 0
So, this is my question. I have tried to use
while (input.hasNext()) {
if (input.hasNextInt()) {
and this creates an infinite loop,
but if I use
while (input.hasNext()) {
input.next();
if (input.hasNextInt()) {
I lose my first token if it is an int...
what should I do?
I suggest you check this way .. which cover all your scenario
int totalint =0;
float totalfloat=0 ;
int count=0;
while(input.hasNext())
{
String next = input.next();
int n; float f;
try{
if(next.contains(".")
{
f= Float.parseFloat(next);
totalfloat += f;
}
else{
n= Integer.parseInt(next);
totalint +=n;
}
}
catch(Exception e){ /*not int nor a float so nothing*/ }
count++;
}
In order to determine the amount of Integers in your file I suggest doing something like this
Add the following variables to your code
ArrayList<Integer> list = new ArrayList<Integer>();
int EntryCount = 0;
int IntegerCount =0;
Then when looking through the file inputs try something like this were s is an instance of a scanner
while (s.hasNext()) {
if(s.hasNextInt() == true){
int add =s.nextInt();
System.out.println(add);
list.add(add);
IntegerCount++;
}
EntryCount++;
}
Then in order to figure out the sum of all integers you would loop through the array list.
public static void tokenStats(Scanner input) {
int integers = 0;
double real = 0.0;
int tokens = 0;
while (input.hasNext()) {
if (input.hasNextInt()) {
integers+= input.nextInt();
} else if (input.hasNextDouble()) {
real+= input.nextDouble();
} else {
input.next();
}
tokens++;
}
System.out.println("integers: " + integers);
System.out.println("real numbers: " + real);
System.out.println("total tokens: " + tokens);
}
Related
(I'm a beginner at Java)
I am trying to write a program that asks for 6 digits from the user using a scanner, then from those 6 individual digits find the second highest number. So far this works however I'd like to have the input read from a single line rather than 6 separate lines. I've heard of delimiters and tokenisation, but have no idea how to implement it. I'ld like to have it read like "Enter 6 digits: 1 2 3 4 5 6" and parsing each digit as a separate variable so i can then place them in an array as shown. If anyone could give me a run-down of how this would work it would be much appreciated. Cheers for your time.
public static void main(String[] args)
{
//Ask user input
System.out.println("Enter 6 digits: ");
//New Scanner
Scanner input = new Scanner(System.in);
//Assign 6 variables for each digit
int num1 = input.nextInt();
int num2 = input.nextInt();
int num3 = input.nextInt();
int num4 = input.nextInt();
int num5 = input.nextInt();
int num6 = input.nextInt();
//unsorted array
int num[] = {num1, num2, num3, num4, num5, num6};
//Length
int n = num.length;
//Sort
Arrays.sort(num);
//After sorting
// Second highest number is at n-2 position
System.out.println("Second highest Number: "+num[n-2]);
}
}
Your solution does this allready!
If you go through the documentation of scaner you will find out that your code works with different inputs, as long they are integers separated by whitespace and/or line seperators.
But you can optimice your code, to let it look nicer:
public static void main6(String[] args) {
// Ask user input
System.out.println("Enter 6 digits: ");
// New Scanner
Scanner input = new Scanner(System.in);
// Assign 6 variables for each digit
int size=6;
int[] num=new int[size];
for (int i=0;i<size;i++) {
num[i]=input.nextInt();
}
Arrays.sort(num);
// After sorting
// Second highest number is at n-2 position
System.out.println("Second highest Number: " + num[size - 2]);
}
As an additional hint, i like to mention this code still produces lot of overhead you can avoid this by using:
public static void main7(String[] args) {
// Ask user input
System.out.println("Enter 6 digits: ");
// New Scanner
Scanner input = new Scanner(System.in);
// Assign 6 variables for each digit
int size=6;
int highest=Integer.MIN_VALUE;
int secondhighest=Integer.MIN_VALUE;
for (int i=0;i<size-1;i++) {
int value=input.nextInt();
if (value>highest) {
secondhighest=highest;
highest=value;
} else if (value>secondhighest) {
secondhighest=value;
}
}
//give out second highest
System.out.println("Second highest Number: " + secondhighest);
}
if you do not like to point on highest if there are multiple highest, you can replace the else if:
public static void main7(String[] args) {
// Ask user input
System.out.println("Enter 6 digits: ");
// New Scanner
Scanner input = new Scanner(System.in);
// Assign 6 variables for each digit
int size = 6;
int highest = Integer.MIN_VALUE;
int secondhighest = Integer.MIN_VALUE;
for (int i = 0; i < size - 1; i++) {
int value = input.nextInt();
if (value > highest) {
secondhighest = highest;
highest = value;
} else if (secondhighest==Integer.MIN_VALUE&&value!=highest) {
secondhighest=value;
}
}
// give out second highest
System.out.println("Second highest Number: " + secondhighest);
}
Of course, there are many ways to do that. I will give you two ways:
1. Use lambda functions - this way is more advanced but very practical:
Integer[] s = Arrays.stream(input.nextLine().split(" ")).map(Integer::parseInt).toArray(Integer[]::new);
first create a stream, you can read more about streams here
than read the whole line "1 2 3 ...."
split the line by space " " and after this point the stream will look like ["1", "2", "3" ....]
to convert the strings to int "map" operator is used
and finally collect the stream into Integer[]
You can use an iterator and loop as many times as you need and read from the console.
int num[] = new int[6];
for (int i = 0; i < 6; i++) {
num[i] = input.nextInt();
}
There are several ways to do that:
take a single line string, then parse it.
Scanner input = new Scanner(System.in);
....
String numString = input.nextLine();
String[] split = numString.split("\\s+");
int num[] = new int[split];
// assuming there will be always atleast 6 numbers.
for (int i = 0; i < split.length; i++) {
num[i] = Integer.parseInt(split[i]);
}
...
//Sort
Arrays.sort(num);
//After sorting
// Second highest number is at n-2 position
System.out.println("Second highest Number: "+num[n-2]);
I'm having some problems splitting a string that is read in from an input file, making sure it's valid, then saving it to a variable.
Let's say this is the first string:
12345 5 59.28
I would want to split the 12345, 5, and 59.28.
After verifying that they are the correct format ( 00000-99999, 0-5, 000.00 0 100.00 ), I would then assign it to a variable.
My main two obstacles are that I CANNOT use arrays in this program, so I'm not sure how to split the string. I have tried just pulling each section as an int, but that doesn't seem to work.
My other problem is that I'm not sure how to validate it. Would I be using something like this:
//Assuming I have a scanner set up and a class, method declared
//Declare variables
int numbers;
int studentID;
while(fileInput.hasNext())
{
numbers = fileInput.nextInt(); //Not sure how to pull a part of the string
}
//Used to validate that it is within the range
if(numbers < 00000 || numbers > 99999)
{
studentID = numbers;
}
I am a beginner at Java so please do excuse my confusion.
If you know what the structure of the file is, for example if it's always formatted like this:
int int double
Then you can simply callnextInt(), nextInt(), and then nextDouble() to parse the data from it that way.
Maybe something like this
do
{
num1 = scanner.nextInt();
num2 = scanner.nextInt();
num3 = scanner.nextDouble();
} while (scanner.hasNextInt());
And do that in order to collect all of your data, but you'll likely need lots of variables if you have any substantial amount of data you're reading in
Or if there's bad data sometimes with it's correct data immediately after it you could so something like this to skip over the bad one, even though it's not very pretty
do
{
if (scanner.hasNextInt())
{
num1 = scanner.nextInt();
}
else
{
scanner.next() // move past whatever bad data there was
num1 = scanner.nextInt();
}
if (scanner.hasNextInt())
{
num2 = scanner.nextInt();
}
else
{
scanner.next() // move past whatever bad data there was
num2 = scanner.nextInt();
}
if (scanner.hasNextDouble())
{
num3 = scanner.nextDouble();
}
else
{
scanner.next() // move past whatever bad data there was
num3 = scanner.nextDouble();
}
} while (scanner.hasNext());
I think your teachers give this assignment to practice your if-else condition or switch statement and for loop(fundamental) skills.
Here what I did, this may be not completely match with your assignment question but using this you can get complete idea and think of a way to reduce this. Hey! because of we are not here to do your assignment. you have to tackle with your problem and get familiar with those.
Try to understand these, do changes look what happen:
public static void main(String[] args) {
Scanner fileInput = new Scanner(System.in);
//Declare variables
String numbers = "";
String firstNum = "";
String secondNum = "";
String thirdNum = "";
int studentID = 0;
int secondDigit = 0;
double thirdDigit = 0;
System.out.print("Input: ");
numbers = fileInput.nextLine();
int firstIndex = 0;
int secondIndex = 0;
int thirdIndex = 0;
firstIndex = numbers.indexOf(" ");
if(firstIndex <= 4){
System.out.println("Number should be 5");
}else{
firstNum = numbers.substring(0, firstIndex);
numbers = numbers.substring(firstIndex+1);
studentID = Integer.parseInt(firstNum);
if(studentID > 0 && studentID < 99999){
System.out.println("First num: " +firstNum);
}else{
System.out.println("first digits not in a range ");
}
}
secondIndex = numbers.indexOf(" ");
if(secondIndex == 0){
System.out.println("no number");
}else{
secondNum = numbers.substring(0, secondIndex);
numbers = numbers.substring(secondIndex+1);
secondDigit = Integer.parseInt(secondNum);
if(secondDigit >= 0 && secondDigit <= 5){
System.out.println("Second num: " +secondNum);
}else{
System.out.println("second digit not in a range ");
}
}
thirdIndex = numbers.length();
if(thirdIndex < 3){
System.out.println("3 numbers should be there");
}else{
thirdNum = numbers.substring(0, thirdIndex);
thirdDigit = Double.parseDouble(thirdNum);
if(thirdDigit >= 0 && thirdDigit <= 100){
System.out.println("third num: " +thirdNum);
}else{
System.out.println("third digit not in a range ");
}
}
}
I'm not going to explain this also. You have to try, if you have any problem after tackling with this code. ask any question in comment.
Hope this will help!
Try this. Invalid formats will throw an exception during the next method call.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner in = new Scanner("12345 5 59.28");
in.useDelimiter(" "); // reads per space
String next = in.next("\\d{5}"); // reads next 5 digits
int numbers = Integer.valueOf(next);
System.out.println(numbers);
next = in.next("\\d{1}"); // reads next 1 digit
int studentId = Integer.valueOf(next);
System.out.println(studentId);
next = in.next("\\d{2}\\.\\d{2}"); // reads next a decimal with two digits before and after point
float floatingNumbers = Float.valueOf(next);
System.out.println(floatingNumbers);
}
}
<script src="//repl.it/embed/IWzC/0.js"></script>
Imagine there is Scanner passes any String input such as "11 22 a b 22" and the method should calculate the total sum of all of the numbers (55 for the mentiond example). I've coded something here but I'm not able to skip strings. Could anyone help me with that?
System.out.println("Please enter any words and/or numbers: ");
String kbdInput = kbd.nextLine();
Scanner input = new Scanner(kbdInput);
addNumbers(input);
public static void addNumbers(Scanner input) {
double sum = 0;
while (input.hasNextDouble()) {
double nextNumber = input.nextDouble();
sum += nextNumber;
}
System.out.println("The total sum of the numbers from the file is " + sum);
}
To be able to bypass non-numeric input, you need to have your while loop look for any tokens still on the stream, not just doubles.
while (input.hasNext())
Then, inside, the while loop, see if the next token is a double with hasNextDouble. If not, you still need to consume the token with a call to next().
if (input.hasNextDouble())
{
double nextNumber = input.nextDouble();
sum += nextNumber;
}
else
{
input.next();
}
I need to write a program in Java that prompts the user to enter three integer. Among these integers entered, the largest of said integers will need to be found in addition to the square root. I'm just a beginner, and I appreciate any and all assistance.
import java.util.Scanner;
public class largest {
public static void main (String [] args) {
int Integer1;
int Integer2;
int Integer3;
Scanner input=new Scanner(System.in);
System.out.println("Enter 3 integers:");
Integer1 = input.nextInt();
Integer2 = input.nextInt();
Integer3 = input.nextInt();
if (Integer1 > Integer2);
System.out.println (Integer1);
if (Integer1 > Integer3);
System.out.println (Integer1)
This is all I have so far, and I'm dubious that I'm even on track. Please, help.
I would recommend using Math.max as aioobe suggested, but if you want to implement the logic yourself use this:
import java.util.Scanner;
import java.lang.Math;
class prog {
public static void main (String [] args) {
int Integer1;
int Integer2;
int Integer3;
Scanner input = new Scanner(System.in);
System.out.println("Enter 3 integers:");
Integer1 = input.nextInt();
Integer2 = input.nextInt();
Integer3 = input.nextInt();
if (Integer1 > Integer2) {
if (Integer1 > Integer3) {
System.out.println (Integer1);
System.out.println (Math.sqrt((float)Integer1));
}
else {
System.out.println (Integer3);
System.out.println (Math.sqrt((float)Integer3));
}
}
else if (Integer2 > Integer3) {
System.out.println (Integer2);
System.out.println (Math.sqrt((float)Integer2));
}
else {
System.out.println (Integer3);
System.out.println (Math.sqrt((float)Integer3));
}
}
}
For anything more than 3, your best off using Math.max. The (float) part is converting the integer to a float, otherwise the square root wouldn't be precise (as integers are whole numbers
There are a lot of ways to do this and you can use different libraries and data types , I'm not sure you are allowed to use for loop , array or Lists .
Mostly for these kind of jobs you need to use loops, that make it simple and easy to understand .
Here are few different ways that you can do it :
In this example if you need to get more than 3 entries simply modify the number 4 to number of integers that you need to receive from user.
int num, tmp = 0;
Scanner input = new Scanner(System.in);
for (int i = 1; i < 4; i++) {
System.out.printf("Enter integer number %d :", i);
num = input.nextInt();
if (num > tmp) {
tmp = num;
}
}
System.out.printf("the largest number is :%d and the Square is: %s", tmp, Math.sqrt((float) tmp));
second Way without using the for loop:
int num, tmp = 0;
Scanner input = new Scanner(System.in);
System.out.printf("Enter integer number 1 :");
num = input.nextInt();
if (num > tmp) {
tmp = num;
}
System.out.printf("Enter integer number 2 :");
num = input.nextInt();
if (num > tmp) {
tmp = num;
}
System.out.printf("Enter integer number 3 :");
num = input.nextInt();
if (num > tmp) {
tmp = num;
}
System.out.printf("the largest number is :%d and the Square is: %s", tmp, Math.sqrt((float) tmp));
Always try to use less variables, that's make your application more memory efficient.
I am allowing the user to enter numbers via command line. I would like to make it so when the user enters more then one number on the command line at a time it displays a message asking for one number then press enter. then carries on.
here is my code. If someone could show me how to implement this I would appreciate it.
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.Scanner;
class programTwo
{
private static Double calculate_average( ArrayList<Double> myArr )
{
Double sum = 0.0;
for (Double number: myArr)
{
sum += number;
}
return sum/myArr.size(); // added return statement
}
public static void main( String[] args )
{
Scanner scan = new Scanner(System.in);
ArrayList<Double> myArr = new ArrayList<Double>();
int count = 0;
System.out.println("Enter a number to be averaged, repeat up to 20 times:");
String inputs = scan.nextLine();
while (!inputs.matches("[qQ]") )
{
if (count == 20)
{
System.out.println("You entered more than 20 numbers, you suck!");
break;
}
Scanner scan2 = new Scanner(inputs); // create a new scanner out of our single line of input
try{
myArr.add(scan2.nextDouble());
count += 1;
System.out.println("Please enter another number or press Q for your average");
}
catch (InputMismatchException e) {
System.out.println("Stop it swine! Numbers only! Now you have to start over...");
main(args);
return;
}
inputs = scan.nextLine();
}
Double average = calculate_average(myArr);
System.out.println("Your average is: " + average);
}
}
As suggested in the comments to the question: Just do not scan the line you read for numbers, but parse it as a single number instead using Double.valueOf (I also beautified the rest of your code a little, see comments in there)
public static void main( String[] args )
{
Scanner scan = new Scanner(System.in);
ArrayList<Double> myArr = new ArrayList<Double>();
int count = 0;
System.out.println("Enter a number to be averaged, repeat up to 20 times:");
// we can use a for loop here to break on q and read the next line instead of that while you had here.
for (String inputs = scan.nextLine() ; !inputs.matches("[qQ]") ; inputs = scan.nextLine())
{
if (count == 20)
{
System.out.println("You entered more than 20 numbers, you suck!");
break;
}
try{
myArr.add(Double.valueOf(inputs));
count++; //that'S even shorter than count += 1, and does the exact same thing.
System.out.println("Please enter another number or press Q for your average");
}
catch (NumberFormatException e) {
System.out.println("You entered more than one number, or not a valid number at all.");
continue; // Skipping the input and carrying on, instead of just starting over.
// If that's not what you want, just stay with what you had here
}
}
Double average = calculate_average(myArr);
System.out.println("Your average is: " + average);
}
(Code untested, so there may be errors in there. Please notify me if you got one ;))
String[] numbers = inputs.split(" ");
if(numbers.length != 1){
System.out.println("Please enter only one number");
}