Basic Java questions Scanning - java

This is very basic java that i'm struggling with n00b style. it just prints out this
Please enter '.' when you want to calculate
1 2 3
.
Numbers are 1 2 3
The Sum is0The Product is1
when it is supposed to calculate the sum and product of those consecutive numbers. something is wrong id appreciate any help!
main method
import java.util.*;
public class NumberScanned {
public static void main(String[] args) {
System.out.println("Please enter '.' when you want to calculate");
Scanner keyboard = new Scanner(System.in);
String scannedString = keyboard.nextLine();
Scanning scanz= new Scanning(scannedString);
while(!keyboard.nextLine().equals("."))
{
scanz.set(scannedString);
}
keyboard.close();
System.out.println("Numbers are"+scannedString);
scanz.printState();
}
}
Class Scanning
public class Scanning {
int num;
int sum;
int product;
String userInput;
public Scanning(String userInput)
{
num=0;
sum=0;
product=1;
this.userInput=userInput;
}
public void set(String userInput)
{
for(int index=0; index<userInput.length(); index++)
{
if(Character.isDigit(userInput.charAt(index))==true)
{
num=userInput.charAt(index);
sum+=num;
product*=num;
}
else
{
index++;
}
}
}
public void printState()
{
System.out.println("The Sum is"+sum+"The Product is"+product);
}
}

A few things to look at:
We know keyboard.nextLine() gets the input from the console, but where are you checking it's validity (more importantly, when do you check it?). Are you looking at all input or just the last line?
isDigit will return true if the passed in character is a number. Do you want to operate on numbers or characters in your for loop?
(a side note, What happens if I enter "1 10" in the console?)
A for loop will automatically increment its index at the end of a loop, so an additional ++ is unnecessary

You might find this helful in case you just need the sum and product values of a user entered
values.
public class ProductSumCalculator{
private static List<Integer> numbers = new ArrayList<Integer>();
public static void main(String[] args){
getInputs();
calculateSumAndProduct();
}
private static void getInputs() {
Scanner scanner = new Scanner(System.in);
System.out.println("Please Enter numbers or ctrl+z to end inputs");
while(scanner.hasNext()){
numbers.add(scanner.nextInt());
}
}
private static void calculateSumAndProduct() {
Iterator<Integer> iterator = numbers.iterator();
int sum=0;
int product=1;
int nextVal;
while(iterator.hasNext()){
nextVal = iterator.next();
sum+=nextVal;
product*=nextVal;
}
System.out.println("Value entered are: "+numbers+".\nThe sum is "+
sum+".The product is "+product);
}
}

You can also try this. You can calculate the sum and product of all the int from your string line input like this:
import java.util.Scanner;
public class Scanning {
/*
* This method returns the integer. If while
* conversion an Exception is thrown it returns
* null. Otherwise the integer.
*/
public static Integer tryParse(String text) {
try {
return Integer.parseInt(text);
} catch (NumberFormatException e) {
return null;
}
}
/*
* Next String line is scanned. It is split by space.
* Stores String tokens in an String array from one String variable.
* Then passed to tryParse() class method. null or auto Boxed Integer
* is returned accordingly. It is auto unboxed from Integer
* object to int variable. Then sum and product is calculated and
* the final result is printed on the console Or Integrated
* Development Environment.
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner keyboard = new Scanner(System.in);
String strInts = keyboard.nextLine();
String[] splits = strInts.split("\\s+");
int i = 0;
Integer anInteger = null;
int total = 0;
int product = 1;
while((i < splits.length)) {
anInteger = tryParse(splits[i]);
if(anInteger != null) {
total = total + anInteger;
product = product * anInteger;
}
++i;
}
System.out.println("The sum is: " + total);
System.out.println("The product is: " + product);
}
}

Related

I'm trying to create a looping validation method that tests data type and range

I'm new to java and I'm tinkering with my code and decided to create an input validation method, my problem is how am I going to loop the input through the validations.
First I decided to take the input as string to do a try/catch with a double, no problem with that, now I need to test the input if it's in the range of 0-100. Of course I wanted to check if the user will type in a double in the "range check". What I wrote somewhat worked but when the input passed the data type validation but not the range check, it will still return the first double, whatever I typed next.
public static double check(String n){
boolean done = false;
double i=0.0;
Scanner beep = new Scanner(System.in);
while (!done) {
try {
i = Double.parseDouble(n);
done = true;
} catch (Exception e) {
System.out.print("Please input a valid grade (0-100): ");
n = beep.nextLine();
}
}
double b = rangetest(i);
return b;
}
public static double rangetest (double n){
if (n > 100 || n < 0){
System.out.print("0-100 only ");
Scanner beep = new Scanner(System.in);
check(beep.next());
}
return n;
}
public static void main(String[] args) {
Scanner beep = new Scanner(System.in);
double ave = 0.0;
int rounded;
for (int i = 1; i <= 5; i++)
{
System.out.print("Input grade number " + i + " : ");
ave += rangetest(check(beep.next()));
}
ave /= 5;
rounded = (int)Math.round(ave);
}
Is there any easier methods or workarounds? Or am I doing it all wrong? Cheers!
Beware of Scanner#next, this can leave a dangling new line character in the buffer which can mess with your workflows, however, the core issue is with your rangetest
public static double rangetest (double n){
if (n > 100 || n < 0){
System.out.print("0-100 only ");
Scanner beep = new Scanner(System.in);
check(beep.next());
}
return n;
}
Here, if the value is not within the specified range, you're calling check again, but you're ignoring the result, so you end up returning the original value of n
It would seem that instead, you want to do...
n = rangetest(check(beep.next()))
within the if block.
You could accomplish something similar using do-while loops, for example...
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Double value = getDoubleWithinRange(scanner, "Make me an offer ([X] to exit): ", "That's not a reasonable offer", "X", 0, 100, "Value is not within a valid range (0-100)");
if (value != null) {
System.out.println("You mad an offer of " + value);
}
}
public static Double getDoubleWithinRange(Scanner input, String prompt, String errorMessage, String exitValue, double min, double max, String rangeErrorMessage) {
boolean done = false;
Double value = null;
do {
value = getDouble(input, prompt, errorMessage, exitValue);
if (value != null) {
if (isWithinRange(value, 0, 100)) {
done = true;
} else {
beep();
System.out.println(rangeErrorMessage);
}
} else {
done = true;
}
} while (!done);
return value;
}
public static void beep() {
java.awt.Toolkit.getDefaultToolkit().beep();
}
public static boolean isWithinRange(double value, double min, double max) {
return value >= min && value <= max;
}
public static Double getDouble(Scanner input, String prompt, String errorMessage, String exitValue) {
Double value = null;
boolean exit = false;
do {
System.out.print(prompt);
String nextLine = input.nextLine();
Scanner parser = new Scanner(nextLine);
if (parser.hasNextDouble()) {
value = parser.nextDouble();
} else if (nextLine.equals(exitValue)) {
exit = true;
} else {
beep();
System.out.println(errorMessage);
}
} while (!(value != null || exit));
return value;
}
}
nb: I have a exit condition available, you don't need it, but it's nice as a demonstration
I fashioned myself a function from #MadProgrammer's code (Thanks man!), this somehow works a wee bit simpler.
public static double getValue() {
Scanner beep = new Scanner(System.in);
boolean flag = true;
double value=0.0;
while(flag==true){
if(beep.hasNextDouble()){
value = beep.nextDouble();
if(value>=0&&value<=100){
flag=false;
}
else{
System.out.print("Invalid input, 0-100 only: ");
beep.nextLine();
}
}
else{
System.out.print("That's not a numerical value, try again: ");
beep.nextLine();
}
}
return value;
}
Feel free to comment, make a correction and/or suggest anything that would make this better.

Having trouble building a math Calculator

I am trying to build a math Calculator in Java but I am having problems with it, I want to build it with methods and not just int.
I am having problems with how to print the return value (rishon+sheni) and also how to check if the in.nextLine() that the console wrote equal to plus like that:
package mehadash;
import java.util.Scanner;
public class lilmod {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String plus = null;
String minus = null;
String math;
int sum = 0;
System.out.println("What kind of math you want to do?");
math = in.nextLine();
if(math = plus)
{
System.out.println("Enter the two numbers you would like to check");
SumNumbers(in.nextInt(),in.nextInt());
System.out.println("The answer is :" +SumNumbers());
}
minusNumbers(in.nextInt(),in.nextInt());
}
public static int SumNumbers(int rishon , int sheni)
{
return rishon + sheni;
}
public static int minusNumbers(int rishon , int sheni)
{
return rishon - sheni;
}
}
You can always just define more variables.
int numberA = in.nextInt();
int numberB = in.nextInt();
int result = SumNumbers(numberA, numberB);
System.out.println("The result: " + result);
how to print the return value (rishon+sheni)
Try this way:
System.out.println("The answer is :" +SumNumbers(in.nextInt(),in.nextInt()));
instead of
SumNumbers(in.nextInt(),in.nextInt());
System.out.println("The answer is :" +SumNumbers());
also how to check if the in.nextLine(); that the console wrote equal
to plus
Try
if(math.equals("+"))
instead of
if(math = plus)

Output will not print the correct information

I'm trying to make a program which asks the user a particular bird then how many of them they had seen at that point. If the use at any point enters the word 'END' then the system should print out the most seen bird and the number seen. However, when running my program if I enter 'END' at random points it instead returns that the most seen was END with 0 seen. I can't figure out how to make it work. I've tried different methods but it's just not working properly. Also, I've set the maximum array limit to 10 possitions but it continues after 10 and if i enter a value the system crashes. Have I written the limit part properly? Or am I missing something important?
import java.util.Scanner;
public class testing
{
public static void main (String[] param)
{
birdInput();
most();
System.exit(0);
}
public static void birdInput()
{
int i = 0;
String birdInput;
int numberInput;
Scanner scanner = new Scanner(System.in);
int maxVal = Integer.MIN_VALUE;
int maxValIndex = -1;
while (true)
{
System.out.println("What bird did you see?");
birdInput = scanner.nextLine();
if (birdInput.equals("END"))
{
System.out.print("\nWell....I guess thanks for using this program?\n");
System.exit(0);
}
else
{
String[] birds = new String[10];
int[] numbers = new int[10];
birds[i] = scanner.nextLine();
System.out.println("How many did you see?");
numbers[i] = scanner.nextInt();
i++;
if (birds[i].equals("END"))
{
maxVal = numbers[i];
maxValIndex = i;
System.out.print("\nThe most common bird that you saw was the " + birds[maxValIndex] + " with " + maxVal + " being seen in total\n");
System.exit(0);
}
}
}
}
public static void most()
{
System.out.println("fdff");
}
}
This is my edit of Till Hemmerich's answer to my issue. I tried to remove the global variables and so combine the entire code into 1 method. However, I'm still having some issues. Been working at it but really confused.
import java.util.Scanner;
public class birds2
{
public static void main(String[] param)
{
birdInput();
System.exit(0);
}
public static void birdInput()
{
Scanner scanner = new Scanner(System.in);
String[] birds = new String[99999999];
int[] numbers = new int[99999999];
int i = 0;
int maxIndex;
while (i <= birds.length)
{
System.out.println("What bird did you see?");
birds[i] = scanner.nextLine();
System.out.println("How many did you see?");
numbers[i] = scanner.nextInt();
i++;
}
int newnumber = numbers[i];
if ((newnumber > numbers.length))
{
maxIndex = i;
i++;
}
if (birds[i].toUpperCase().equals("END"))
{
System.out.print("\nWell....I guess thanks for using this program?\n");
System.out.print("\nThe most common bird that you saw was the " + birds[maxIndex] + " with " + numbers[maxIndex] + " being seen in total\n");
System.exit(0);
}
}
}
You're re-declaring the birds and numbers arrays in each iteration of the loop. They should be declared and initialized only once, before the loop.
I changed a lot so im going to explain my changes here in total.
First of all i had to move the Array Definition out of your while-loop as >mentioned above, since other wise you would override these Arrays every time.
I also made them globally accessible to work with them in other methods.
public static int maxIndex;
public static String[] birds = new String[10];
public static int[] numbers = new int[10];
in general I re structured the whole code a little bit to make it more readable and a little bit more object-orientated.
For example I created an method called inputCheck() which returns our input as a String and check if it equals END so you do not have to write your logic for this twice. (it also considers writing end lower or Uppercased by just Upper our input before checking it"if (input.toUpperCase().equals("END"))")
static String inputCheck() {
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
if (input.toUpperCase().equals("END")) {
end();
}
return input;
}
this method can now be called every time you need an input like this:
birds[i] = inputCheck();
but you need to be carefull if you want to get an integer out of it you first have to parse it like this:Integer.parseInt(inputCheck())
after that I wrote a method to search for the biggest Value in your numbers Array and getting its index:
public static int getMaxIndex(int[] numbers) {
for (int i = 0; i < numbers.length; i++) {
int newnumber = numbers[i];
if ((newnumber > numbers.length)) {
maxIndex = i;
}
}
return maxIndex;
}
it takes an int array as parameter and returns the index of the highest element in there as an Integer. Called like this:maxIndex = getMaxIndex(numbers);
Then after that I rewrote your end method. It now just calles our getMaxIndex method and prints some output to the console.
public static void end() {
maxIndex = getMaxIndex(numbers);
System.out.print("\nWell....I guess thanks for using this program?\n");
System.out.print("\nThe most common bird that you saw was the " + birds[maxIndex] + " with " + numbers[maxIndex] + " being seen in total\n");
System.exit(0);
}
to fix your last problem (crashing after more then 10 inputs)I changed your while-loop. Since your array only has 10 places to put things it crashes if you try to put information in place number 11. it not looks like this:while (i <= birds.length) instead of while (true) this way the max loops it can take is the amout of places Array birds has and it wont crash anymore.
public static void birdInput() {
int i = 0;
while (i <= birds.length) {
System.out.println("What bird did you see?");
birds[i] = inputCheck();
System.out.println("How many did you see?");
numbers[i] = Integer.parseInt(inputCheck()); //you should check here if its actuall a number otherwiese your programm will crash
i++;
}
}
Here is the whole code in total:
import java.util.Scanner;
/**
*
* #author E0268617
*/
public class JavaApplication1 {
public static int maxIndex;
public static String[] birds = new String[10];
public static int[] numbers = new int[10];
public static void main(String[] param) {
birdInput();
most();
System.exit(0);
}
public static void birdInput() {
int i = 0;
while (i <= birds.length) {
System.out.println("What bird did you see?");
birds[i] = inputCheck();
System.out.println("How many did you see?");
numbers[i] = Integer.parseInt(inputCheck()); //you should check here if its actuall a number otherwiese your programm will crash
i++;
}
}
static String inputCheck() {
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
if (input.toUpperCase().equals("END")) {
end();
}
return input;
}
public static int getMaxIndex(int[] numbers) {
for (int i = 0; i < numbers.length; i++) {
int newnumber = numbers[i];
if ((newnumber > numbers.length)) {
maxIndex = i;
}
}
return maxIndex;
}
public static void end() {
maxIndex = getMaxIndex(numbers);
System.out.print("\nWell....I guess thanks for using this program?\n");
System.out.print("\nThe most common bird that you saw was the " + birds[maxIndex] + " with " + numbers[maxIndex] + " being seen in total\n");
System.exit(0);
}
public static void most() {
System.out.println("fdff");
}
}
I hope you understand where the Problems had been hidden if you have any Questions hit me up.

Use scanner only from main method

I have this class (with setters, getters and one method) that asks from a user a number indefinitely until he types -1.
I've called the Scanner Method from both, the main method and the class itself, is there a way to call the Scanner method only once only from the main method and apply the input to the class every time it is needed? I really appreciate your help. If something is not clear, please contact me.
Here's the Class Code:
public class calculation {
int current = 0;
int maxNum = 0;
int minNum;
int counter=0;
float sum = 0;
float avg;
Scanner scan = new Scanner(System.in);
public void setMin(int min){
this.minNum = min;
}
public int getMin(){
return minNum;
}
public void setMax(int max){
this.maxNum = max;
}
public void setSum(float sum){
this.sum += sum;
}
public void minMax(int current){
setMin(current);
while(current!=-1){
setSum(current);;
if(current>getMin()){
setMax(current);
}else if(current<getMin()){
setMin(current);;
}
current = scan.nextInt();
counter++;
}
System.out.println("The smallest number you entered was: \n" + minNum);
System.out.println("The biggest number you entered was: \n" + maxNum);
System.out.println("The sum of all those numbers is: \n" + sum);
System.out.println("The avarege number is: \n" + (sum/counter));
}
}
And here's the main method code:
public class minusOne {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
calculation cal1 = new calculation();
System.out.println("Type numbers at will, when finish, type -1 and press enter");
cal1.minMax(scan.nextInt());
scan.close();
}
}
From what I understand, you don't want to have two call to new Scanner(System.in);
To avoid this, you can simply, in your class calculation, write :
Scanner scan;
And add a constructor :
public calculation(Scanner sc){
scan = sc;
}
Of course, in the main method you should write :
new calculation(scan)
I hope I answered your question
Note: in Java your classes name should start with uppercase letter, it should be Calculation
You have some alternatives for this, you can have your Calculator class with a constructor that takes a Scanner as a parameter and then store it in a field, or you cand have a public field in the Calculator class and in your main when you get the scanner just affect this field (but it should be private, you can change it via getters and setters methods).
/* This is the first option*/
public class Calculation {
int current = 0;
int maxNum = 0;
int minNum;
int counter=0;
float sum = 0;
float avg;
private Scanner scan;
public Calculation(Scanner scan){
this.scan = scan;
}
public int setCurrent(int current){
this.current = current;
return current;
}
public void setMin(int min){
this.minNum = min;
}
public int getMin(){
return minNum;
}
public void setMax(int max){
this.maxNum = max;
}
public void setSum(float sum){
this.sum += sum;
}
public void minMax(int current){
setMin(current);
while(current!=-1){
setSum(current);;
if(current>getMin()){
setMax(current);
}else if(current<getMin()){
setMin(current);;
}
current = setCurrent(current);;
counter++;
}
System.out.println("The smallest number you entered was: \n" + minNum);
System.out.println("The biggest number you entered was: \n" + maxNum);
System.out.println("The sum of all those numbers is: \n" + sum);
System.out.println("The avarege number is: \n" + (sum/counter));
}
}
/* Second option */
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
calculation cal1 = new calculation();
//if the field scan in Calculation is public
cal1.scan = scan;
//if it is private
cal1.setScan(scan);
System.out.println("Type numbers at will, when finish, type -1 and press enter");
cal1.minMax(scan.nextInt());
scan.close();
}

Java assignment don't know what is the mistake

the question is :
A fruit shop sells several types of fruits each day. Write a program that reads from user several lines of input.Each line includes a fruit's name,price per kilogram (as an integer), number of kilograms sold (as an integer).
the program should calculate and print the earned money of all fruits sold and fruit that achieved largest profit.
hint: -you could assume that user will insert valid data -user could stop the program via entering the word "stop" as a fruit's name.
Sample input and out put:
in each line, insert a fruit's name, price per kilogram, number of kilograms sold. To halt the program,insert "stop" as a fruit's name
banana 2 11
mango 3 8
peach 4 5
stop
the earned money of all fruits sold: 66
fruit that achieved the largest profit: mango
what i wrote now:
public static void main(String[] args) {
// TODO code application logic here
Scanner input = new Scanner (System.in);
String fruitname= " ";
String maxfruit = " ";
int price = 0,number=0;
int sum=0;
int max=0;
System.out.print("Fruit name, " + "price in killogram, number of killogram sold: ");
while (!fruitname.equals("stop"))
{
fruitname = input.next();
price = input.nextInt();
number = input.nextInt();
}
if (fruitname.equals("stop"))
{
sum = sum+(price*number);
}
if (max<(price*number))
{
max = price*number;
maxfruit = fruitname;
}
System.out.println("the earned money of all fruits is " + sum);
System.out.println("fruit that achieved the largest profit is "+ maxfruit);
}
}
the program is not reading what i submit to it, don't know why and not giving me the sum and the max fruit.. what is the problem of what i wrote?
As you can see your reads happen in the while loop:
while (!fruitname.equals("stop"))
{
fruitname = input.next();
price = input.nextInt();
number = input.nextInt();
}
Every time it loops - it overrides the values. Finally when you read stop and exit the loop - your fruitname is stop. So you need to fix your logic on how you would want to read in the input
Working variant:
public class FruitTest {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Fruit name, " + "price in killogram, number of killogram sold: ");
String text = input.nextLine();
String[] words = text.split(" ");
List<Fruit> fruits = parseInput(words);
int sum = getSum(fruits);
String popular = getPopularFruitName(fruits);
System.out.println("Got fruits: " + fruits.toString());
System.out.println("the earned money of all fruits is " + sum);
System.out.println("fruit that achieved the largest profit is " + popular);
}
private static String getPopularFruitName(List<Fruit> fruits) {
int max = 0;
String name = null;
for (Fruit fruit : fruits) {
int checkVal = fruit.getPrice() * fruit.getAmount();
if(checkVal > max) {
max = checkVal;
name = fruit.getName();
}
}
return name;
}
private static int getSum(List<Fruit> fruits) {
int result = 0;
for (Fruit fruit : fruits) {
result += fruit.getPrice() * fruit.getAmount();
}
return result;
}
private static List<Fruit> parseInput(String[] words) {
List<Fruit> result = new ArrayList<Fruit>();
int element = 1;
final int name = 1;
final int price = 2;
final int amount = 3;
Fruit fruit = null;
for (String word : words) {
if (word.equals("stop") || word.isEmpty()) {
break;
}
if(element > amount)
element = name;
switch (element) {
case name:
fruit = new Fruit(word);
result.add(fruit);
break;
case price:
if (fruit != null) {
fruit.setPrice(Integer.valueOf(word));
}
break;
case amount:
if(fruit != null) {
fruit.setAmount(Integer.valueOf(word));
}
break;
}
element++;
}
return result;
}
static class Fruit {
String name;
int price = 0;
int amount = 0;
Fruit(String name) {
this.name = name;
}
String getName() {
return name;
}
int getPrice() {
return price;
}
void setPrice(int price) {
this.price = price;
}
int getAmount() {
return amount;
}
void setAmount(int amount) {
this.amount = amount;
}
#Override
public String toString() {
return name + ". $" + price +
", amount=" + amount;
}
}
}
Comments to code - it's proper way to parse all the inputted string and parse it to an object that stores all the data - name, price and amount. Store all parsed objects into array or a list and then calculate max and popular fruit while looping your parsed fruit array
I found some mistake. The most important was in the while condition. Check this out.
public static void main(String[] args) {
// TODO code application logic here
Scanner input = new Scanner (System.in);
String fruitname = null;
String maxfruit = null;
int fruitSum = 0;
int totalSum = 0;
int max = 0;
System.out.print("Fruit name, " + "price in killogram, number of killogram sold: ");
while(!(fruitname = input.next()).equals("stop")){
fruitSum = input.nextInt() * input.nextInt();
totalSum += fruitSum;
if(fruitSum > max){
maxfruit = fruitname;
max = fruitSum;
}
}
System.out.println("the earned money of all fruits is " + totalSum);
System.out.println("fruit that achieved the largest profit is "+ maxfruit);
}
}
Oh it is reading it.
the problem is that it doesn't do what you want it to do.
the problems with the code I can see are this:
you are not storing the fruits quantities or prices anywhere, you need to store the values
in an array or something (maxFruit,MaxValue) to compare them later.
when you are reading the fruit values and a "stop" string is input the next step in your code is to wait for the price so it won't get out of the loop even if you input "stop", you need to restructure your scanner loop.
And if it is a beginner class it may be ok, but the code you are writing is not object oriented don't write the logic in the main.
You may want to learn to debug it is a very useful tool when you are learning to code, if you run this program in debug mode , you could see that the values are getting input and everything that is happening, Netbeans and Eclipse have very good debuggers and it would be worth to expend half an hour learning the basics of debugging It certainly helped me a lot when I was starting.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class FruitSells {
public static void main(String... args) {
BufferedReader bufer = new BufferedReader(new InputStreamReader(System.in));
try {
String str;
String[] inarr;
int sumMoney = 0;
do {
str = (String) bufer.readLine();
inarr = str.split(" ");
for(int i = 1; i < inarr.length; i += 3) {
sumMoney += Integer.parseInt(inarr[i]) * Integer.parseInt(inarr[i + 1]);
}
System.out.println(sumMoney);
sumMoney = 0;
} while (!str.equals("stop"));
} catch(IOException ex) {
System.out.println("Problems with bufer.readLine()");
}
}
}
something like this you can modernize it.sorry for eng i can not speak))and write correctly of course))

Categories

Resources