2014 dxdy logo

Научный форум dxdy

Математика, Физика, Computer Science, Machine Learning, LaTeX, Механика и Техника, Химия,
Биология и Медицина, Экономика и Финансовая Математика, Гуманитарные науки




Начать новую тему Ответить на тему
 
 Java: Бензин калькулятор
Сообщение07.03.2013, 03:47 


29/12/10
33
Privet!

This program accepts a user's destination and the distance (in miles). It then calculates the amount petrol required to reach that destination.

The program below does that but it crashes whenever the user enters something other than an integer.
I tried fixing it with an if statement. It doesn't work.

How do I fix the if...else statement in this code?

Код:
import java.util.*;

public class Location
{
public static void main(String args[])
{
double Gallons;
double LITERS_of_PETROL;
final double LitreConversion = 3.78541178;
final int MPG = 23;
int AmtMiles = 100; //Default Miles value, for distance travelled

Scanner stdin = new Scanner(System.in);
Scanner keyboard;
keyboard = new Scanner(System.in);

System.out.println("Where do you travel to?: ");
String Destination = stdin.next();

System.out.println(Destination + " is how many miles away?");
String Miles = stdin.next();
AmtMiles = Integer.parseInt(Miles);
System.out.printf("\n%s is %d miles away. You will need %.2f gallons, or %.4f liters of fuel.", Destination, AmtMiles, (AmtMiles/23.0),(3.78541178*AmtMiles/23.0));

if (keyboard.hasNextInt())
System.out.printf("\n%s is %d miles away. You will need %.2f gallons, or %.4f liters of fuel.", Destination, AmtMiles, (AmtMiles/23.0),(3.78541178*AmtMiles/23.0));

else
{
System.out.println(Miles + "not valid. I will use 100 for the number of miles.");
}
}


I can do it with a try...catch block, but I want to solve the problem with an if...else statment.
Код:
try
{
NoofMiles = Integer.parseInt(Miles);
}
catch (NumberFormatException nfe)
{
System.out.println(Miles + "not valid. I will use 100 for the number of miles.");
}
System.out.printf("\n%s is %d miles away. You will need %.2f gallons, or %.4f liters of fuel.",Destination,NoofMiles,(NoofMiles/23.0),(3.78541178* NoofMiles/23.0));



Заранее благодарю!

 Профиль  
                  
 
 Re: Java: Бензин калькулятор
Сообщение07.03.2013, 08:53 
Заслуженный участник
Аватара пользователя


06/10/08
6422
You can check that every character in Miles is a decimal digit. To accept negative numbers, you can check that all the characters are decimal digits except the first one which may be a minus sign.

 Профиль  
                  
 
 Re: Java: Бензин калькулятор
Сообщение07.03.2013, 09:45 


29/12/10
33
Xaositect в сообщении #692057 писал(а):
You can check that every character in Miles is a decimal digit. To accept negative numbers, you can check that all the characters are decimal digits except the first one which may be a minus sign.

Thank you, Xaositect!
I don't know how to check for decimals, however, I do know how to check for integers.
I used
Код:
keyboard.hasNextInt()
to check for an integer, but I don't understand why the program doesn't evaluate my if statement?!

I simply wish for the program to not crash when the user enters a character or non-integer at this point:
Код:
System.out.println(Destination + " is how many miles away?");


If the user does enter some unwanted value, the program should just use the default value of 100 and evaluate to:
Код:
System.out.println(Miles + "not valid. I will use 100 for the number of miles.");

 Профиль  
                  
 
 Re: Java: Бензин калькулятор
Сообщение07.03.2013, 09:58 
Заслуженный участник
Аватара пользователя


06/10/08
6422
I suppose if you want to use hasNextInt, you should first check keyboard.hasNextInt() and then read data using keyboard.nextInt()


CrypticMath в сообщении #692073 писал(а):
I don't know how to check for decimals, however
Something like that:
Код:
bool good = true;
for (char c : Miles.toCharArray()) { good = good && c >= '0' && c <= '9'}
if (good) {
//do some work
} else {
//error
}

 Профиль  
                  
 
 Re: Java: Бензин калькулятор
Сообщение07.03.2013, 11:16 


29/12/10
33
Xaositect писал(а):
I suppose if you want to use hasNextInt, you should first check keyboard.hasNextInt() and then read data using keyboard.nextInt()


Do you mean this, (placing next(); in the if statement check for the correct value entered:
Код:
if (keyboard.hasNextInt())
next();
System.out.printf("\n%s is %d miles away. You will need %.2f gallons, or %.4f liters of fuel.", Destination, AmtMiles, (AmtMiles/23.0),(3.78541178*AmtMiles/23.0));

else
{
System.out.println(Miles + "not valid. I will use 100 for the number of miles.");
}

 Профиль  
                  
 
 Re: Java: Бензин калькулятор
Сообщение07.03.2013, 11:48 
Заслуженный участник
Аватара пользователя


06/10/08
6422
Yes, but not just next(); of course.

 Профиль  
                  
 
 Re: Java: Бензин калькулятор
Сообщение07.03.2013, 12:26 


29/12/10
33
Xaositect в сообщении #692111 писал(а):
Yes, but not just next(); of course.


I tried Miles = keyboard.next();:
Код:
if (keyboard.hasNextInt())
{
Miles = keyboard.next();
System.out.printf("\n%s is %d miles away. You will need %.2f gallons, or %.4f liters of fuel.", Destination, AmtMiles, (AmtMiles/23.0),(3.78541178*AmtMiles/23.0));
}


When I enter a character, say 'q', it gives the following error and points to AmtMiles = Integer.parseInt(Miles);:
Код:
Exception in thread "main" java.lang.NumberFormatException: For input string: "q"
   at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
   at java.lang.Integer.parseInt(Integer.java:492)
   at java.lang.Integer.parseInt(Integer.java:527)
   at Location.main(Location.java:22)


I don't know where to put the code to check for integer -- I've experimented everywhere.

 Профиль  
                  
 
 Re: Java: Бензин калькулятор
Сообщение07.03.2013, 12:32 
Заслуженный участник
Аватара пользователя


06/10/08
6422
Please post the entire program.

 Профиль  
                  
 
 Re: Java: Бензин калькулятор
Сообщение07.03.2013, 12:52 
Заслуженный участник


09/09/10
3729
Код:
        if (stdin.hasNextInt())
        {
            AmtMiles = stdin.nextInt();
        }
        else
        {
            String Miles = stdin.next();
            System.out.println(Miles + " not valid. I will use 100 for the number of miles.");
        }

And why do you have keyboard and stdin both scanning System.in? That leads to nasty bugs.

 Профиль  
                  
 
 Re: Java: Бензин калькулятор
Сообщение07.03.2013, 12:54 


29/12/10
33
Xaositect в сообщении #692131 писал(а):
Please post the entire program.


Код:
import java.util.*;

public class Location
{
public static void main(String args[])
{
double Gallons;
double LITERS_of_PETROL;
final double LitreConversion = 3.78541178;
final int MPG = 23;
int AmtMiles = 100; //Default Miles value, for distance travelled

Scanner stdin = new Scanner(System.in);
Scanner keyboard;
keyboard = new Scanner(System.in);

System.out.println("Where do you travel to?: ");
String Destination = stdin.next();

System.out.println(Destination + " is how many miles away?");
String Miles = stdin.next();
AmtMiles = Integer.parseInt(Miles);
System.out.printf("\n%s is %d miles away. You will need %.2f gallons, or %.4f liters of fuel.", Destination, AmtMiles, (AmtMiles/23.0),(3.78541178*AmtMiles/23.0));

if (keyboard.hasNextInt())
{
Miles = keyboard.next();
System.out.printf("\n%s is %d miles away. You will need %.2f gallons, or %.4f liters of fuel.", Destination, AmtMiles, (AmtMiles/23.0),(3.78541178*AmtMiles/23.0));
}

else
{
System.out.println(Miles + "not valid. I will use 100 for the number of miles.");
}
}
}

 Профиль  
                  
 
 Re: Java: Бензин калькулятор
Сообщение07.03.2013, 13:10 
Заслуженный участник
Аватара пользователя


06/10/08
6422
The input is read before hasNextInt check is done.

Delete lines 21-23 and change Miles = keyboard.next(); to AmtMiles = keyboard.nextInt();

 Профиль  
                  
 
 Re: Java: Бензин калькулятор
Сообщение08.03.2013, 05:34 


29/12/10
33
Joker_vD в сообщении #692142 писал(а):
Код:
        if (stdin.hasNextInt())
        {
            AmtMiles = stdin.nextInt();
        }
        else
        {
            String Miles = stdin.next();
            System.out.println(Miles + " not valid. I will use 100 for the number of miles.");
        }


Thank you.

That piece of code works.
I tried something similar and got an error and I gave up on that route.

So the lesson is: I should have simply placed the integer check inside of the body of the if statement. If that fails, the else statement checks and moves onto the next line. Am I correct?

You have enlightened me here:
Цитата:
And why do you have keyboard and stdin both scanning System.in? That leads to nasty bugs.

I used different scan methods because of errors and I thought it a good idea to change one.
Could you give me an outline as to why it leads to bugs?
I'll do some self-research afterwards.

-- Пт мар 08, 2013 05:55:25 --

Xaositect в сообщении #692156 писал(а):
The input is read before hasNextInt check is done.

Delete lines 21-23 and change Miles = keyboard.next(); to AmtMiles = keyboard.nextInt();


Код:
Scanner stdin = new Scanner(System.in);
Scanner keyboard = new Scanner(System.in);

System.out.println("Where do you travel to?: ");
String Destination = stdin.next();
System.out.println(Destination + " is how many miles away?");

if (keyboard.hasNextInt())
{
AmtMiles = keyboard.nextInt();
System.out.printf("\n%s is %d miles away. You will need %.2f gallons, or %.4f liters of fuel.", Destination, AmtMiles, (AmtMiles/23.0),(3.78541178*AmtMiles/23.0));
}

else
{
String Miles = stdin.next();
System.out.println(Miles + "not valid. I will use 100 for the number of miles.");
}
}

This works fine when the expected inputs are entered. Otherwise, it accepts outputs nothing.

 Профиль  
                  
Показать сообщения за:  Поле сортировки  
Начать новую тему Ответить на тему  [ Сообщений: 12 ] 

Модераторы: Karan, Toucan, PAV, maxal, Супермодераторы



Кто сейчас на конференции

Сейчас этот форум просматривают: нет зарегистрированных пользователей


Вы не можете начинать темы
Вы не можете отвечать на сообщения
Вы не можете редактировать свои сообщения
Вы не можете удалять свои сообщения
Вы не можете добавлять вложения

Найти:
Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group