I wanted to program a little Program that generates an addition task with 4 random numbers with measurements, like 45mm+34dm+ and so on....
The second function is: when the user enters the right solution, in mm measurements in the console, the program should print out: "right". But on the second function lies the problem. Something doesn't work on the if statement I wrote for this function.
Here is the Code:
package Uebungen;
import java.util.Scanner;
import sun.applet.Main;
import java.util.Random;
public class AvuG {
// Programmstart
public static void main(String[] args) {
// Declarationen
Scanner scn= new Scanner(System.in);
Random rG = new Random();
int[] numbers = new int[4];
int[] measurments = new int[4];
//Fills Array with four Random numbers for future measurment generation
for (int i = 0; i < maßEinheiten.length; i++) {
measurments[i] = rG.nextInt(4);
}
// Fills Array with four random numbers
for (int i = 0; i < numbers.length; i++) {
numbers[i] = rG.nextInt(99);
}
// Prints out 4 numbers with measurments
for (int i = 0; i < numbers.length; i++) {
if (i == numbers.length - 1) {
System.out.print(data[i] + checkInput(measurments[i]));
} else {
System.out.print(data[i] + checkInput(measurments[i]) + " + ");
}
}
//Calculates Solution of the calculation in measure mm in the Background for future use.
for (int i = 0; i < measurments.length; i++) {
switch(measurments[i]) {
case 1:
result += numbers[i];
break;
case 2:
result += numbers[i] * 10;
break;
case 3:
result += numbers[i] * 1000;
break;
case 0:
result += numbers[i] * 100;
break;
}
}
// Solution of the calculation, so you dont have to calculate when you want to investigate if its working.
System.out.println("");
System.out.println(result + "mm");
// *** Here lies the Problem. If the Solution is right, it should print out: "Right".
int nutzereingabe2 = scn.nextInt();
String nutzerEingabe = scn.next();
String nutzerEingabe3 = nutzereingabe2 + nutzerEingabe;
if ( nutzerEingabe3 == (result+"mm")){
System.out.println(result + "mm");
}
}
// Measurment Generator
private static String checkInput(int i) {
String result = "";
switch (i) {
case 1:
result = "mm";
break;
case 2:
result = "cm";
break;
case 3:
result = "m";
break;
case 0:
result = "dm";
break;
default:
result = "Error";
}
return result;
}
}
Related
This is the code I have, but I want it to be able to roll the dice based on the number of trials the user inputs and then display the frequencies of each face.
This code isn't working as I would expect.
Also I would like to change the switch cases to if and else if statements, if anybody could help me out with that would be amazing, I've been working on this for a while now.
import java.util.Random;
import java.util.Scanner;
public class DieRoll {
public static void main(String[] args) {
// TODO Auto-generated method stub
Random randomNumbers = new Random();
int one=0;
int two=0;
int three=0;
int four=0;
int five=0;
int six=0;
int trials;
int face;
System.out.println("Please enter the number of trials");
Scanner scan= new Scanner (System.in);
trials= scan.nextInt();
for(int rolls= 1; rolls==trials; rolls++);{
face= randomNumbers.nextInt(6) + 1;
// determine roll value 1-6 and increment appropriate counter
switch ( face )
{
case 1:
++one; // increment the 1s counter
break;
case 2:
++two; // increment the 2s counter
break;
case 3:
++three; // increment the 3s counter
break;
case 4:
++four; // increment the 4s counter
break;
case 5:
++five; // increment the 5s counter
break;
case 6:
++six; // increment the 6s counter
break; // optional at end of switch
}
}
System.out.println( "Face\tFrequency" ); // output headers
System.out.printf( "1\t%d\n2\t%d\n3\t%d\n4\t%d\n5\t%d\n6\t%d\n",
one, two, three, four,
five, six );
scan.close();
}
}
In your for loop:
Remove the semicolon (;) just after the for(int rolls= 1; rolls==trials; rolls++) line.
Change:
for(int rolls= 1; rolls==trials; rolls++)
to:
for(int rolls= 1; rolls<=trials; rolls++)
As far as changing switch to if-else-if, not sure why you would want to do this, but simply write it as:
if(face == 1){
one++;
}
else if(face ==2){
two++;
}
and so on..
Please have a look at this:
public class Main {
private static final Random RANDOM_NUMBER_GENERATOR = new Random();
public static void main(String[] args) {
int numberOfTrials;
int[] facesFrequencies = new int[6];
System.out.println("Please enter the number of trials");
Scanner scanner = new Scanner(System.in);
numberOfTrials = scanner.nextInt();
scanner.close();
for (int numberOfRolls = 1; numberOfRolls <= numberOfTrials; numberOfRolls++) {
int face = rollDice();
if (face == 1) {
facesFrequencies[0] += 1;
} else if (face == 2) {
facesFrequencies[1] += 1;
} else if (face == 3) {
facesFrequencies[2] += 1;
} else if (face == 4) {
facesFrequencies[3] += 1;
} else if (face == 5) {
facesFrequencies[4] += 1;
} else if (face == 6) {
facesFrequencies[5] += 1;
}
}
System.out.println("Face\tFrequency");
for (int i = 0; i < facesFrequencies.length; i++) {
System.out.printf("%d\t\t%d%n", i, facesFrequencies[i]);
}
}
private static int rollDice() {
return RANDOM_NUMBER_GENERATOR.nextInt(6) + 1;
}
}
I've put the results (int one to int six) into an array. facesFrequencies[0] will be the same as int one.
The ; after for (...) is syntactically incorrect.
Switch statement is replaced with if statement.
I am working on a project for my programming class and I am having trouble with the BufferedReader. Here is the code. It will run fine but it is only reading every other line in my csv file. I think the issue is I have inFile = input.readLine in there twice but if I remove one of them the I get runtime errors.
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
import java.io.BufferedReader;
public class CrimeData {
public static void main(String[] args) throws FileNotFoundException {
BufferedReader input = new BufferedReader(new FileReader("crime.csv"));
String inFile;
try {
inFile = input.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int n = 0;
int year[] = new int[50], population[] = new int[50], violentCrime[] = new int[50];
double violentCrimeRate[] = new double[50];
int murderAndNonnegligentManslaughter[] = new int[50];
double murderAndNonnegligentManslaughterRate[] = new double[50];
int rape[] = new int[50];
double rapeRate[] = new double[50];
int robbery[] = new int[50];
double robberyRate[] = new double[50];
int aggravatedAssault[] = new int[50];
double aggravatedAssaultRate[] = new double[50];
int propertyCrime[] = new int[50];
double propertyCrimeRate[] = new double[50];
int burglary[] = new int[50];
double burglaryRate[] = new double[50];
int larcenyTheft[] = new int[50];
double larcenyTheftRate[] = new double[50];
int motorVehicleTheft[] = new int[50];
double motorVehicleTheftRate[] = new double[50];
try {
while ((inFile = input.readLine()) != null) {
String words[] = input.readLine().split(",");
year[n] = Integer.parseInt(words[0]);
population[n] = Integer.parseInt(words[1]);
violentCrime[n] = Integer.parseInt(words[2]);
violentCrimeRate[n] = Double.parseDouble(words[3]);
murderAndNonnegligentManslaughter[n] = Integer.parseInt(words[4]);
murderAndNonnegligentManslaughterRate[n] = Double.parseDouble(words[5]);
rape[n] = Integer.parseInt(words[6]);
rapeRate[n] = Double.parseDouble(words[7]);
robbery[n] = Integer.parseInt(words[8]);
robberyRate[n] = Double.parseDouble(words[9]);
aggravatedAssault[n] = Integer.parseInt(words[10]);
aggravatedAssaultRate[n] = Double.parseDouble(words[11]);
propertyCrime[n] = Integer.parseInt(words[12]);
propertyCrimeRate[n] = Double.parseDouble(words[13]);
burglary[n] = Integer.parseInt(words[14]);
burglaryRate[n] = Double.parseDouble(words[15]);
larcenyTheft[n] = Integer.parseInt(words[16]);
larcenyTheftRate[n] = Double.parseDouble(words[17]);
motorVehicleTheft[n] = Integer.parseInt(words[18]);
motorVehicleTheftRate[n] = Double.parseDouble(words[19]);
n++;
}
} catch (NumberFormatException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Scanner scan = new Scanner(System.in);
while (true) {
System.out.println("********** Welcome to the US Crime Statistical Application **************************");
System.out.println("Enter the number of the question you want answered. ");
System.out.println("1. What were the percentages in population growth for each consecutive year from 1994 – 2013?");
System.out.println("2. What year was the Murder rate the highest?");
System.out.println("3. What year was the Murder rate the lowest?");
System.out.println("4. What year was the Robbery rate the highest?");
System.out.println("5. What year was the Robbery rate the lowest?");
System.out.println("6. What was the total percentage change in Motor Vehicle Theft between 1998 and 2012?");
System.out.println("7. What was [enter your first unique statistic here]?");
System.out.println("8. What was [enter your second unique statistic here]?");
System.out.println("9. Quit the program");
System.out.println("Enter your selection: ");
int choice = scan.nextInt();
double low, high, percent;
int y;
switch (choice) {
case 1:
for (int i = 1; i < n; i++) {
percent = ((population[i] - population[i - 1]) / population[i - 1]) * 100;
System.out.println(
"Percentage of population growth during " + year[i - 1] + "-" + year[i] + " :" + percent);
}
break;
case 2:
high = murderAndNonnegligentManslaughter[0];
y = year[0];
for (int i = 1; i < n; i++) {
if (murderAndNonnegligentManslaughter[i] > high) {
high = murderAndNonnegligentManslaughter[i];
y = year[i];
}
}
System.out.println("The year has the highest Murder rate : " + y);
break;
case 3:
low = murderAndNonnegligentManslaughter[0];
y = year[0];
for (int i = 1; i < n; i++) {
if (murderAndNonnegligentManslaughter[i] < low) {
low = murderAndNonnegligentManslaughter[i];
y = year[i];
}
}
System.out.println("The year has the lowest Murder rate : " + y);
break;
case 4:
high = robberyRate[0];
y = year[0];
for (int i = 1; i < n; i++) {
if (robberyRate[i] > high) {
high = robberyRate[i];
y = year[i];
}
}
System.out.println("The year has the highest Robbery rate : " + y);
break;
case 5:
low = robberyRate[0];
y = year[0];
for (int i = 1; i < n; i++) {
if (robberyRate[i] < low) {
low = robberyRate[i];
y = year[i];
}
}
System.out.println("The year has the lowest Robbery rate : " + y);
break;
case 6:
double rateChange = 0;
rateChange = (motorVehicleTheft[19] - motorVehicleTheft[5]);
System.out.println(motorVehicleTheft);
case 7:
break;
case 8:
break;
case 9:
System.out.println("Thank you for using the Crime Database");
System.exit(0);
}
}
}
}
Your guess is absolutely correct.
This skips because the first condition in your while loop reads a line,
while((infile = input.readLine()) != null){
but you do not do anything with the read-in line.
Then the next time you call
input.readLine();
You read the next line, but you actually do something with the line.
For further reference, try looking at this thread:
Java: How to read a text file
.split() Method is NOT Allowed
I was got some help earlier from a helpful guy! I was just wondering if anyone could help me modify this a little bit more,
The code is meant for an assignment and It is based on the input from the scanner. It has two other classes but this is the one of interest.
The code is working at the moment, however The things that have to be input are things like **U5, D10** etc. That works fine. However I need the code to be able to read multiple String off one one line whilst seperating them like they are now. Like say for example **D10 U5 L4**, all from one line for just one player out of two. The code at the moment is not recognizing it as one line and instead if assigning the second typed thing to the second player.
Any tips?
Thanks
import java.util.Scanner;
class Asgn2
{
public static void main(String[] args)
{
Scanner scan = new Scanner (System.in);
Player me = new Player("Player1");
Player opponent = new Player("player2");
int startingLoop = 0;
String strA;
int turn =1;
System.out.print("How many turns will the game have: ");
int turnsInGame = scan.nextInt();
System.out.print("How many moves does each player have each turn: ");
int numberOfTurns = scan.nextInt();
for(int i = turnsInGame; startingLoop < i; startingLoop++)
{
System.out.print("Turn " + turn++ + "\n");
System.out.print("Player 1 what are your " + numberOfTurns + " move(s): ");
String userInput = scan.next();
System.out.print("Player 2 what are your " + numberOfTurns + " move(s): ");
String userInputOne = scan.next();
for (int j = 0; j < userInput.length() - 1; j++)
{
char letter = userInput.charAt(j);
String num = "";
for(int k= j + 1; k < userInput.length(); k++)
{
j++;
if(userInput.charAt(k)!=' ')
{
num+=userInput.charAt(k);
}
else
{
break;
}
}
int integer = Integer.parseInt(num + "");
strA = Character.toString(letter);
switch(strA) //For player oneChooses which value to add or subtract from based on what is input.
{
case "U":
me.move(moveSteps.UP , integer);
break;
case "D":
me.move(moveSteps.DOWN, integer);
break;
case "L":
me.move(moveSteps.LEFT, integer);
break;
case "R":
me.move(moveSteps.RIGHT, integer);
break;
}
//Player 2
for (int playerTwo = 0; playerTwo < userInputOne.length() - 1; playerTwo++)
{
char letterTwo = userInputOne.charAt(0);
String numTwo = "";
String strB = Character.toString(letterTwo);
for(int m= playerTwo + 1; m<userInput.length(); m++)
{
playerTwo++;
if(userInputOne.charAt(playerTwo)!=' ')
{
numTwo+=userInputOne.charAt(playerTwo);
}
else
{
break;
}
}
int stepsMoved = Integer.parseInt(numTwo + "");
switch(strB) //For player two
{
case "U":
opponent.move(moveSteps.UP , stepsMoved);
break;
case "D":
opponent.move(moveSteps.DOWN, stepsMoved);
break;
case "L":
opponent.move(moveSteps.LEFT, stepsMoved);
break;
case "R":
opponent.move(moveSteps.RIGHT, stepsMoved);
break;
}
}
}
System.out.print(me);
System.out.print(opponent);
}
}
}
Once you assign the input to a String, use the .split() method to split the string into an array. To use the .split(), put in the character you want to split it with. In this case a space. For example use this for your current project: .split(" "). Once you split it, you can access it just like any array.
Update:
first use the .nextLine() and assign it to a temporary string variable. Then
you can create another scanner and put a string in. For example:
Scanner sc = new Scanner(YOUR TEMPORARY VARIABLE);
you can now use the .next() to get individual strings.
Here is the Asgn2 class
import java.util.Scanner;
public class Asgn2 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("What is your name player 1: ");
String p1name = scan.nextLine();
System.out.print("What is your name player 2: ");
String p2name = scan.nextLine();
Player p1 = new Player(p1name);
Player p2 = new Player(p2name);
System.out.print("How many turns will the game have: ");
int numTurns = scan.nextInt();
System.out.print("How many moves does each player have each turn: ");
int numMoves = scan.nextInt();
for (int turn = 1; turn <= numTurns; turn++) {
System.out.println("----------------");
System.out.println("Turn number " + turn);
System.out.println("----------------");
for (int player = 1; player <= 2; player++) {
System.out.print("Player " + player + " what are your " + numMoves + " move(s): ");
for(int move=1;move<=numMoves;move++){
String currMove = scan.next();//splits at space;
char dir = currMove.charAt(0);//gets dir
String temp="";
for(int index=1;index<currMove.length();index++){
temp+=currMove.charAt(index);
}
int dist = Integer.parseInt(temp);
if(player==1){
p1.move(dir, dist);
}else if(player==2){
p2.move(dir, dist);
}
}
System.out.println("Player 1 is at " + p1.getPos() + " and Player 2 is at " + p2.getPos());
System.out.println();
}
}
}
}
And here is the Player class
public class Player {
private String name;
private int locX = 0;
private int locY = 0;
public Player(String name) {
this.name = name;
}
public void move(char dir, int numSteps) {
switch (dir) {
case 'U':
locY += numSteps;
break;
case 'D':
locY -= numSteps;
break;
case 'L':
locX -= numSteps;
break;
case 'R':
locX += numSteps;
break;
}
}
public String getPos() {
return "(" + locX + ", " + locY + ")";
}
public String getName() {
return name;
}
}
And before anyone goes and says that posting blocks of code does not help OP, I am in a chatroom with him in which I explain this stuff, so dont hate :)
call the method .nextLine() instead of .next(). I think that should solve your problem.
I am creating a program that converts roman numeral input to it's integer value and every time I run the program I get an error that says,
"Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1
at java.lang.String.charAt(String.java:646)
at romannumeralconverter.RomanNumeralConverter.convert(RomanNumeralConverter.java:20)
at romannumeralconverter.RomanNumeralConverter.romanInput(RomanNumeralConverter.java:68)
at romannumeralconverter.RomanNumeralConverter.printValue(RomanNumeralConverter.java:72)
at romannumeralconverter.RomanNumeralConverter.main(RomanNumeralConverter.java:77)
Java Result: 1"
Now I am new to programming so I don't know what this means exactly. I am guessing my conversion algorithm is wrong in which the roman numeral entered is not read by the loop. Here is what I have:
public class RomanNumeralConverter {
public String getUserInput() {
Scanner numberInput = new Scanner (System.in);
System.out.print("Enter a roman numeral in uppercase: ");
String userInput = numberInput.next();
numberInput.close();
return userInput;
}
public int convert (String userInput) {
int result = 0;
int subtractamount = 0;
int x = userInput.length();
while(x != 0) {
char romanConvert = userInput.charAt(x);
if(x >= 1) {
if(convertChar(romanConvert) >= convertChar(userInput.charAt(x - 1))) {
subtractamount += convertChar(userInput.charAt(x - 1));
}
}
result += convertChar(romanConvert);
x--;
}
result -= subtractamount;
return result;
}
public static char convertChar(char value) {
char result;
switch (value) {
case 'I':
result = 1;
break;
case 'V':
result = 5;
break;
case 'X':
result = 10;
break;
case 'L':
result = 50;
break;
case 'C':
result = 100;
break;
case 'D':
result = 500;
break;
case 'M':
result = 1000;
break;
default:
System.out.println("Invalid character!");
result = 0;
break;
}
return result;
}
public int romanInput() {
return convert(getUserInput());
}
public void printValue() {
System.out.println(romanInput());
}
public static void main (String[] args) {
new RomanNumeralConverter().printValue();
}
}
If my algorithm is wrong, does anyone know how to fix it?
change userInput.charAt(x); to userInput.charAt(x - 1);
charAt starts with index 0 to length -1
or int x = userInput.length() - 1;
#nd issue, everything coming out as 0
You are actually using uppercase characters in switch statement.
so just add below statement,in the starting of your function convert(String userInput)
userInput = userInput.toUpperCase(); // converts user input to uppercase , even if its is already or not.
code
public int convert(String userInput) {
userInput = userInput.toUpperCase();
int result = 0;
int subtractamount = 0;
int x = userInput.length() - 1;
while (x != 0) {
char romanConvert = userInput.charAt(x);
if (x >= 1) {
if (convertChar(romanConvert) >= convertChar(userInput.charAt(x - 1))) {
subtractamount += convertChar(userInput.charAt(x - 1));
}
}
result += convertChar(romanConvert);
x--;
}
result -= subtractamount;
return result;
}
output
Enter a roman numeral in uppercase: adig
Invalid character!
Invalid character!
Invalid character!
Invalid character!
501
You should start with
int x = userInput.length() - 1;
The last character in a string is at the index - (length-of-string - 1), not length-of-string.
Input from the Java commandline: "4 + 6 + 5 - 5".
Wanted outcome: "is 10".
Actual outcome: "is 5".
class Calculator
{
int v_in1, v_in2, v_in3, v_in4, v_answer, result;
String v_sign1, v_sign2, v_sign3;
public Calculator()
{
}
public void count(String[] args)
{
for(int i = 0; i < args.length; i++)
{
//System.out.print(args[i]+ " ");
if(i == 0 || i % 2 == 0)
{
v_in1 = Integer.parseInt(args[i]);
//System.out.print(v_in1 + " ");
}
switch(args[i])
{
case "+": {
v_answer += v_in1;
break;
}
case "-": {
v_answer -= v_in1;
break;
}
}
}
System.out.print("is " + v_answer);
}
}
There might be some additional problems e.g too many variable declared etc, but what I'm concerned about it the for- if- switch part, I'm unable to pin- point the problem.
Thank you :)
The problem is that you are applying the operation to the previous number, not to the next to come. Instead you should memorize the operator and update the result when you see a number, e.g. like this:
int sign = +1, result = 0;
for (String arg : args) {
switch (arg) {
case "+":
sign = +1;
break;
case "-":
sign = -1;
break;
default:
result += sign * Integer.parseInt(arg);
}
}
This is happening because your last integer wont be taken into account as it is just stored in v_in1, but since there is no +,- so it doesnt get added or subtracted. Try this:
for(int i = 0; i < args.length; i++)
{
//System.out.print(args[i]+ " ");
if(i == 0 || i % 2 == 0)
{
v_in1 = Integer.parseInt(args[i]);
//System.out.print(v_in1 + " ");
}
switch(args[i])
{
case "+":
{
v_answer = v_in1 + Integer.parseInt(args[i+1]) + v_answer;
i++;
break;
}
case "-":
{
v_answer = v_in1 - Integer.parseInt(args[i+1]) + v_answer;
i++;
break;
}
}
}
I do not know all requirements for this task, but I recommend to convert the whole expression to postfix notation, then parse it using stack to evaluate the result.
I took a look at your method, and I recommend you simplify your code (something like this for long count(String[] args))
long result = 0; // Note, this shadows your Object's result. I'm not sure why you
// had hard-coded fields like that. I don't think you need them.
// Also, this returns a long.
boolean negative = false;
for (String arg : args) {
String oper = arg.trim();
if (oper.equals("+")) { // Is it a plus sign?
negative = false;
} else if (oper.equals("-")) { // Is it a minus sign?
negative = !negative; // - a negative value is addition
} else {
try {
int i = Integer.parseInt(oper); // Parse the integer
if (negative) {
i = -i;
negative = false;
}
result += i; // add the result
} catch (NumberFormatException nfe) {
System.err.println(oper + " is not +, - or a number");
}
}
}
return result;
This is what worked in the exercise.
class Calculator
{
int v_answer = 0;
int v_in1 = 0;
public Calculator()
{
}
public void count(String args[])
{
System.out.println();
System.out.print("Result of the calculation ");
for(int i = 0; i < args.length; i++)
{
System.out.print(args[i]+ " ");
if(i % 2 == 0)
{
v_in1 = Integer.parseInt(args[i]);
}
if(i == 0)
{
v_answer += Integer.parseInt(args[0]);
}
if(args[i].equals("+"))
{
v_answer += Integer.parseInt(args[i+1]);
}
else if(args[i].equals("-"))
{
v_answer -= Integer.parseInt(args[i+1]);
}
}
System.out.print("is " + v_answer);
System.out.println();
}
}