2016-12-18 2 views
-1

Основной класс:Выход показывает ноль, переменная не сохраняет значение

package tdm; 

import java.util.Scanner; 

/** 
* 
* @author abbas 
*/ 
public class TDM { 

    public static void main(String[] args) { 
     Scanner input = new Scanner(System.in); 
     System.out.println("** WHAT DO YOU WANT TO FIND? **"); 
     System.out.println("1. (A) Duration of each input slot, (B) Duration of each output slot and (C) Duration of each frame"); 
     System.out.println("2. (A) Input bit duration, (B) Output bit duration, (C) Output bit rate and (D) Output frame rate"); 
     System.out.println("3. (A) Duration of bit before multiplexing, (B) The transmission rate of the link, (C) The duration of a time slot and (D) The duration of a frame"); 
     System.out.println("4. Find everything!!"); 

     int choice; 
     System.out.println(); 
     System.out.print("Enter your choice: "); 
     choice = input.nextInt(); 

     switch (choice) { 
      case 1: { 
       Ex1 ex1 = new Ex1(); 
       ex1.calculateEx1(); 
       break; 
      } 
     } 

    } 

} 

EX1, класс

/* 
* To change this license header, choose License Headers in Project Properties. 
* To change this template file, choose Tools | Templates 
* and open the template in the editor. 
*/ 
package tdm; 

import java.util.Scanner; 

/** 
* 
* @author abbas 
*/ 
public class Ex1 { 

    public void calculateEx1() { 
     Scanner input = new Scanner(System.in); 
     int connectionsNum, dataRate, bitMultiplexed; 
     System.out.print("Enter number of connections: "); 
     connectionsNum = input.nextInt(); 
     System.out.print("Enter the data rate (Kbps) for each connection: "); 
     dataRate = input.nextInt(); 
     System.out.print("Enter number of bit(s)"); 
     bitMultiplexed = input.nextInt(); 
     System.out.println("** Your question is **"); 
     System.out.println("The data rate for each one of the " + connectionsNum 
       + " connections is " + dataRate + " Kbps. If " + bitMultiplexed 
       + " bit at time is multiplexed, what is (A) The duration of each" 
       + " input slot, (B) duration of each output slot and (C) duration " 
       + "of each frame"); 

     System.out.println("** The answer is **"); 
     int inputSlot = (bitMultiplexed/(dataRate * 1000)); 
     int outputSlot = ((1/connectionsNum) * inputSlot); 
     int frameDuration = (connectionsNum * outputSlot); 
     System.out.println(inputSlot); 
     System.out.println(outputSlot); 
     System.out.println(frameDuration); 

    } 

} 

Выход:

run: 
** WHAT DO YOU WANT TO FIND? ** 
1. (A) Duration of each input slot, (B) Duration of each output slot and (C) Duration of each frame 
2. (A) Input bit duration, (B) Output bit duration, (C) Output bit rate and (D) Output frame rate 
3. (A) Duration of bit before multiplexing, (B) The transmission rate of the link, (C) The duration of a time slot and (D) The duration of a frame 
4. Find everything!! 

Enter your choice: 1 
Enter number of connections: 3 
Enter the data rate (Kbps) for each connection: 1 
Enter number of bit(s): 1 
** Your question is ** 
The data rate for each one of the 3 connections is 1 Kbps. If 1 bit at time is multiplexed, what is (A) The duration of each input slot, (B) duration of each output slot and (C) duration of each frame 
** The answer is ** 
0 
0 
0 
BUILD SUCCESSFUL (total time: 14 seconds) 

Как вы можете видеть , три переменные inputSlot, outputSlot и frameDuration должны сохранять результат выражения. Но, как вы можете видеть на выходе, он показывает 0. Я думаю, это странно! Это первый случай, когда подобное случается со мной.

Я полагаю, что это небольшая проблема, но я не могу понять, что это такое !!

+0

Если вы используете IDE, используйте свой отладчик и установите некоторые точки останова. Если вы все еще не можете найти проблему, сделайте [mcve]. – 4castle

+0

Вы делите целые числа. '(bitMultiplexed/(dataRate * 1000)' ... Если 'dataRate * 1000> битMultiplexed', вы получите 0. –

+1

измените int на double. Может быть, что-то вроде 0,589 или около того, и оно отображает только часть int –

ответ

1

Переменные должны быть поплавками вместо целых. Целые числа могут хранить только целые числа в качестве имени sais. Поплавки могут хранить точечные нуферы, такие как 0,0002. Если u разделит int 20 на 11 и сохранит это как int, то в результате Java поместит 1. Поэтому, если ваш результат равен 1.9, он равен 1.0 как int. Это проблема здесь. Похоже, что этот

float inputSlot = (bitMultiplexed/(dataRate * 1000)); 
float outputSlot = ((1/connectionsNum) * inputSlot); 
int frameDuration = (connectionsNum * outputSlot); 
System.out.println(inputSlot); 
System.out.println(outputSlot); 
System.out.println(frameDuration); 

Если у вас есть вопросы спрашивайте меня :)

1
Enter the data rate (Kbps) for each connection: 1 

Хорошо, поэтому dataRate = 1.

Enter number of bit(s): 1 

И bitMultiplexed = 1.

System.out.println(1/(1000 * 1)); // 0 

Нужно, например, бросить на поплавок/двойной.

System.out.println(1/(1000.0 * 1)) // 0.001 
1

Как вы предлагаете программу/ответ.

inputSlot = 1/10000 = 0; 
output = (1/3)*0 = 0; 
frameDuration = 3 * 0 = 0; 

Поскольку это int. Он разделит десятичную часть. Используйте BigDecimal или double для этой цели

1

Проблема возникает из-за этих 3-х полей инициализируется, как Интс. Если вы сделаете их вдвойне, ваша проблема будет решена, потому что, когда вы объявляете их как int, она займет целую часть. Так, например, если у вас есть 0.588, это займет всего 0, что и происходит сейчас.

int inputSlot = (bitMultiplexed/(dataRate * 1000)); 
     int outputSlot = ((1/connectionsNum) * inputSlot); 
     int frameDuration = (connectionsNum * outputSlot); 

Чтобы решить эту проблему, необходимо изменить int к double.